UNPKG

5.49 MBJavaScriptView Raw
1/*! *****************************************************************************
2Copyright (c) Microsoft Corporation. All rights reserved.
3Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4this file except in compliance with the License. You may obtain a copy of the
5License at http://www.apache.org/licenses/LICENSE-2.0
6
7THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10MERCHANTABLITY OR NON-INFRINGEMENT.
11
12See the Apache Version 2.0 License for specific language governing permissions
13and limitations under the License.
14***************************************************************************** */
15
16
17"use strict";
18var __assign = (this && this.__assign) || function () {
19 __assign = Object.assign || function(t) {
20 for (var s, i = 1, n = arguments.length; i < n; i++) {
21 s = arguments[i];
22 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
23 t[p] = s[p];
24 }
25 return t;
26 };
27 return __assign.apply(this, arguments);
28};
29var __generator = (this && this.__generator) || function (thisArg, body) {
30 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
31 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
32 function verb(n) { return function (v) { return step([n, v]); }; }
33 function step(op) {
34 if (f) throw new TypeError("Generator is already executing.");
35 while (_) try {
36 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;
37 if (y = 0, t) op = [op[0] & 2, t.value];
38 switch (op[0]) {
39 case 0: case 1: t = op; break;
40 case 4: _.label++; return { value: op[1], done: false };
41 case 5: _.label++; y = op[1]; op = [0]; continue;
42 case 7: op = _.ops.pop(); _.trys.pop(); continue;
43 default:
44 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
45 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
46 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
47 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
48 if (t[2]) _.ops.pop();
49 _.trys.pop(); continue;
50 }
51 op = body.call(thisArg, _);
52 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
53 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
54 }
55};
56var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
57 if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
58 return cooked;
59};
60var __extends = (this && this.__extends) || (function () {
61 var extendStatics = function (d, b) {
62 extendStatics = Object.setPrototypeOf ||
63 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
64 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
65 return extendStatics(d, b);
66 };
67 return function (d, b) {
68 extendStatics(d, b);
69 function __() { this.constructor = d; }
70 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
71 };
72})();
73var ts;
74(function (ts) {
75 // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values.
76 // If changing the text in this section, be sure to test `configureNightly` too.
77 ts.versionMajorMinor = "3.4";
78 /** The version of the TypeScript compiler release */
79 ts.version = ts.versionMajorMinor + ".5";
80})(ts || (ts = {}));
81(function (ts) {
82 /* @internal */
83 var Comparison;
84 (function (Comparison) {
85 Comparison[Comparison["LessThan"] = -1] = "LessThan";
86 Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
87 Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
88 })(Comparison = ts.Comparison || (ts.Comparison = {}));
89})(ts || (ts = {}));
90/* @internal */
91(function (ts) {
92 ts.emptyArray = [];
93 /** Create a MapLike with good performance. */
94 function createDictionaryObject() {
95 var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword
96 // Using 'delete' on an object causes V8 to put the object in dictionary mode.
97 // This disables creation of hidden classes, which are expensive when an object is
98 // constantly changing shape.
99 map.__ = undefined;
100 delete map.__;
101 return map;
102 }
103 /** Create a new map. If a template object is provided, the map will copy entries from it. */
104 function createMap() {
105 return new ts.MapCtr();
106 }
107 ts.createMap = createMap;
108 function createMapFromEntries(entries) {
109 var map = createMap();
110 for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
111 var _a = entries_1[_i], key = _a[0], value = _a[1];
112 map.set(key, value);
113 }
114 return map;
115 }
116 ts.createMapFromEntries = createMapFromEntries;
117 function createMapFromTemplate(template) {
118 var map = new ts.MapCtr();
119 // Copies keys/values from template. Note that for..in will not throw if
120 // template is undefined, and instead will just exit the loop.
121 for (var key in template) {
122 if (hasOwnProperty.call(template, key)) {
123 map.set(key, template[key]);
124 }
125 }
126 return map;
127 }
128 ts.createMapFromTemplate = createMapFromTemplate;
129 // Internet Explorer's Map doesn't support iteration, so don't use it.
130 // tslint:disable-next-line no-in-operator variable-name
131 ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap();
132 // Keep the class inside a function so it doesn't get compiled if it's not used.
133 function shimMap() {
134 var MapIterator = /** @class */ (function () {
135 function MapIterator(currentEntry, selector) {
136 this.currentEntry = currentEntry;
137 this.selector = selector;
138 }
139 MapIterator.prototype.next = function () {
140 // Navigate to the next entry.
141 while (this.currentEntry) {
142 var skipNext = !!this.currentEntry.skipNext;
143 this.currentEntry = this.currentEntry.nextEntry;
144 if (!skipNext) {
145 break;
146 }
147 }
148 if (this.currentEntry) {
149 return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
150 }
151 else {
152 return { value: undefined, done: true };
153 }
154 };
155 return MapIterator;
156 }());
157 return /** @class */ (function () {
158 function class_1() {
159 this.data = createDictionaryObject();
160 this.size = 0;
161 // Create a first (stub) map entry that will not contain a key
162 // and value but serves as starting point for iterators.
163 this.firstEntry = {};
164 // When the map is empty, the last entry is the same as the
165 // first one.
166 this.lastEntry = this.firstEntry;
167 }
168 class_1.prototype.get = function (key) {
169 var entry = this.data[key];
170 return entry && entry.value;
171 };
172 class_1.prototype.set = function (key, value) {
173 if (!this.has(key)) {
174 this.size++;
175 // Create a new entry that will be appended at the
176 // end of the linked list.
177 var newEntry = {
178 key: key,
179 value: value
180 };
181 this.data[key] = newEntry;
182 // Adjust the references.
183 var previousLastEntry = this.lastEntry;
184 previousLastEntry.nextEntry = newEntry;
185 newEntry.previousEntry = previousLastEntry;
186 this.lastEntry = newEntry;
187 }
188 else {
189 this.data[key].value = value;
190 }
191 return this;
192 };
193 class_1.prototype.has = function (key) {
194 // tslint:disable-next-line:no-in-operator
195 return key in this.data;
196 };
197 class_1.prototype.delete = function (key) {
198 if (this.has(key)) {
199 this.size--;
200 var entry = this.data[key];
201 delete this.data[key];
202 // Adjust the linked list references of the neighbor entries.
203 var previousEntry = entry.previousEntry;
204 previousEntry.nextEntry = entry.nextEntry;
205 if (entry.nextEntry) {
206 entry.nextEntry.previousEntry = previousEntry;
207 }
208 // When the deleted entry was the last one, we need to
209 // adust the lastEntry reference.
210 if (this.lastEntry === entry) {
211 this.lastEntry = previousEntry;
212 }
213 // Adjust the forward reference of the deleted entry
214 // in case an iterator still references it. This allows us
215 // to throw away the entry, but when an active iterator
216 // (which points to the current entry) continues, it will
217 // navigate to the entry that originally came before the
218 // current one and skip it.
219 entry.previousEntry = undefined;
220 entry.nextEntry = previousEntry;
221 entry.skipNext = true;
222 return true;
223 }
224 return false;
225 };
226 class_1.prototype.clear = function () {
227 this.data = createDictionaryObject();
228 this.size = 0;
229 // Reset the linked list. Note that we must adjust the forward
230 // references of the deleted entries to ensure iterators stuck
231 // in the middle of the list don't continue with deleted entries,
232 // but can continue with new entries added after the clear()
233 // operation.
234 var firstEntry = this.firstEntry;
235 var currentEntry = firstEntry.nextEntry;
236 while (currentEntry) {
237 var nextEntry = currentEntry.nextEntry;
238 currentEntry.previousEntry = undefined;
239 currentEntry.nextEntry = firstEntry;
240 currentEntry.skipNext = true;
241 currentEntry = nextEntry;
242 }
243 firstEntry.nextEntry = undefined;
244 this.lastEntry = firstEntry;
245 };
246 class_1.prototype.keys = function () {
247 return new MapIterator(this.firstEntry, function (key) { return key; });
248 };
249 class_1.prototype.values = function () {
250 return new MapIterator(this.firstEntry, function (_key, value) { return value; });
251 };
252 class_1.prototype.entries = function () {
253 return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
254 };
255 class_1.prototype.forEach = function (action) {
256 var iterator = this.entries();
257 while (true) {
258 var _a = iterator.next(), entry = _a.value, done = _a.done;
259 if (done) {
260 break;
261 }
262 action(entry[1], entry[0]);
263 }
264 };
265 return class_1;
266 }());
267 }
268 ts.shimMap = shimMap;
269 function length(array) {
270 return array ? array.length : 0;
271 }
272 ts.length = length;
273 /**
274 * Iterates through 'array' by index and performs the callback on each element of array until the callback
275 * returns a truthy value, then returns that value.
276 * If no such value is found, the callback is applied to each element of array and undefined is returned.
277 */
278 function forEach(array, callback) {
279 if (array) {
280 for (var i = 0; i < array.length; i++) {
281 var result = callback(array[i], i);
282 if (result) {
283 return result;
284 }
285 }
286 }
287 return undefined;
288 }
289 ts.forEach = forEach;
290 /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
291 function firstDefined(array, callback) {
292 if (array === undefined) {
293 return undefined;
294 }
295 for (var i = 0; i < array.length; i++) {
296 var result = callback(array[i], i);
297 if (result !== undefined) {
298 return result;
299 }
300 }
301 return undefined;
302 }
303 ts.firstDefined = firstDefined;
304 function firstDefinedIterator(iter, callback) {
305 while (true) {
306 var _a = iter.next(), value = _a.value, done = _a.done;
307 if (done) {
308 return undefined;
309 }
310 var result = callback(value);
311 if (result !== undefined) {
312 return result;
313 }
314 }
315 }
316 ts.firstDefinedIterator = firstDefinedIterator;
317 function zipWith(arrayA, arrayB, callback) {
318 var result = [];
319 Debug.assertEqual(arrayA.length, arrayB.length);
320 for (var i = 0; i < arrayA.length; i++) {
321 result.push(callback(arrayA[i], arrayB[i], i));
322 }
323 return result;
324 }
325 ts.zipWith = zipWith;
326 function zipToIterator(arrayA, arrayB) {
327 Debug.assertEqual(arrayA.length, arrayB.length);
328 var i = 0;
329 return {
330 next: function () {
331 if (i === arrayA.length) {
332 return { value: undefined, done: true };
333 }
334 i++;
335 return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
336 }
337 };
338 }
339 ts.zipToIterator = zipToIterator;
340 function zipToMap(keys, values) {
341 Debug.assert(keys.length === values.length);
342 var map = createMap();
343 for (var i = 0; i < keys.length; ++i) {
344 map.set(keys[i], values[i]);
345 }
346 return map;
347 }
348 ts.zipToMap = zipToMap;
349 /**
350 * Iterates through `array` by index and performs the callback on each element of array until the callback
351 * returns a falsey value, then returns false.
352 * If no such value is found, the callback is applied to each element of array and `true` is returned.
353 */
354 function every(array, callback) {
355 if (array) {
356 for (var i = 0; i < array.length; i++) {
357 if (!callback(array[i], i)) {
358 return false;
359 }
360 }
361 }
362 return true;
363 }
364 ts.every = every;
365 function find(array, predicate) {
366 for (var i = 0; i < array.length; i++) {
367 var value = array[i];
368 if (predicate(value, i)) {
369 return value;
370 }
371 }
372 return undefined;
373 }
374 ts.find = find;
375 function findLast(array, predicate) {
376 for (var i = array.length - 1; i >= 0; i--) {
377 var value = array[i];
378 if (predicate(value, i)) {
379 return value;
380 }
381 }
382 return undefined;
383 }
384 ts.findLast = findLast;
385 /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
386 function findIndex(array, predicate, startIndex) {
387 for (var i = startIndex || 0; i < array.length; i++) {
388 if (predicate(array[i], i)) {
389 return i;
390 }
391 }
392 return -1;
393 }
394 ts.findIndex = findIndex;
395 function findLastIndex(array, predicate, startIndex) {
396 for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
397 if (predicate(array[i], i)) {
398 return i;
399 }
400 }
401 return -1;
402 }
403 ts.findLastIndex = findLastIndex;
404 /**
405 * Returns the first truthy result of `callback`, or else fails.
406 * This is like `forEach`, but never returns undefined.
407 */
408 function findMap(array, callback) {
409 for (var i = 0; i < array.length; i++) {
410 var result = callback(array[i], i);
411 if (result) {
412 return result;
413 }
414 }
415 return Debug.fail();
416 }
417 ts.findMap = findMap;
418 function contains(array, value, equalityComparer) {
419 if (equalityComparer === void 0) { equalityComparer = equateValues; }
420 if (array) {
421 for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
422 var v = array_1[_i];
423 if (equalityComparer(v, value)) {
424 return true;
425 }
426 }
427 }
428 return false;
429 }
430 ts.contains = contains;
431 function arraysEqual(a, b, equalityComparer) {
432 if (equalityComparer === void 0) { equalityComparer = equateValues; }
433 return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
434 }
435 ts.arraysEqual = arraysEqual;
436 function indexOfAnyCharCode(text, charCodes, start) {
437 for (var i = start || 0; i < text.length; i++) {
438 if (contains(charCodes, text.charCodeAt(i))) {
439 return i;
440 }
441 }
442 return -1;
443 }
444 ts.indexOfAnyCharCode = indexOfAnyCharCode;
445 function countWhere(array, predicate) {
446 var count = 0;
447 if (array) {
448 for (var i = 0; i < array.length; i++) {
449 var v = array[i];
450 if (predicate(v, i)) {
451 count++;
452 }
453 }
454 }
455 return count;
456 }
457 ts.countWhere = countWhere;
458 function filter(array, f) {
459 if (array) {
460 var len = array.length;
461 var i = 0;
462 while (i < len && f(array[i]))
463 i++;
464 if (i < len) {
465 var result = array.slice(0, i);
466 i++;
467 while (i < len) {
468 var item = array[i];
469 if (f(item)) {
470 result.push(item);
471 }
472 i++;
473 }
474 return result;
475 }
476 }
477 return array;
478 }
479 ts.filter = filter;
480 function filterMutate(array, f) {
481 var outIndex = 0;
482 for (var i = 0; i < array.length; i++) {
483 if (f(array[i], i, array)) {
484 array[outIndex] = array[i];
485 outIndex++;
486 }
487 }
488 array.length = outIndex;
489 }
490 ts.filterMutate = filterMutate;
491 function clear(array) {
492 array.length = 0;
493 }
494 ts.clear = clear;
495 function map(array, f) {
496 var result;
497 if (array) {
498 result = [];
499 for (var i = 0; i < array.length; i++) {
500 result.push(f(array[i], i));
501 }
502 }
503 return result;
504 }
505 ts.map = map;
506 function mapIterator(iter, mapFn) {
507 return {
508 next: function () {
509 var iterRes = iter.next();
510 return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
511 }
512 };
513 }
514 ts.mapIterator = mapIterator;
515 function sameMap(array, f) {
516 if (array) {
517 for (var i = 0; i < array.length; i++) {
518 var item = array[i];
519 var mapped = f(item, i);
520 if (item !== mapped) {
521 var result = array.slice(0, i);
522 result.push(mapped);
523 for (i++; i < array.length; i++) {
524 result.push(f(array[i], i));
525 }
526 return result;
527 }
528 }
529 }
530 return array;
531 }
532 ts.sameMap = sameMap;
533 function flatten(array) {
534 var result;
535 if (array) {
536 result = [];
537 for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
538 var v = array_2[_i];
539 if (v) {
540 if (isArray(v)) {
541 addRange(result, v);
542 }
543 else {
544 result.push(v);
545 }
546 }
547 }
548 }
549 return result;
550 }
551 ts.flatten = flatten;
552 /**
553 * Maps an array. If the mapped value is an array, it is spread into the result.
554 *
555 * @param array The array to map.
556 * @param mapfn The callback used to map the result into one or more values.
557 */
558 function flatMap(array, mapfn) {
559 var result;
560 if (array) {
561 for (var i = 0; i < array.length; i++) {
562 var v = mapfn(array[i], i);
563 if (v) {
564 if (isArray(v)) {
565 result = addRange(result, v);
566 }
567 else {
568 result = append(result, v);
569 }
570 }
571 }
572 }
573 return result || ts.emptyArray;
574 }
575 ts.flatMap = flatMap;
576 function flatMapToMutable(array, mapfn) {
577 var result = [];
578 if (array) {
579 for (var i = 0; i < array.length; i++) {
580 var v = mapfn(array[i], i);
581 if (v) {
582 if (isArray(v)) {
583 addRange(result, v);
584 }
585 else {
586 result.push(v);
587 }
588 }
589 }
590 }
591 return result;
592 }
593 ts.flatMapToMutable = flatMapToMutable;
594 function flatMapIterator(iter, mapfn) {
595 var first = iter.next();
596 if (first.done) {
597 return ts.emptyIterator;
598 }
599 var currentIter = getIterator(first.value);
600 return {
601 next: function () {
602 while (true) {
603 var currentRes = currentIter.next();
604 if (!currentRes.done) {
605 return currentRes;
606 }
607 var iterRes = iter.next();
608 if (iterRes.done) {
609 return iterRes;
610 }
611 currentIter = getIterator(iterRes.value);
612 }
613 },
614 };
615 function getIterator(x) {
616 var res = mapfn(x);
617 return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
618 }
619 }
620 ts.flatMapIterator = flatMapIterator;
621 function sameFlatMap(array, mapfn) {
622 var result;
623 if (array) {
624 for (var i = 0; i < array.length; i++) {
625 var item = array[i];
626 var mapped = mapfn(item, i);
627 if (result || item !== mapped || isArray(mapped)) {
628 if (!result) {
629 result = array.slice(0, i);
630 }
631 if (isArray(mapped)) {
632 addRange(result, mapped);
633 }
634 else {
635 result.push(mapped);
636 }
637 }
638 }
639 }
640 return result || array;
641 }
642 ts.sameFlatMap = sameFlatMap;
643 function mapAllOrFail(array, mapFn) {
644 var result = [];
645 for (var i = 0; i < array.length; i++) {
646 var mapped = mapFn(array[i], i);
647 if (mapped === undefined) {
648 return undefined;
649 }
650 result.push(mapped);
651 }
652 return result;
653 }
654 ts.mapAllOrFail = mapAllOrFail;
655 function mapDefined(array, mapFn) {
656 var result = [];
657 if (array) {
658 for (var i = 0; i < array.length; i++) {
659 var mapped = mapFn(array[i], i);
660 if (mapped !== undefined) {
661 result.push(mapped);
662 }
663 }
664 }
665 return result;
666 }
667 ts.mapDefined = mapDefined;
668 function mapDefinedIterator(iter, mapFn) {
669 return {
670 next: function () {
671 while (true) {
672 var res = iter.next();
673 if (res.done) {
674 return res;
675 }
676 var value = mapFn(res.value);
677 if (value !== undefined) {
678 return { value: value, done: false };
679 }
680 }
681 }
682 };
683 }
684 ts.mapDefinedIterator = mapDefinedIterator;
685 ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
686 function singleIterator(value) {
687 var done = false;
688 return {
689 next: function () {
690 var wasDone = done;
691 done = true;
692 return wasDone ? { value: undefined, done: true } : { value: value, done: false };
693 }
694 };
695 }
696 ts.singleIterator = singleIterator;
697 function spanMap(array, keyfn, mapfn) {
698 var result;
699 if (array) {
700 result = [];
701 var len = array.length;
702 var previousKey = void 0;
703 var key = void 0;
704 var start = 0;
705 var pos = 0;
706 while (start < len) {
707 while (pos < len) {
708 var value = array[pos];
709 key = keyfn(value, pos);
710 if (pos === 0) {
711 previousKey = key;
712 }
713 else if (key !== previousKey) {
714 break;
715 }
716 pos++;
717 }
718 if (start < pos) {
719 var v = mapfn(array.slice(start, pos), previousKey, start, pos);
720 if (v) {
721 result.push(v);
722 }
723 start = pos;
724 }
725 previousKey = key;
726 pos++;
727 }
728 }
729 return result;
730 }
731 ts.spanMap = spanMap;
732 function mapEntries(map, f) {
733 if (!map) {
734 return undefined;
735 }
736 var result = createMap();
737 map.forEach(function (value, key) {
738 var _a = f(key, value), newKey = _a[0], newValue = _a[1];
739 result.set(newKey, newValue);
740 });
741 return result;
742 }
743 ts.mapEntries = mapEntries;
744 function some(array, predicate) {
745 if (array) {
746 if (predicate) {
747 for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
748 var v = array_3[_i];
749 if (predicate(v)) {
750 return true;
751 }
752 }
753 }
754 else {
755 return array.length > 0;
756 }
757 }
758 return false;
759 }
760 ts.some = some;
761 /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
762 function getRangesWhere(arr, pred, cb) {
763 var start;
764 for (var i = 0; i < arr.length; i++) {
765 if (pred(arr[i])) {
766 start = start === undefined ? i : start;
767 }
768 else {
769 if (start !== undefined) {
770 cb(start, i);
771 start = undefined;
772 }
773 }
774 }
775 if (start !== undefined)
776 cb(start, arr.length);
777 }
778 ts.getRangesWhere = getRangesWhere;
779 function concatenate(array1, array2) {
780 if (!some(array2))
781 return array1;
782 if (!some(array1))
783 return array2;
784 return array1.concat(array2);
785 }
786 ts.concatenate = concatenate;
787 function deduplicateRelational(array, equalityComparer, comparer) {
788 // Perform a stable sort of the array. This ensures the first entry in a list of
789 // duplicates remains the first entry in the result.
790 var indices = array.map(function (_, i) { return i; });
791 stableSortIndices(array, indices, comparer);
792 var last = array[indices[0]];
793 var deduplicated = [indices[0]];
794 for (var i = 1; i < indices.length; i++) {
795 var index = indices[i];
796 var item = array[index];
797 if (!equalityComparer(last, item)) {
798 deduplicated.push(index);
799 last = item;
800 }
801 }
802 // restore original order
803 deduplicated.sort();
804 return deduplicated.map(function (i) { return array[i]; });
805 }
806 function deduplicateEquality(array, equalityComparer) {
807 var result = [];
808 for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
809 var item = array_4[_i];
810 pushIfUnique(result, item, equalityComparer);
811 }
812 return result;
813 }
814 /**
815 * Deduplicates an unsorted array.
816 * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
817 * @param comparer An optional `Comparer` used to sort entries before comparison, though the
818 * result will remain in the original order in `array`.
819 */
820 function deduplicate(array, equalityComparer, comparer) {
821 return array.length === 0 ? [] :
822 array.length === 1 ? array.slice() :
823 comparer ? deduplicateRelational(array, equalityComparer, comparer) :
824 deduplicateEquality(array, equalityComparer);
825 }
826 ts.deduplicate = deduplicate;
827 /**
828 * Deduplicates an array that has already been sorted.
829 */
830 function deduplicateSorted(array, comparer) {
831 if (array.length === 0)
832 return ts.emptyArray;
833 var last = array[0];
834 var deduplicated = [last];
835 for (var i = 1; i < array.length; i++) {
836 var next = array[i];
837 switch (comparer(next, last)) {
838 // equality comparison
839 case true:
840 // relational comparison
841 case 0 /* EqualTo */:
842 continue;
843 case -1 /* LessThan */:
844 // If `array` is sorted, `next` should **never** be less than `last`.
845 return Debug.fail("Array is unsorted.");
846 }
847 deduplicated.push(last = next);
848 }
849 return deduplicated;
850 }
851 function insertSorted(array, insert, compare) {
852 if (array.length === 0) {
853 array.push(insert);
854 return;
855 }
856 var insertIndex = binarySearch(array, insert, identity, compare);
857 if (insertIndex < 0) {
858 array.splice(~insertIndex, 0, insert);
859 }
860 }
861 ts.insertSorted = insertSorted;
862 function sortAndDeduplicate(array, comparer, equalityComparer) {
863 return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
864 }
865 ts.sortAndDeduplicate = sortAndDeduplicate;
866 function arrayIsEqualTo(array1, array2, equalityComparer) {
867 if (equalityComparer === void 0) { equalityComparer = equateValues; }
868 if (!array1 || !array2) {
869 return array1 === array2;
870 }
871 if (array1.length !== array2.length) {
872 return false;
873 }
874 for (var i = 0; i < array1.length; i++) {
875 if (!equalityComparer(array1[i], array2[i], i)) {
876 return false;
877 }
878 }
879 return true;
880 }
881 ts.arrayIsEqualTo = arrayIsEqualTo;
882 function compact(array) {
883 var result;
884 if (array) {
885 for (var i = 0; i < array.length; i++) {
886 var v = array[i];
887 if (result || !v) {
888 if (!result) {
889 result = array.slice(0, i);
890 }
891 if (v) {
892 result.push(v);
893 }
894 }
895 }
896 }
897 return result || array;
898 }
899 ts.compact = compact;
900 /**
901 * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
902 * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
903 * based on the provided comparer.
904 */
905 function relativeComplement(arrayA, arrayB, comparer) {
906 if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
907 return arrayB;
908 var result = [];
909 loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
910 if (offsetB > 0) {
911 // Ensure `arrayB` is properly sorted.
912 Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
913 }
914 loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
915 if (offsetA > startA) {
916 // Ensure `arrayA` is properly sorted. We only need to perform this check if
917 // `offsetA` has changed since we entered the loop.
918 Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
919 }
920 switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
921 case -1 /* LessThan */:
922 // If B is less than A, B does not exist in arrayA. Add B to the result and
923 // move to the next element in arrayB without changing the current position
924 // in arrayA.
925 result.push(arrayB[offsetB]);
926 continue loopB;
927 case 0 /* EqualTo */:
928 // If B is equal to A, B exists in arrayA. Move to the next element in
929 // arrayB without adding B to the result or changing the current position
930 // in arrayA.
931 continue loopB;
932 case 1 /* GreaterThan */:
933 // If B is greater than A, we need to keep looking for B in arrayA. Move to
934 // the next element in arrayA and recheck.
935 continue loopA;
936 }
937 }
938 }
939 return result;
940 }
941 ts.relativeComplement = relativeComplement;
942 function sum(array, prop) {
943 var result = 0;
944 for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
945 var v = array_5[_i];
946 result += v[prop];
947 }
948 return result;
949 }
950 ts.sum = sum;
951 function append(to, value) {
952 if (value === undefined)
953 return to;
954 if (to === undefined)
955 return [value];
956 to.push(value);
957 return to;
958 }
959 ts.append = append;
960 /**
961 * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
962 * position offset from the end of the array.
963 */
964 function toOffset(array, offset) {
965 return offset < 0 ? array.length + offset : offset;
966 }
967 function addRange(to, from, start, end) {
968 if (from === undefined || from.length === 0)
969 return to;
970 if (to === undefined)
971 return from.slice(start, end);
972 start = start === undefined ? 0 : toOffset(from, start);
973 end = end === undefined ? from.length : toOffset(from, end);
974 for (var i = start; i < end && i < from.length; i++) {
975 if (from[i] !== undefined) {
976 to.push(from[i]);
977 }
978 }
979 return to;
980 }
981 ts.addRange = addRange;
982 /**
983 * @return Whether the value was added.
984 */
985 function pushIfUnique(array, toAdd, equalityComparer) {
986 if (contains(array, toAdd, equalityComparer)) {
987 return false;
988 }
989 else {
990 array.push(toAdd);
991 return true;
992 }
993 }
994 ts.pushIfUnique = pushIfUnique;
995 /**
996 * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
997 */
998 function appendIfUnique(array, toAdd, equalityComparer) {
999 if (array) {
1000 pushIfUnique(array, toAdd, equalityComparer);
1001 return array;
1002 }
1003 else {
1004 return [toAdd];
1005 }
1006 }
1007 ts.appendIfUnique = appendIfUnique;
1008 function stableSortIndices(array, indices, comparer) {
1009 // sort indices by value then position
1010 indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
1011 }
1012 /**
1013 * Returns a new sorted array.
1014 */
1015 function sort(array, comparer) {
1016 return (array.length === 0 ? array : array.slice().sort(comparer));
1017 }
1018 ts.sort = sort;
1019 function arrayIterator(array) {
1020 var i = 0;
1021 return { next: function () {
1022 if (i === array.length) {
1023 return { value: undefined, done: true };
1024 }
1025 else {
1026 i++;
1027 return { value: array[i - 1], done: false };
1028 }
1029 } };
1030 }
1031 ts.arrayIterator = arrayIterator;
1032 function arrayReverseIterator(array) {
1033 var i = array.length;
1034 return {
1035 next: function () {
1036 if (i === 0) {
1037 return { value: undefined, done: true };
1038 }
1039 else {
1040 i--;
1041 return { value: array[i], done: false };
1042 }
1043 }
1044 };
1045 }
1046 ts.arrayReverseIterator = arrayReverseIterator;
1047 /**
1048 * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
1049 */
1050 function stableSort(array, comparer) {
1051 var indices = array.map(function (_, i) { return i; });
1052 stableSortIndices(array, indices, comparer);
1053 return indices.map(function (i) { return array[i]; });
1054 }
1055 ts.stableSort = stableSort;
1056 function rangeEquals(array1, array2, pos, end) {
1057 while (pos < end) {
1058 if (array1[pos] !== array2[pos]) {
1059 return false;
1060 }
1061 pos++;
1062 }
1063 return true;
1064 }
1065 ts.rangeEquals = rangeEquals;
1066 /**
1067 * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
1068 * A negative offset indicates the element should be retrieved from the end of the array.
1069 */
1070 function elementAt(array, offset) {
1071 if (array) {
1072 offset = toOffset(array, offset);
1073 if (offset < array.length) {
1074 return array[offset];
1075 }
1076 }
1077 return undefined;
1078 }
1079 ts.elementAt = elementAt;
1080 /**
1081 * Returns the first element of an array if non-empty, `undefined` otherwise.
1082 */
1083 function firstOrUndefined(array) {
1084 return array.length === 0 ? undefined : array[0];
1085 }
1086 ts.firstOrUndefined = firstOrUndefined;
1087 function first(array) {
1088 Debug.assert(array.length !== 0);
1089 return array[0];
1090 }
1091 ts.first = first;
1092 /**
1093 * Returns the last element of an array if non-empty, `undefined` otherwise.
1094 */
1095 function lastOrUndefined(array) {
1096 return array.length === 0 ? undefined : array[array.length - 1];
1097 }
1098 ts.lastOrUndefined = lastOrUndefined;
1099 function last(array) {
1100 Debug.assert(array.length !== 0);
1101 return array[array.length - 1];
1102 }
1103 ts.last = last;
1104 /**
1105 * Returns the only element of an array if it contains only one element, `undefined` otherwise.
1106 */
1107 function singleOrUndefined(array) {
1108 return array && array.length === 1
1109 ? array[0]
1110 : undefined;
1111 }
1112 ts.singleOrUndefined = singleOrUndefined;
1113 function singleOrMany(array) {
1114 return array && array.length === 1
1115 ? array[0]
1116 : array;
1117 }
1118 ts.singleOrMany = singleOrMany;
1119 function replaceElement(array, index, value) {
1120 var result = array.slice(0);
1121 result[index] = value;
1122 return result;
1123 }
1124 ts.replaceElement = replaceElement;
1125 /**
1126 * Performs a binary search, finding the index at which `value` occurs in `array`.
1127 * If no such index is found, returns the 2's-complement of first index at which
1128 * `array[index]` exceeds `value`.
1129 * @param array A sorted array whose first element must be no larger than number
1130 * @param value The value to be searched for in the array.
1131 * @param keySelector A callback used to select the search key from `value` and each element of
1132 * `array`.
1133 * @param keyComparer A callback used to compare two keys in a sorted array.
1134 * @param offset An offset into `array` at which to start the search.
1135 */
1136 function binarySearch(array, value, keySelector, keyComparer, offset) {
1137 return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
1138 }
1139 ts.binarySearch = binarySearch;
1140 /**
1141 * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
1142 * If no such index is found, returns the 2's-complement of first index at which
1143 * `array[index]` exceeds `key`.
1144 * @param array A sorted array whose first element must be no larger than number
1145 * @param key The key to be searched for in the array.
1146 * @param keySelector A callback used to select the search key from each element of `array`.
1147 * @param keyComparer A callback used to compare two keys in a sorted array.
1148 * @param offset An offset into `array` at which to start the search.
1149 */
1150 function binarySearchKey(array, key, keySelector, keyComparer, offset) {
1151 if (!some(array)) {
1152 return -1;
1153 }
1154 var low = offset || 0;
1155 var high = array.length - 1;
1156 while (low <= high) {
1157 var middle = low + ((high - low) >> 1);
1158 var midKey = keySelector(array[middle]);
1159 switch (keyComparer(midKey, key)) {
1160 case -1 /* LessThan */:
1161 low = middle + 1;
1162 break;
1163 case 0 /* EqualTo */:
1164 return middle;
1165 case 1 /* GreaterThan */:
1166 high = middle - 1;
1167 break;
1168 }
1169 }
1170 return ~low;
1171 }
1172 ts.binarySearchKey = binarySearchKey;
1173 function reduceLeft(array, f, initial, start, count) {
1174 if (array && array.length > 0) {
1175 var size = array.length;
1176 if (size > 0) {
1177 var pos = start === undefined || start < 0 ? 0 : start;
1178 var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
1179 var result = void 0;
1180 if (arguments.length <= 2) {
1181 result = array[pos];
1182 pos++;
1183 }
1184 else {
1185 result = initial;
1186 }
1187 while (pos <= end) {
1188 result = f(result, array[pos], pos);
1189 pos++;
1190 }
1191 return result;
1192 }
1193 }
1194 return initial;
1195 }
1196 ts.reduceLeft = reduceLeft;
1197 var hasOwnProperty = Object.prototype.hasOwnProperty;
1198 /**
1199 * Indicates whether a map-like contains an own property with the specified key.
1200 *
1201 * @param map A map-like.
1202 * @param key A property key.
1203 */
1204 function hasProperty(map, key) {
1205 return hasOwnProperty.call(map, key);
1206 }
1207 ts.hasProperty = hasProperty;
1208 /**
1209 * Gets the value of an owned property in a map-like.
1210 *
1211 * @param map A map-like.
1212 * @param key A property key.
1213 */
1214 function getProperty(map, key) {
1215 return hasOwnProperty.call(map, key) ? map[key] : undefined;
1216 }
1217 ts.getProperty = getProperty;
1218 /**
1219 * Gets the owned, enumerable property keys of a map-like.
1220 */
1221 function getOwnKeys(map) {
1222 var keys = [];
1223 for (var key in map) {
1224 if (hasOwnProperty.call(map, key)) {
1225 keys.push(key);
1226 }
1227 }
1228 return keys;
1229 }
1230 ts.getOwnKeys = getOwnKeys;
1231 function getOwnValues(sparseArray) {
1232 var values = [];
1233 for (var key in sparseArray) {
1234 if (hasOwnProperty.call(sparseArray, key)) {
1235 values.push(sparseArray[key]);
1236 }
1237 }
1238 return values;
1239 }
1240 ts.getOwnValues = getOwnValues;
1241 function arrayFrom(iterator, map) {
1242 var _a;
1243 var result = [];
1244 for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
1245 result.push(map ? map(value) : value);
1246 }
1247 return result;
1248 }
1249 ts.arrayFrom = arrayFrom;
1250 function assign(t) {
1251 var args = [];
1252 for (var _i = 1; _i < arguments.length; _i++) {
1253 args[_i - 1] = arguments[_i];
1254 }
1255 for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
1256 var arg = args_1[_a];
1257 if (arg === undefined)
1258 continue;
1259 for (var p in arg) {
1260 if (hasProperty(arg, p)) {
1261 t[p] = arg[p];
1262 }
1263 }
1264 }
1265 return t;
1266 }
1267 ts.assign = assign;
1268 /**
1269 * Performs a shallow equality comparison of the contents of two map-likes.
1270 *
1271 * @param left A map-like whose properties should be compared.
1272 * @param right A map-like whose properties should be compared.
1273 */
1274 function equalOwnProperties(left, right, equalityComparer) {
1275 if (equalityComparer === void 0) { equalityComparer = equateValues; }
1276 if (left === right)
1277 return true;
1278 if (!left || !right)
1279 return false;
1280 for (var key in left) {
1281 if (hasOwnProperty.call(left, key)) {
1282 if (!hasOwnProperty.call(right, key))
1283 return false;
1284 if (!equalityComparer(left[key], right[key]))
1285 return false;
1286 }
1287 }
1288 for (var key in right) {
1289 if (hasOwnProperty.call(right, key)) {
1290 if (!hasOwnProperty.call(left, key))
1291 return false;
1292 }
1293 }
1294 return true;
1295 }
1296 ts.equalOwnProperties = equalOwnProperties;
1297 function arrayToMap(array, makeKey, makeValue) {
1298 if (makeValue === void 0) { makeValue = identity; }
1299 var result = createMap();
1300 for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
1301 var value = array_6[_i];
1302 var key = makeKey(value);
1303 if (key !== undefined)
1304 result.set(key, makeValue(value));
1305 }
1306 return result;
1307 }
1308 ts.arrayToMap = arrayToMap;
1309 function arrayToNumericMap(array, makeKey, makeValue) {
1310 if (makeValue === void 0) { makeValue = identity; }
1311 var result = [];
1312 for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
1313 var value = array_7[_i];
1314 result[makeKey(value)] = makeValue(value);
1315 }
1316 return result;
1317 }
1318 ts.arrayToNumericMap = arrayToNumericMap;
1319 function arrayToMultiMap(values, makeKey, makeValue) {
1320 if (makeValue === void 0) { makeValue = identity; }
1321 var result = createMultiMap();
1322 for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
1323 var value = values_1[_i];
1324 result.add(makeKey(value), makeValue(value));
1325 }
1326 return result;
1327 }
1328 ts.arrayToMultiMap = arrayToMultiMap;
1329 function group(values, getGroupId) {
1330 return arrayFrom(arrayToMultiMap(values, getGroupId).values());
1331 }
1332 ts.group = group;
1333 function clone(object) {
1334 var result = {};
1335 for (var id in object) {
1336 if (hasOwnProperty.call(object, id)) {
1337 result[id] = object[id];
1338 }
1339 }
1340 return result;
1341 }
1342 ts.clone = clone;
1343 function extend(first, second) {
1344 var result = {};
1345 for (var id in second) {
1346 if (hasOwnProperty.call(second, id)) {
1347 result[id] = second[id];
1348 }
1349 }
1350 for (var id in first) {
1351 if (hasOwnProperty.call(first, id)) {
1352 result[id] = first[id];
1353 }
1354 }
1355 return result;
1356 }
1357 ts.extend = extend;
1358 function copyProperties(first, second) {
1359 for (var id in second) {
1360 if (hasOwnProperty.call(second, id)) {
1361 first[id] = second[id];
1362 }
1363 }
1364 }
1365 ts.copyProperties = copyProperties;
1366 function maybeBind(obj, fn) {
1367 return fn ? fn.bind(obj) : undefined;
1368 }
1369 ts.maybeBind = maybeBind;
1370 function createMultiMap() {
1371 var map = createMap();
1372 map.add = multiMapAdd;
1373 map.remove = multiMapRemove;
1374 return map;
1375 }
1376 ts.createMultiMap = createMultiMap;
1377 function multiMapAdd(key, value) {
1378 var values = this.get(key);
1379 if (values) {
1380 values.push(value);
1381 }
1382 else {
1383 this.set(key, values = [value]);
1384 }
1385 return values;
1386 }
1387 function multiMapRemove(key, value) {
1388 var values = this.get(key);
1389 if (values) {
1390 unorderedRemoveItem(values, value);
1391 if (!values.length) {
1392 this.delete(key);
1393 }
1394 }
1395 }
1396 /**
1397 * Tests whether a value is an array.
1398 */
1399 function isArray(value) {
1400 return Array.isArray ? Array.isArray(value) : value instanceof Array;
1401 }
1402 ts.isArray = isArray;
1403 function toArray(value) {
1404 return isArray(value) ? value : [value];
1405 }
1406 ts.toArray = toArray;
1407 /**
1408 * Tests whether a value is string
1409 */
1410 function isString(text) {
1411 return typeof text === "string";
1412 }
1413 ts.isString = isString;
1414 function isNumber(x) {
1415 return typeof x === "number";
1416 }
1417 ts.isNumber = isNumber;
1418 function tryCast(value, test) {
1419 return value !== undefined && test(value) ? value : undefined;
1420 }
1421 ts.tryCast = tryCast;
1422 function cast(value, test) {
1423 if (value !== undefined && test(value))
1424 return value;
1425 return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'.");
1426 }
1427 ts.cast = cast;
1428 /** Does nothing. */
1429 function noop(_) { } // tslint:disable-line no-empty
1430 ts.noop = noop;
1431 /** Do nothing and return false */
1432 function returnFalse() { return false; }
1433 ts.returnFalse = returnFalse;
1434 /** Do nothing and return true */
1435 function returnTrue() { return true; }
1436 ts.returnTrue = returnTrue;
1437 /** Do nothing and return undefined */
1438 function returnUndefined() { return undefined; }
1439 ts.returnUndefined = returnUndefined;
1440 /** Returns its argument. */
1441 function identity(x) { return x; }
1442 ts.identity = identity;
1443 /** Returns lower case string */
1444 function toLowerCase(x) { return x.toLowerCase(); }
1445 ts.toLowerCase = toLowerCase;
1446 /** Throws an error because a function is not implemented. */
1447 function notImplemented() {
1448 throw new Error("Not implemented");
1449 }
1450 ts.notImplemented = notImplemented;
1451 function memoize(callback) {
1452 var value;
1453 return function () {
1454 if (callback) {
1455 value = callback();
1456 callback = undefined;
1457 }
1458 return value;
1459 };
1460 }
1461 ts.memoize = memoize;
1462 function chain(a, b, c, d, e) {
1463 if (e) {
1464 var args_2 = [];
1465 for (var i = 0; i < arguments.length; i++) {
1466 args_2[i] = arguments[i];
1467 }
1468 return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); };
1469 }
1470 else if (d) {
1471 return function (t) { return compose(a(t), b(t), c(t), d(t)); };
1472 }
1473 else if (c) {
1474 return function (t) { return compose(a(t), b(t), c(t)); };
1475 }
1476 else if (b) {
1477 return function (t) { return compose(a(t), b(t)); };
1478 }
1479 else if (a) {
1480 return function (t) { return compose(a(t)); };
1481 }
1482 else {
1483 return function (_) { return function (u) { return u; }; };
1484 }
1485 }
1486 ts.chain = chain;
1487 function compose(a, b, c, d, e) {
1488 if (e) {
1489 var args_3 = [];
1490 for (var i = 0; i < arguments.length; i++) {
1491 args_3[i] = arguments[i];
1492 }
1493 return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); };
1494 }
1495 else if (d) {
1496 return function (t) { return d(c(b(a(t)))); };
1497 }
1498 else if (c) {
1499 return function (t) { return c(b(a(t))); };
1500 }
1501 else if (b) {
1502 return function (t) { return b(a(t)); };
1503 }
1504 else if (a) {
1505 return function (t) { return a(t); };
1506 }
1507 else {
1508 return function (t) { return t; };
1509 }
1510 }
1511 ts.compose = compose;
1512 var AssertionLevel;
1513 (function (AssertionLevel) {
1514 AssertionLevel[AssertionLevel["None"] = 0] = "None";
1515 AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
1516 AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
1517 AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
1518 })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
1519 var Debug;
1520 (function (Debug) {
1521 Debug.currentAssertionLevel = 0 /* None */;
1522 Debug.isDebugging = false;
1523 function shouldAssert(level) {
1524 return Debug.currentAssertionLevel >= level;
1525 }
1526 Debug.shouldAssert = shouldAssert;
1527 function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
1528 if (!expression) {
1529 if (verboseDebugInfo) {
1530 message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
1531 }
1532 fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert);
1533 }
1534 }
1535 Debug.assert = assert;
1536 function assertEqual(a, b, msg, msg2) {
1537 if (a !== b) {
1538 var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
1539 fail("Expected " + a + " === " + b + ". " + message);
1540 }
1541 }
1542 Debug.assertEqual = assertEqual;
1543 function assertLessThan(a, b, msg) {
1544 if (a >= b) {
1545 fail("Expected " + a + " < " + b + ". " + (msg || ""));
1546 }
1547 }
1548 Debug.assertLessThan = assertLessThan;
1549 function assertLessThanOrEqual(a, b) {
1550 if (a > b) {
1551 fail("Expected " + a + " <= " + b);
1552 }
1553 }
1554 Debug.assertLessThanOrEqual = assertLessThanOrEqual;
1555 function assertGreaterThanOrEqual(a, b) {
1556 if (a < b) {
1557 fail("Expected " + a + " >= " + b);
1558 }
1559 }
1560 Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
1561 function fail(message, stackCrawlMark) {
1562 debugger;
1563 var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
1564 if (Error.captureStackTrace) {
1565 Error.captureStackTrace(e, stackCrawlMark || fail);
1566 }
1567 throw e;
1568 }
1569 Debug.fail = fail;
1570 function assertDefined(value, message) {
1571 if (value === undefined || value === null)
1572 return fail(message);
1573 return value;
1574 }
1575 Debug.assertDefined = assertDefined;
1576 function assertEachDefined(value, message) {
1577 for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
1578 var v = value_1[_i];
1579 assertDefined(v, message);
1580 }
1581 return value;
1582 }
1583 Debug.assertEachDefined = assertEachDefined;
1584 function assertNever(member, message, stackCrawlMark) {
1585 if (message === void 0) { message = "Illegal value:"; }
1586 var detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
1587 return fail(message + " " + detail, stackCrawlMark || assertNever);
1588 }
1589 Debug.assertNever = assertNever;
1590 function getFunctionName(func) {
1591 if (typeof func !== "function") {
1592 return "";
1593 }
1594 else if (func.hasOwnProperty("name")) {
1595 return func.name;
1596 }
1597 else {
1598 var text = Function.prototype.toString.call(func);
1599 var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
1600 return match ? match[1] : "";
1601 }
1602 }
1603 Debug.getFunctionName = getFunctionName;
1604 })(Debug = ts.Debug || (ts.Debug = {}));
1605 function equateValues(a, b) {
1606 return a === b;
1607 }
1608 ts.equateValues = equateValues;
1609 /**
1610 * Compare the equality of two strings using a case-sensitive ordinal comparison.
1611 *
1612 * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1613 * value of each code-point after applying `toUpperCase` to each string. We always map both
1614 * strings to their upper-case form as some unicode characters do not properly round-trip to
1615 * lowercase (such as `ẞ` (German sharp capital s)).
1616 */
1617 function equateStringsCaseInsensitive(a, b) {
1618 return a === b
1619 || a !== undefined
1620 && b !== undefined
1621 && a.toUpperCase() === b.toUpperCase();
1622 }
1623 ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
1624 /**
1625 * Compare the equality of two strings using a case-sensitive ordinal comparison.
1626 *
1627 * Case-sensitive comparisons compare both strings one code-point at a time using the
1628 * integer value of each code-point.
1629 */
1630 function equateStringsCaseSensitive(a, b) {
1631 return equateValues(a, b);
1632 }
1633 ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
1634 function compareComparableValues(a, b) {
1635 return a === b ? 0 /* EqualTo */ :
1636 a === undefined ? -1 /* LessThan */ :
1637 b === undefined ? 1 /* GreaterThan */ :
1638 a < b ? -1 /* LessThan */ :
1639 1 /* GreaterThan */;
1640 }
1641 /**
1642 * Compare two numeric values for their order relative to each other.
1643 * To compare strings, use any of the `compareStrings` functions.
1644 */
1645 function compareValues(a, b) {
1646 return compareComparableValues(a, b);
1647 }
1648 ts.compareValues = compareValues;
1649 function min(a, b, compare) {
1650 return compare(a, b) === -1 /* LessThan */ ? a : b;
1651 }
1652 ts.min = min;
1653 /**
1654 * Compare two strings using a case-insensitive ordinal comparison.
1655 *
1656 * Ordinal comparisons are based on the difference between the unicode code points of both
1657 * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1658 * comparisons provide predictable ordering, but place "a" after "B".
1659 *
1660 * Case-insensitive comparisons compare both strings one code-point at a time using the integer
1661 * value of each code-point after applying `toUpperCase` to each string. We always map both
1662 * strings to their upper-case form as some unicode characters do not properly round-trip to
1663 * lowercase (such as `ẞ` (German sharp capital s)).
1664 */
1665 function compareStringsCaseInsensitive(a, b) {
1666 if (a === b)
1667 return 0 /* EqualTo */;
1668 if (a === undefined)
1669 return -1 /* LessThan */;
1670 if (b === undefined)
1671 return 1 /* GreaterThan */;
1672 a = a.toUpperCase();
1673 b = b.toUpperCase();
1674 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1675 }
1676 ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
1677 /**
1678 * Compare two strings using a case-sensitive ordinal comparison.
1679 *
1680 * Ordinal comparisons are based on the difference between the unicode code points of both
1681 * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1682 * comparisons provide predictable ordering, but place "a" after "B".
1683 *
1684 * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1685 * value of each code-point.
1686 */
1687 function compareStringsCaseSensitive(a, b) {
1688 return compareComparableValues(a, b);
1689 }
1690 ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
1691 function getStringComparer(ignoreCase) {
1692 return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
1693 }
1694 ts.getStringComparer = getStringComparer;
1695 /**
1696 * Creates a string comparer for use with string collation in the UI.
1697 */
1698 var createUIStringComparer = (function () {
1699 var defaultComparer;
1700 var enUSComparer;
1701 var stringComparerFactory = getStringComparerFactory();
1702 return createStringComparer;
1703 function compareWithCallback(a, b, comparer) {
1704 if (a === b)
1705 return 0 /* EqualTo */;
1706 if (a === undefined)
1707 return -1 /* LessThan */;
1708 if (b === undefined)
1709 return 1 /* GreaterThan */;
1710 var value = comparer(a, b);
1711 return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1712 }
1713 function createIntlCollatorStringComparer(locale) {
1714 // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
1715 // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
1716 var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
1717 return function (a, b) { return compareWithCallback(a, b, comparer); };
1718 }
1719 function createLocaleCompareStringComparer(locale) {
1720 // if the locale is not the default locale (`undefined`), use the fallback comparer.
1721 if (locale !== undefined)
1722 return createFallbackStringComparer();
1723 return function (a, b) { return compareWithCallback(a, b, compareStrings); };
1724 function compareStrings(a, b) {
1725 return a.localeCompare(b);
1726 }
1727 }
1728 function createFallbackStringComparer() {
1729 // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
1730 // We first sort case insensitively. So "Aaa" will come before "baa".
1731 // Then we sort case sensitively, so "aaa" will come before "Aaa".
1732 //
1733 // For case insensitive comparisons we always map both strings to their
1734 // upper-case form as some unicode characters do not properly round-trip to
1735 // lowercase (such as `ẞ` (German sharp capital s)).
1736 return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
1737 function compareDictionaryOrder(a, b) {
1738 return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
1739 }
1740 function compareStrings(a, b) {
1741 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1742 }
1743 }
1744 function getStringComparerFactory() {
1745 // If the host supports Intl, we use it for comparisons using the default locale.
1746 if (typeof Intl === "object" && typeof Intl.Collator === "function") {
1747 return createIntlCollatorStringComparer;
1748 }
1749 // If the host does not support Intl, we fall back to localeCompare.
1750 // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
1751 if (typeof String.prototype.localeCompare === "function" &&
1752 typeof String.prototype.toLocaleUpperCase === "function" &&
1753 "a".localeCompare("B") < 0) {
1754 return createLocaleCompareStringComparer;
1755 }
1756 // Otherwise, fall back to ordinal comparison:
1757 return createFallbackStringComparer;
1758 }
1759 function createStringComparer(locale) {
1760 // Hold onto common string comparers. This avoids constantly reallocating comparers during
1761 // tests.
1762 if (locale === undefined) {
1763 return defaultComparer || (defaultComparer = stringComparerFactory(locale));
1764 }
1765 else if (locale === "en-US") {
1766 return enUSComparer || (enUSComparer = stringComparerFactory(locale));
1767 }
1768 else {
1769 return stringComparerFactory(locale);
1770 }
1771 }
1772 })();
1773 var uiComparerCaseSensitive;
1774 var uiLocale;
1775 function getUILocale() {
1776 return uiLocale;
1777 }
1778 ts.getUILocale = getUILocale;
1779 function setUILocale(value) {
1780 if (uiLocale !== value) {
1781 uiLocale = value;
1782 uiComparerCaseSensitive = undefined;
1783 }
1784 }
1785 ts.setUILocale = setUILocale;
1786 /**
1787 * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
1788 *
1789 * Ordering is not predictable between different host locales, but is best for displaying
1790 * ordered data for UI presentation. Characters with multiple unicode representations may
1791 * be considered equal.
1792 *
1793 * Case-sensitive comparisons compare strings that differ in base characters, or
1794 * accents/diacritic marks, or case as unequal.
1795 */
1796 function compareStringsCaseSensitiveUI(a, b) {
1797 var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
1798 return comparer(a, b);
1799 }
1800 ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
1801 function compareProperties(a, b, key, comparer) {
1802 return a === b ? 0 /* EqualTo */ :
1803 a === undefined ? -1 /* LessThan */ :
1804 b === undefined ? 1 /* GreaterThan */ :
1805 comparer(a[key], b[key]);
1806 }
1807 ts.compareProperties = compareProperties;
1808 /** True is greater than false. */
1809 function compareBooleans(a, b) {
1810 return compareValues(a ? 1 : 0, b ? 1 : 0);
1811 }
1812 ts.compareBooleans = compareBooleans;
1813 /**
1814 * 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.
1815 * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
1816 *
1817 * If there is a candidate that's the same except for case, return that.
1818 * If there is a candidate that's within one edit of the name, return that.
1819 * Otherwise, return the candidate with the smallest Levenshtein distance,
1820 * except for candidates:
1821 * * With no name
1822 * * Whose length differs from the target name by more than 0.34 of the length of the name.
1823 * * Whose levenshtein distance is more than 0.4 of the length of the name
1824 * (0.4 allows 1 substitution/transposition for every 5 characters,
1825 * and 1 insertion/deletion at 3 characters)
1826 */
1827 function getSpellingSuggestion(name, candidates, getName) {
1828 var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
1829 var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
1830 var bestCandidate;
1831 var justCheckExactMatches = false;
1832 var nameLowerCase = name.toLowerCase();
1833 for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
1834 var candidate = candidates_1[_i];
1835 var candidateName = getName(candidate);
1836 if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
1837 var candidateNameLowerCase = candidateName.toLowerCase();
1838 if (candidateNameLowerCase === nameLowerCase) {
1839 if (candidateName === name) {
1840 continue;
1841 }
1842 return candidate;
1843 }
1844 if (justCheckExactMatches) {
1845 continue;
1846 }
1847 if (candidateName.length < 3) {
1848 // Don't bother, user would have noticed a 2-character name having an extra character
1849 continue;
1850 }
1851 // Only care about a result better than the best so far.
1852 var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
1853 if (distance === undefined) {
1854 continue;
1855 }
1856 if (distance < 3) {
1857 justCheckExactMatches = true;
1858 bestCandidate = candidate;
1859 }
1860 else {
1861 Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
1862 bestDistance = distance;
1863 bestCandidate = candidate;
1864 }
1865 }
1866 }
1867 return bestCandidate;
1868 }
1869 ts.getSpellingSuggestion = getSpellingSuggestion;
1870 function levenshteinWithMax(s1, s2, max) {
1871 var previous = new Array(s2.length + 1);
1872 var current = new Array(s2.length + 1);
1873 /** Represents any value > max. We don't care about the particular value. */
1874 var big = max + 1;
1875 for (var i = 0; i <= s2.length; i++) {
1876 previous[i] = i;
1877 }
1878 for (var i = 1; i <= s1.length; i++) {
1879 var c1 = s1.charCodeAt(i - 1);
1880 var minJ = i > max ? i - max : 1;
1881 var maxJ = s2.length > max + i ? max + i : s2.length;
1882 current[0] = i;
1883 /** Smallest value of the matrix in the ith column. */
1884 var colMin = i;
1885 for (var j = 1; j < minJ; j++) {
1886 current[j] = big;
1887 }
1888 for (var j = minJ; j <= maxJ; j++) {
1889 var dist = c1 === s2.charCodeAt(j - 1)
1890 ? previous[j - 1]
1891 : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
1892 current[j] = dist;
1893 colMin = Math.min(colMin, dist);
1894 }
1895 for (var j = maxJ + 1; j <= s2.length; j++) {
1896 current[j] = big;
1897 }
1898 if (colMin > max) {
1899 // Give up -- everything in this column is > max and it can't get better in future columns.
1900 return undefined;
1901 }
1902 var temp = previous;
1903 previous = current;
1904 current = temp;
1905 }
1906 var res = previous[s2.length];
1907 return res > max ? undefined : res;
1908 }
1909 function endsWith(str, suffix) {
1910 var expectedPos = str.length - suffix.length;
1911 return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
1912 }
1913 ts.endsWith = endsWith;
1914 function removeSuffix(str, suffix) {
1915 return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
1916 }
1917 ts.removeSuffix = removeSuffix;
1918 function tryRemoveSuffix(str, suffix) {
1919 return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
1920 }
1921 ts.tryRemoveSuffix = tryRemoveSuffix;
1922 function stringContains(str, substring) {
1923 return str.indexOf(substring) !== -1;
1924 }
1925 ts.stringContains = stringContains;
1926 function fileExtensionIs(path, extension) {
1927 return path.length > extension.length && endsWith(path, extension);
1928 }
1929 ts.fileExtensionIs = fileExtensionIs;
1930 function fileExtensionIsOneOf(path, extensions) {
1931 for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
1932 var extension = extensions_1[_i];
1933 if (fileExtensionIs(path, extension)) {
1934 return true;
1935 }
1936 }
1937 return false;
1938 }
1939 ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
1940 /**
1941 * Takes a string like "jquery-min.4.2.3" and returns "jquery"
1942 */
1943 function removeMinAndVersionNumbers(fileName) {
1944 // Match a "." or "-" followed by a version number or 'min' at the end of the name
1945 var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
1946 // The "min" or version may both be present, in either order, so try applying the above twice.
1947 return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
1948 }
1949 ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
1950 /** Remove an item from an array, moving everything to its right one space left. */
1951 function orderedRemoveItem(array, item) {
1952 for (var i = 0; i < array.length; i++) {
1953 if (array[i] === item) {
1954 orderedRemoveItemAt(array, i);
1955 return true;
1956 }
1957 }
1958 return false;
1959 }
1960 ts.orderedRemoveItem = orderedRemoveItem;
1961 /** Remove an item by index from an array, moving everything to its right one space left. */
1962 function orderedRemoveItemAt(array, index) {
1963 // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
1964 for (var i = index; i < array.length - 1; i++) {
1965 array[i] = array[i + 1];
1966 }
1967 array.pop();
1968 }
1969 ts.orderedRemoveItemAt = orderedRemoveItemAt;
1970 function unorderedRemoveItemAt(array, index) {
1971 // Fill in the "hole" left at `index`.
1972 array[index] = array[array.length - 1];
1973 array.pop();
1974 }
1975 ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
1976 /** Remove the *first* occurrence of `item` from the array. */
1977 function unorderedRemoveItem(array, item) {
1978 return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
1979 }
1980 ts.unorderedRemoveItem = unorderedRemoveItem;
1981 /** Remove the *first* element satisfying `predicate`. */
1982 function unorderedRemoveFirstItemWhere(array, predicate) {
1983 for (var i = 0; i < array.length; i++) {
1984 if (predicate(array[i])) {
1985 unorderedRemoveItemAt(array, i);
1986 return true;
1987 }
1988 }
1989 return false;
1990 }
1991 function createGetCanonicalFileName(useCaseSensitiveFileNames) {
1992 return useCaseSensitiveFileNames ? identity : toLowerCase;
1993 }
1994 ts.createGetCanonicalFileName = createGetCanonicalFileName;
1995 function patternText(_a) {
1996 var prefix = _a.prefix, suffix = _a.suffix;
1997 return prefix + "*" + suffix;
1998 }
1999 ts.patternText = patternText;
2000 /**
2001 * Given that candidate matches pattern, returns the text matching the '*'.
2002 * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
2003 */
2004 function matchedText(pattern, candidate) {
2005 Debug.assert(isPatternMatch(pattern, candidate));
2006 return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
2007 }
2008 ts.matchedText = matchedText;
2009 /** Return the object corresponding to the best pattern to match `candidate`. */
2010 function findBestPatternMatch(values, getPattern, candidate) {
2011 var matchedValue;
2012 // use length of prefix as betterness criteria
2013 var longestMatchPrefixLength = -1;
2014 for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
2015 var v = values_2[_i];
2016 var pattern = getPattern(v);
2017 if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
2018 longestMatchPrefixLength = pattern.prefix.length;
2019 matchedValue = v;
2020 }
2021 }
2022 return matchedValue;
2023 }
2024 ts.findBestPatternMatch = findBestPatternMatch;
2025 function startsWith(str, prefix) {
2026 return str.lastIndexOf(prefix, 0) === 0;
2027 }
2028 ts.startsWith = startsWith;
2029 function removePrefix(str, prefix) {
2030 return startsWith(str, prefix) ? str.substr(prefix.length) : str;
2031 }
2032 ts.removePrefix = removePrefix;
2033 function tryRemovePrefix(str, prefix, getCanonicalFileName) {
2034 if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
2035 return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
2036 }
2037 ts.tryRemovePrefix = tryRemovePrefix;
2038 function isPatternMatch(_a, candidate) {
2039 var prefix = _a.prefix, suffix = _a.suffix;
2040 return candidate.length >= prefix.length + suffix.length &&
2041 startsWith(candidate, prefix) &&
2042 endsWith(candidate, suffix);
2043 }
2044 function and(f, g) {
2045 return function (arg) { return f(arg) && g(arg); };
2046 }
2047 ts.and = and;
2048 function or(f, g) {
2049 return function (arg) { return f(arg) || g(arg); };
2050 }
2051 ts.or = or;
2052 function assertType(_) { } // tslint:disable-line no-empty
2053 ts.assertType = assertType;
2054 function singleElementArray(t) {
2055 return t === undefined ? undefined : [t];
2056 }
2057 ts.singleElementArray = singleElementArray;
2058 function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
2059 unchanged = unchanged || noop;
2060 var newIndex = 0;
2061 var oldIndex = 0;
2062 var newLen = newItems.length;
2063 var oldLen = oldItems.length;
2064 while (newIndex < newLen && oldIndex < oldLen) {
2065 var newItem = newItems[newIndex];
2066 var oldItem = oldItems[oldIndex];
2067 var compareResult = comparer(newItem, oldItem);
2068 if (compareResult === -1 /* LessThan */) {
2069 inserted(newItem);
2070 newIndex++;
2071 }
2072 else if (compareResult === 1 /* GreaterThan */) {
2073 deleted(oldItem);
2074 oldIndex++;
2075 }
2076 else {
2077 unchanged(oldItem, newItem);
2078 newIndex++;
2079 oldIndex++;
2080 }
2081 }
2082 while (newIndex < newLen) {
2083 inserted(newItems[newIndex++]);
2084 }
2085 while (oldIndex < oldLen) {
2086 deleted(oldItems[oldIndex++]);
2087 }
2088 }
2089 ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
2090 function fill(length, cb) {
2091 var result = Array(length);
2092 for (var i = 0; i < length; i++) {
2093 result[i] = cb(i);
2094 }
2095 return result;
2096 }
2097 ts.fill = fill;
2098})(ts || (ts = {}));
2099/*@internal*/
2100var ts;
2101(function (ts) {
2102 /** Gets a timestamp with (at least) ms resolution */
2103 ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
2104})(ts || (ts = {}));
2105/*@internal*/
2106/** Performance measurements for the compiler. */
2107(function (ts) {
2108 var performance;
2109 (function (performance) {
2110 // NOTE: cannot use ts.noop as core.ts loads after this
2111 var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { };
2112 var enabled = false;
2113 var profilerStart = 0;
2114 var counts;
2115 var marks;
2116 var measures;
2117 function createTimerIf(condition, measureName, startMarkName, endMarkName) {
2118 return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
2119 }
2120 performance.createTimerIf = createTimerIf;
2121 function createTimer(measureName, startMarkName, endMarkName) {
2122 var enterCount = 0;
2123 return {
2124 enter: enter,
2125 exit: exit
2126 };
2127 function enter() {
2128 if (++enterCount === 1) {
2129 mark(startMarkName);
2130 }
2131 }
2132 function exit() {
2133 if (--enterCount === 0) {
2134 mark(endMarkName);
2135 measure(measureName, startMarkName, endMarkName);
2136 }
2137 else if (enterCount < 0) {
2138 ts.Debug.fail("enter/exit count does not match.");
2139 }
2140 }
2141 }
2142 performance.createTimer = createTimer;
2143 performance.nullTimer = { enter: ts.noop, exit: ts.noop };
2144 /**
2145 * Marks a performance event.
2146 *
2147 * @param markName The name of the mark.
2148 */
2149 function mark(markName) {
2150 if (enabled) {
2151 marks.set(markName, ts.timestamp());
2152 counts.set(markName, (counts.get(markName) || 0) + 1);
2153 profilerEvent(markName);
2154 }
2155 }
2156 performance.mark = mark;
2157 /**
2158 * Adds a performance measurement with the specified name.
2159 *
2160 * @param measureName The name of the performance measurement.
2161 * @param startMarkName The name of the starting mark. If not supplied, the point at which the
2162 * profiler was enabled is used.
2163 * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
2164 * used.
2165 */
2166 function measure(measureName, startMarkName, endMarkName) {
2167 if (enabled) {
2168 var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
2169 var start = startMarkName && marks.get(startMarkName) || profilerStart;
2170 measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
2171 }
2172 }
2173 performance.measure = measure;
2174 /**
2175 * Gets the number of times a marker was encountered.
2176 *
2177 * @param markName The name of the mark.
2178 */
2179 function getCount(markName) {
2180 return counts && counts.get(markName) || 0;
2181 }
2182 performance.getCount = getCount;
2183 /**
2184 * Gets the total duration of all measurements with the supplied name.
2185 *
2186 * @param measureName The name of the measure whose durations should be accumulated.
2187 */
2188 function getDuration(measureName) {
2189 return measures && measures.get(measureName) || 0;
2190 }
2191 performance.getDuration = getDuration;
2192 /**
2193 * Iterate over each measure, performing some action
2194 *
2195 * @param cb The action to perform for each measure
2196 */
2197 function forEachMeasure(cb) {
2198 measures.forEach(function (measure, key) {
2199 cb(key, measure);
2200 });
2201 }
2202 performance.forEachMeasure = forEachMeasure;
2203 /** Enables (and resets) performance measurements for the compiler. */
2204 function enable() {
2205 counts = ts.createMap();
2206 marks = ts.createMap();
2207 measures = ts.createMap();
2208 enabled = true;
2209 profilerStart = ts.timestamp();
2210 }
2211 performance.enable = enable;
2212 /** Disables performance measurements for the compiler. */
2213 function disable() {
2214 enabled = false;
2215 }
2216 performance.disable = disable;
2217 })(performance = ts.performance || (ts.performance = {}));
2218})(ts || (ts = {}));
2219/* @internal */
2220var ts;
2221(function (ts) {
2222 // https://semver.org/#spec-item-2
2223 // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2224 // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2225 // > version, and Z is the patch version. Each element MUST increase numerically.
2226 //
2227 // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2228 // value of `0`.
2229 var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2230 // https://semver.org/#spec-item-9
2231 // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2232 // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2233 // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2234 // > MUST NOT include leading zeroes.
2235 var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2236 // https://semver.org/#spec-item-10
2237 // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2238 // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2239 // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2240 var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2241 // https://semver.org/#spec-item-9
2242 // > Numeric identifiers MUST NOT include leading zeroes.
2243 var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2244 /**
2245 * Describes a precise semantic version number, https://semver.org
2246 */
2247 var Version = /** @class */ (function () {
2248 function Version(major, minor, patch, prerelease, build) {
2249 if (minor === void 0) { minor = 0; }
2250 if (patch === void 0) { patch = 0; }
2251 if (prerelease === void 0) { prerelease = ""; }
2252 if (build === void 0) { build = ""; }
2253 if (typeof major === "string") {
2254 var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version");
2255 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2256 }
2257 ts.Debug.assert(major >= 0, "Invalid argument: major");
2258 ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2259 ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2260 ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2261 ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2262 this.major = major;
2263 this.minor = minor;
2264 this.patch = patch;
2265 this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2266 this.build = build ? build.split(".") : ts.emptyArray;
2267 }
2268 Version.tryParse = function (text) {
2269 var result = tryParseComponents(text);
2270 if (!result)
2271 return undefined;
2272 var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2273 return new Version(major, minor, patch, prerelease, build);
2274 };
2275 Version.prototype.compareTo = function (other) {
2276 // https://semver.org/#spec-item-11
2277 // > Precedence is determined by the first difference when comparing each of these
2278 // > identifiers from left to right as follows: Major, minor, and patch versions are
2279 // > always compared numerically.
2280 //
2281 // https://semver.org/#spec-item-11
2282 // > Precedence for two pre-release versions with the same major, minor, and patch version
2283 // > MUST be determined by comparing each dot separated identifier from left to right until
2284 // > a difference is found [...]
2285 //
2286 // https://semver.org/#spec-item-11
2287 // > Build metadata does not figure into precedence
2288 if (this === other)
2289 return 0 /* EqualTo */;
2290 if (other === undefined)
2291 return 1 /* GreaterThan */;
2292 return ts.compareValues(this.major, other.major)
2293 || ts.compareValues(this.minor, other.minor)
2294 || ts.compareValues(this.patch, other.patch)
2295 || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
2296 };
2297 Version.prototype.increment = function (field) {
2298 switch (field) {
2299 case "major": return new Version(this.major + 1, 0, 0);
2300 case "minor": return new Version(this.major, this.minor + 1, 0);
2301 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2302 default: return ts.Debug.assertNever(field);
2303 }
2304 };
2305 Version.prototype.toString = function () {
2306 var result = this.major + "." + this.minor + "." + this.patch;
2307 if (ts.some(this.prerelease))
2308 result += "-" + this.prerelease.join(".");
2309 if (ts.some(this.build))
2310 result += "+" + this.build.join(".");
2311 return result;
2312 };
2313 Version.zero = new Version(0, 0, 0);
2314 return Version;
2315 }());
2316 ts.Version = Version;
2317 function tryParseComponents(text) {
2318 var match = versionRegExp.exec(text);
2319 if (!match)
2320 return undefined;
2321 var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d;
2322 if (prerelease && !prereleaseRegExp.test(prerelease))
2323 return undefined;
2324 if (build && !buildRegExp.test(build))
2325 return undefined;
2326 return {
2327 major: parseInt(major, 10),
2328 minor: parseInt(minor, 10),
2329 patch: parseInt(patch, 10),
2330 prerelease: prerelease,
2331 build: build
2332 };
2333 }
2334 function comparePrerelaseIdentifiers(left, right) {
2335 // https://semver.org/#spec-item-11
2336 // > When major, minor, and patch are equal, a pre-release version has lower precedence
2337 // > than a normal version.
2338 if (left === right)
2339 return 0 /* EqualTo */;
2340 if (left.length === 0)
2341 return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
2342 if (right.length === 0)
2343 return -1 /* LessThan */;
2344 // https://semver.org/#spec-item-11
2345 // > Precedence for two pre-release versions with the same major, minor, and patch version
2346 // > MUST be determined by comparing each dot separated identifier from left to right until
2347 // > a difference is found [...]
2348 var length = Math.min(left.length, right.length);
2349 for (var i = 0; i < length; i++) {
2350 var leftIdentifier = left[i];
2351 var rightIdentifier = right[i];
2352 if (leftIdentifier === rightIdentifier)
2353 continue;
2354 var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
2355 var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
2356 if (leftIsNumeric || rightIsNumeric) {
2357 // https://semver.org/#spec-item-11
2358 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
2359 if (leftIsNumeric !== rightIsNumeric)
2360 return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
2361 // https://semver.org/#spec-item-11
2362 // > identifiers consisting of only digits are compared numerically
2363 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
2364 if (result)
2365 return result;
2366 }
2367 else {
2368 // https://semver.org/#spec-item-11
2369 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
2370 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
2371 if (result)
2372 return result;
2373 }
2374 }
2375 // https://semver.org/#spec-item-11
2376 // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
2377 // > of the preceding identifiers are equal.
2378 return ts.compareValues(left.length, right.length);
2379 }
2380 /**
2381 * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
2382 */
2383 var VersionRange = /** @class */ (function () {
2384 function VersionRange(spec) {
2385 this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
2386 }
2387 VersionRange.tryParse = function (text) {
2388 var sets = parseRange(text);
2389 if (sets) {
2390 var range = new VersionRange("");
2391 range._alternatives = sets;
2392 return range;
2393 }
2394 return undefined;
2395 };
2396 VersionRange.prototype.test = function (version) {
2397 if (typeof version === "string")
2398 version = new Version(version);
2399 return testDisjunction(version, this._alternatives);
2400 };
2401 VersionRange.prototype.toString = function () {
2402 return formatDisjunction(this._alternatives);
2403 };
2404 return VersionRange;
2405 }());
2406 ts.VersionRange = VersionRange;
2407 // https://github.com/npm/node-semver#range-grammar
2408 //
2409 // range-set ::= range ( logical-or range ) *
2410 // range ::= hyphen | simple ( ' ' simple ) * | ''
2411 // logical-or ::= ( ' ' ) * '||' ( ' ' ) *
2412 var logicalOrRegExp = /\s*\|\|\s*/g;
2413 var whitespaceRegExp = /\s+/g;
2414 // https://github.com/npm/node-semver#range-grammar
2415 //
2416 // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
2417 // xr ::= 'x' | 'X' | '*' | nr
2418 // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
2419 // qualifier ::= ( '-' pre )? ( '+' build )?
2420 // pre ::= parts
2421 // build ::= parts
2422 // parts ::= part ( '.' part ) *
2423 // part ::= nr | [-0-9A-Za-z]+
2424 var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2425 // https://github.com/npm/node-semver#range-grammar
2426 //
2427 // hyphen ::= partial ' - ' partial
2428 var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
2429 // https://github.com/npm/node-semver#range-grammar
2430 //
2431 // simple ::= primitive | partial | tilde | caret
2432 // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
2433 // tilde ::= '~' partial
2434 // caret ::= '^' partial
2435 var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
2436 function parseRange(text) {
2437 var alternatives = [];
2438 for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
2439 var range = _a[_i];
2440 if (!range)
2441 continue;
2442 var comparators = [];
2443 var match = hyphenRegExp.exec(range);
2444 if (match) {
2445 if (!parseHyphen(match[1], match[2], comparators))
2446 return undefined;
2447 }
2448 else {
2449 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
2450 var simple = _c[_b];
2451 var match_1 = rangeRegExp.exec(simple);
2452 if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
2453 return undefined;
2454 }
2455 }
2456 alternatives.push(comparators);
2457 }
2458 return alternatives;
2459 }
2460 function parsePartial(text) {
2461 var match = partialRegExp.exec(text);
2462 if (!match)
2463 return undefined;
2464 var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5];
2465 var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build);
2466 return { version: version, major: major, minor: minor, patch: patch };
2467 }
2468 function parseHyphen(left, right, comparators) {
2469 var leftResult = parsePartial(left);
2470 if (!leftResult)
2471 return false;
2472 var rightResult = parsePartial(right);
2473 if (!rightResult)
2474 return false;
2475 if (!isWildcard(leftResult.major)) {
2476 comparators.push(createComparator(">=", leftResult.version));
2477 }
2478 if (!isWildcard(rightResult.major)) {
2479 comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
2480 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
2481 createComparator("<=", rightResult.version));
2482 }
2483 return true;
2484 }
2485 function parseComparator(operator, text, comparators) {
2486 var result = parsePartial(text);
2487 if (!result)
2488 return false;
2489 var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
2490 if (!isWildcard(major)) {
2491 switch (operator) {
2492 case "~":
2493 comparators.push(createComparator(">=", version));
2494 comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
2495 "minor")));
2496 break;
2497 case "^":
2498 comparators.push(createComparator(">=", version));
2499 comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
2500 version.minor > 0 || isWildcard(patch) ? "minor" :
2501 "patch")));
2502 break;
2503 case "<":
2504 case ">=":
2505 comparators.push(createComparator(operator, version));
2506 break;
2507 case "<=":
2508 case ">":
2509 comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
2510 isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
2511 createComparator(operator, version));
2512 break;
2513 case "=":
2514 case undefined:
2515 if (isWildcard(minor) || isWildcard(patch)) {
2516 comparators.push(createComparator(">=", version));
2517 comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
2518 }
2519 else {
2520 comparators.push(createComparator("=", version));
2521 }
2522 break;
2523 default:
2524 // unrecognized
2525 return false;
2526 }
2527 }
2528 else if (operator === "<" || operator === ">") {
2529 comparators.push(createComparator("<", Version.zero));
2530 }
2531 return true;
2532 }
2533 function isWildcard(part) {
2534 return part === "*" || part === "x" || part === "X";
2535 }
2536 function createComparator(operator, operand) {
2537 return { operator: operator, operand: operand };
2538 }
2539 function testDisjunction(version, alternatives) {
2540 // an empty disjunction is treated as "*" (all versions)
2541 if (alternatives.length === 0)
2542 return true;
2543 for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
2544 var alternative = alternatives_1[_i];
2545 if (testAlternative(version, alternative))
2546 return true;
2547 }
2548 return false;
2549 }
2550 function testAlternative(version, comparators) {
2551 for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
2552 var comparator = comparators_1[_i];
2553 if (!testComparator(version, comparator.operator, comparator.operand))
2554 return false;
2555 }
2556 return true;
2557 }
2558 function testComparator(version, operator, operand) {
2559 var cmp = version.compareTo(operand);
2560 switch (operator) {
2561 case "<": return cmp < 0;
2562 case "<=": return cmp <= 0;
2563 case ">": return cmp > 0;
2564 case ">=": return cmp >= 0;
2565 case "=": return cmp === 0;
2566 default: return ts.Debug.assertNever(operator);
2567 }
2568 }
2569 function formatDisjunction(alternatives) {
2570 return ts.map(alternatives, formatAlternative).join(" || ") || "*";
2571 }
2572 function formatAlternative(comparators) {
2573 return ts.map(comparators, formatComparator).join(" ");
2574 }
2575 function formatComparator(comparator) {
2576 return "" + comparator.operator + comparator.operand;
2577 }
2578})(ts || (ts = {}));
2579var ts;
2580(function (ts) {
2581 // token > SyntaxKind.Identifier => token is a keyword
2582 // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
2583 var SyntaxKind;
2584 (function (SyntaxKind) {
2585 SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
2586 SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
2587 SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
2588 SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
2589 SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
2590 SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
2591 // We detect and preserve #! on the first line
2592 SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
2593 // We detect and provide better error recovery when we encounter a git merge marker. This
2594 // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
2595 SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
2596 // Literals
2597 SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
2598 SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
2599 SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
2600 SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
2601 SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
2602 SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
2603 SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
2604 // Pseudo-literals
2605 SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
2606 SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
2607 SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
2608 // Punctuation
2609 SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
2610 SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
2611 SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
2612 SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
2613 SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
2614 SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
2615 SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
2616 SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
2617 SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
2618 SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
2619 SyntaxKind[SyntaxKind["LessThanToken"] = 28] = "LessThanToken";
2620 SyntaxKind[SyntaxKind["LessThanSlashToken"] = 29] = "LessThanSlashToken";
2621 SyntaxKind[SyntaxKind["GreaterThanToken"] = 30] = "GreaterThanToken";
2622 SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 31] = "LessThanEqualsToken";
2623 SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 32] = "GreaterThanEqualsToken";
2624 SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 33] = "EqualsEqualsToken";
2625 SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 34] = "ExclamationEqualsToken";
2626 SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 35] = "EqualsEqualsEqualsToken";
2627 SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 36] = "ExclamationEqualsEqualsToken";
2628 SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 37] = "EqualsGreaterThanToken";
2629 SyntaxKind[SyntaxKind["PlusToken"] = 38] = "PlusToken";
2630 SyntaxKind[SyntaxKind["MinusToken"] = 39] = "MinusToken";
2631 SyntaxKind[SyntaxKind["AsteriskToken"] = 40] = "AsteriskToken";
2632 SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 41] = "AsteriskAsteriskToken";
2633 SyntaxKind[SyntaxKind["SlashToken"] = 42] = "SlashToken";
2634 SyntaxKind[SyntaxKind["PercentToken"] = 43] = "PercentToken";
2635 SyntaxKind[SyntaxKind["PlusPlusToken"] = 44] = "PlusPlusToken";
2636 SyntaxKind[SyntaxKind["MinusMinusToken"] = 45] = "MinusMinusToken";
2637 SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 46] = "LessThanLessThanToken";
2638 SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanToken";
2639 SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanGreaterThanToken";
2640 SyntaxKind[SyntaxKind["AmpersandToken"] = 49] = "AmpersandToken";
2641 SyntaxKind[SyntaxKind["BarToken"] = 50] = "BarToken";
2642 SyntaxKind[SyntaxKind["CaretToken"] = 51] = "CaretToken";
2643 SyntaxKind[SyntaxKind["ExclamationToken"] = 52] = "ExclamationToken";
2644 SyntaxKind[SyntaxKind["TildeToken"] = 53] = "TildeToken";
2645 SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 54] = "AmpersandAmpersandToken";
2646 SyntaxKind[SyntaxKind["BarBarToken"] = 55] = "BarBarToken";
2647 SyntaxKind[SyntaxKind["QuestionToken"] = 56] = "QuestionToken";
2648 SyntaxKind[SyntaxKind["ColonToken"] = 57] = "ColonToken";
2649 SyntaxKind[SyntaxKind["AtToken"] = 58] = "AtToken";
2650 // Assignments
2651 SyntaxKind[SyntaxKind["EqualsToken"] = 59] = "EqualsToken";
2652 SyntaxKind[SyntaxKind["PlusEqualsToken"] = 60] = "PlusEqualsToken";
2653 SyntaxKind[SyntaxKind["MinusEqualsToken"] = 61] = "MinusEqualsToken";
2654 SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 62] = "AsteriskEqualsToken";
2655 SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 63] = "AsteriskAsteriskEqualsToken";
2656 SyntaxKind[SyntaxKind["SlashEqualsToken"] = 64] = "SlashEqualsToken";
2657 SyntaxKind[SyntaxKind["PercentEqualsToken"] = 65] = "PercentEqualsToken";
2658 SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 66] = "LessThanLessThanEqualsToken";
2659 SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanEqualsToken";
2660 SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 68] = "GreaterThanGreaterThanGreaterThanEqualsToken";
2661 SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 69] = "AmpersandEqualsToken";
2662 SyntaxKind[SyntaxKind["BarEqualsToken"] = 70] = "BarEqualsToken";
2663 SyntaxKind[SyntaxKind["CaretEqualsToken"] = 71] = "CaretEqualsToken";
2664 // Identifiers
2665 SyntaxKind[SyntaxKind["Identifier"] = 72] = "Identifier";
2666 // Reserved words
2667 SyntaxKind[SyntaxKind["BreakKeyword"] = 73] = "BreakKeyword";
2668 SyntaxKind[SyntaxKind["CaseKeyword"] = 74] = "CaseKeyword";
2669 SyntaxKind[SyntaxKind["CatchKeyword"] = 75] = "CatchKeyword";
2670 SyntaxKind[SyntaxKind["ClassKeyword"] = 76] = "ClassKeyword";
2671 SyntaxKind[SyntaxKind["ConstKeyword"] = 77] = "ConstKeyword";
2672 SyntaxKind[SyntaxKind["ContinueKeyword"] = 78] = "ContinueKeyword";
2673 SyntaxKind[SyntaxKind["DebuggerKeyword"] = 79] = "DebuggerKeyword";
2674 SyntaxKind[SyntaxKind["DefaultKeyword"] = 80] = "DefaultKeyword";
2675 SyntaxKind[SyntaxKind["DeleteKeyword"] = 81] = "DeleteKeyword";
2676 SyntaxKind[SyntaxKind["DoKeyword"] = 82] = "DoKeyword";
2677 SyntaxKind[SyntaxKind["ElseKeyword"] = 83] = "ElseKeyword";
2678 SyntaxKind[SyntaxKind["EnumKeyword"] = 84] = "EnumKeyword";
2679 SyntaxKind[SyntaxKind["ExportKeyword"] = 85] = "ExportKeyword";
2680 SyntaxKind[SyntaxKind["ExtendsKeyword"] = 86] = "ExtendsKeyword";
2681 SyntaxKind[SyntaxKind["FalseKeyword"] = 87] = "FalseKeyword";
2682 SyntaxKind[SyntaxKind["FinallyKeyword"] = 88] = "FinallyKeyword";
2683 SyntaxKind[SyntaxKind["ForKeyword"] = 89] = "ForKeyword";
2684 SyntaxKind[SyntaxKind["FunctionKeyword"] = 90] = "FunctionKeyword";
2685 SyntaxKind[SyntaxKind["IfKeyword"] = 91] = "IfKeyword";
2686 SyntaxKind[SyntaxKind["ImportKeyword"] = 92] = "ImportKeyword";
2687 SyntaxKind[SyntaxKind["InKeyword"] = 93] = "InKeyword";
2688 SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 94] = "InstanceOfKeyword";
2689 SyntaxKind[SyntaxKind["NewKeyword"] = 95] = "NewKeyword";
2690 SyntaxKind[SyntaxKind["NullKeyword"] = 96] = "NullKeyword";
2691 SyntaxKind[SyntaxKind["ReturnKeyword"] = 97] = "ReturnKeyword";
2692 SyntaxKind[SyntaxKind["SuperKeyword"] = 98] = "SuperKeyword";
2693 SyntaxKind[SyntaxKind["SwitchKeyword"] = 99] = "SwitchKeyword";
2694 SyntaxKind[SyntaxKind["ThisKeyword"] = 100] = "ThisKeyword";
2695 SyntaxKind[SyntaxKind["ThrowKeyword"] = 101] = "ThrowKeyword";
2696 SyntaxKind[SyntaxKind["TrueKeyword"] = 102] = "TrueKeyword";
2697 SyntaxKind[SyntaxKind["TryKeyword"] = 103] = "TryKeyword";
2698 SyntaxKind[SyntaxKind["TypeOfKeyword"] = 104] = "TypeOfKeyword";
2699 SyntaxKind[SyntaxKind["VarKeyword"] = 105] = "VarKeyword";
2700 SyntaxKind[SyntaxKind["VoidKeyword"] = 106] = "VoidKeyword";
2701 SyntaxKind[SyntaxKind["WhileKeyword"] = 107] = "WhileKeyword";
2702 SyntaxKind[SyntaxKind["WithKeyword"] = 108] = "WithKeyword";
2703 // Strict mode reserved words
2704 SyntaxKind[SyntaxKind["ImplementsKeyword"] = 109] = "ImplementsKeyword";
2705 SyntaxKind[SyntaxKind["InterfaceKeyword"] = 110] = "InterfaceKeyword";
2706 SyntaxKind[SyntaxKind["LetKeyword"] = 111] = "LetKeyword";
2707 SyntaxKind[SyntaxKind["PackageKeyword"] = 112] = "PackageKeyword";
2708 SyntaxKind[SyntaxKind["PrivateKeyword"] = 113] = "PrivateKeyword";
2709 SyntaxKind[SyntaxKind["ProtectedKeyword"] = 114] = "ProtectedKeyword";
2710 SyntaxKind[SyntaxKind["PublicKeyword"] = 115] = "PublicKeyword";
2711 SyntaxKind[SyntaxKind["StaticKeyword"] = 116] = "StaticKeyword";
2712 SyntaxKind[SyntaxKind["YieldKeyword"] = 117] = "YieldKeyword";
2713 // Contextual keywords
2714 SyntaxKind[SyntaxKind["AbstractKeyword"] = 118] = "AbstractKeyword";
2715 SyntaxKind[SyntaxKind["AsKeyword"] = 119] = "AsKeyword";
2716 SyntaxKind[SyntaxKind["AnyKeyword"] = 120] = "AnyKeyword";
2717 SyntaxKind[SyntaxKind["AsyncKeyword"] = 121] = "AsyncKeyword";
2718 SyntaxKind[SyntaxKind["AwaitKeyword"] = 122] = "AwaitKeyword";
2719 SyntaxKind[SyntaxKind["BooleanKeyword"] = 123] = "BooleanKeyword";
2720 SyntaxKind[SyntaxKind["ConstructorKeyword"] = 124] = "ConstructorKeyword";
2721 SyntaxKind[SyntaxKind["DeclareKeyword"] = 125] = "DeclareKeyword";
2722 SyntaxKind[SyntaxKind["GetKeyword"] = 126] = "GetKeyword";
2723 SyntaxKind[SyntaxKind["InferKeyword"] = 127] = "InferKeyword";
2724 SyntaxKind[SyntaxKind["IsKeyword"] = 128] = "IsKeyword";
2725 SyntaxKind[SyntaxKind["KeyOfKeyword"] = 129] = "KeyOfKeyword";
2726 SyntaxKind[SyntaxKind["ModuleKeyword"] = 130] = "ModuleKeyword";
2727 SyntaxKind[SyntaxKind["NamespaceKeyword"] = 131] = "NamespaceKeyword";
2728 SyntaxKind[SyntaxKind["NeverKeyword"] = 132] = "NeverKeyword";
2729 SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 133] = "ReadonlyKeyword";
2730 SyntaxKind[SyntaxKind["RequireKeyword"] = 134] = "RequireKeyword";
2731 SyntaxKind[SyntaxKind["NumberKeyword"] = 135] = "NumberKeyword";
2732 SyntaxKind[SyntaxKind["ObjectKeyword"] = 136] = "ObjectKeyword";
2733 SyntaxKind[SyntaxKind["SetKeyword"] = 137] = "SetKeyword";
2734 SyntaxKind[SyntaxKind["StringKeyword"] = 138] = "StringKeyword";
2735 SyntaxKind[SyntaxKind["SymbolKeyword"] = 139] = "SymbolKeyword";
2736 SyntaxKind[SyntaxKind["TypeKeyword"] = 140] = "TypeKeyword";
2737 SyntaxKind[SyntaxKind["UndefinedKeyword"] = 141] = "UndefinedKeyword";
2738 SyntaxKind[SyntaxKind["UniqueKeyword"] = 142] = "UniqueKeyword";
2739 SyntaxKind[SyntaxKind["UnknownKeyword"] = 143] = "UnknownKeyword";
2740 SyntaxKind[SyntaxKind["FromKeyword"] = 144] = "FromKeyword";
2741 SyntaxKind[SyntaxKind["GlobalKeyword"] = 145] = "GlobalKeyword";
2742 SyntaxKind[SyntaxKind["BigIntKeyword"] = 146] = "BigIntKeyword";
2743 SyntaxKind[SyntaxKind["OfKeyword"] = 147] = "OfKeyword";
2744 // Parse tree nodes
2745 // Names
2746 SyntaxKind[SyntaxKind["QualifiedName"] = 148] = "QualifiedName";
2747 SyntaxKind[SyntaxKind["ComputedPropertyName"] = 149] = "ComputedPropertyName";
2748 // Signature elements
2749 SyntaxKind[SyntaxKind["TypeParameter"] = 150] = "TypeParameter";
2750 SyntaxKind[SyntaxKind["Parameter"] = 151] = "Parameter";
2751 SyntaxKind[SyntaxKind["Decorator"] = 152] = "Decorator";
2752 // TypeMember
2753 SyntaxKind[SyntaxKind["PropertySignature"] = 153] = "PropertySignature";
2754 SyntaxKind[SyntaxKind["PropertyDeclaration"] = 154] = "PropertyDeclaration";
2755 SyntaxKind[SyntaxKind["MethodSignature"] = 155] = "MethodSignature";
2756 SyntaxKind[SyntaxKind["MethodDeclaration"] = 156] = "MethodDeclaration";
2757 SyntaxKind[SyntaxKind["Constructor"] = 157] = "Constructor";
2758 SyntaxKind[SyntaxKind["GetAccessor"] = 158] = "GetAccessor";
2759 SyntaxKind[SyntaxKind["SetAccessor"] = 159] = "SetAccessor";
2760 SyntaxKind[SyntaxKind["CallSignature"] = 160] = "CallSignature";
2761 SyntaxKind[SyntaxKind["ConstructSignature"] = 161] = "ConstructSignature";
2762 SyntaxKind[SyntaxKind["IndexSignature"] = 162] = "IndexSignature";
2763 // Type
2764 SyntaxKind[SyntaxKind["TypePredicate"] = 163] = "TypePredicate";
2765 SyntaxKind[SyntaxKind["TypeReference"] = 164] = "TypeReference";
2766 SyntaxKind[SyntaxKind["FunctionType"] = 165] = "FunctionType";
2767 SyntaxKind[SyntaxKind["ConstructorType"] = 166] = "ConstructorType";
2768 SyntaxKind[SyntaxKind["TypeQuery"] = 167] = "TypeQuery";
2769 SyntaxKind[SyntaxKind["TypeLiteral"] = 168] = "TypeLiteral";
2770 SyntaxKind[SyntaxKind["ArrayType"] = 169] = "ArrayType";
2771 SyntaxKind[SyntaxKind["TupleType"] = 170] = "TupleType";
2772 SyntaxKind[SyntaxKind["OptionalType"] = 171] = "OptionalType";
2773 SyntaxKind[SyntaxKind["RestType"] = 172] = "RestType";
2774 SyntaxKind[SyntaxKind["UnionType"] = 173] = "UnionType";
2775 SyntaxKind[SyntaxKind["IntersectionType"] = 174] = "IntersectionType";
2776 SyntaxKind[SyntaxKind["ConditionalType"] = 175] = "ConditionalType";
2777 SyntaxKind[SyntaxKind["InferType"] = 176] = "InferType";
2778 SyntaxKind[SyntaxKind["ParenthesizedType"] = 177] = "ParenthesizedType";
2779 SyntaxKind[SyntaxKind["ThisType"] = 178] = "ThisType";
2780 SyntaxKind[SyntaxKind["TypeOperator"] = 179] = "TypeOperator";
2781 SyntaxKind[SyntaxKind["IndexedAccessType"] = 180] = "IndexedAccessType";
2782 SyntaxKind[SyntaxKind["MappedType"] = 181] = "MappedType";
2783 SyntaxKind[SyntaxKind["LiteralType"] = 182] = "LiteralType";
2784 SyntaxKind[SyntaxKind["ImportType"] = 183] = "ImportType";
2785 // Binding patterns
2786 SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 184] = "ObjectBindingPattern";
2787 SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 185] = "ArrayBindingPattern";
2788 SyntaxKind[SyntaxKind["BindingElement"] = 186] = "BindingElement";
2789 // Expression
2790 SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 187] = "ArrayLiteralExpression";
2791 SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 188] = "ObjectLiteralExpression";
2792 SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 189] = "PropertyAccessExpression";
2793 SyntaxKind[SyntaxKind["ElementAccessExpression"] = 190] = "ElementAccessExpression";
2794 SyntaxKind[SyntaxKind["CallExpression"] = 191] = "CallExpression";
2795 SyntaxKind[SyntaxKind["NewExpression"] = 192] = "NewExpression";
2796 SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 193] = "TaggedTemplateExpression";
2797 SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 194] = "TypeAssertionExpression";
2798 SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 195] = "ParenthesizedExpression";
2799 SyntaxKind[SyntaxKind["FunctionExpression"] = 196] = "FunctionExpression";
2800 SyntaxKind[SyntaxKind["ArrowFunction"] = 197] = "ArrowFunction";
2801 SyntaxKind[SyntaxKind["DeleteExpression"] = 198] = "DeleteExpression";
2802 SyntaxKind[SyntaxKind["TypeOfExpression"] = 199] = "TypeOfExpression";
2803 SyntaxKind[SyntaxKind["VoidExpression"] = 200] = "VoidExpression";
2804 SyntaxKind[SyntaxKind["AwaitExpression"] = 201] = "AwaitExpression";
2805 SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 202] = "PrefixUnaryExpression";
2806 SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 203] = "PostfixUnaryExpression";
2807 SyntaxKind[SyntaxKind["BinaryExpression"] = 204] = "BinaryExpression";
2808 SyntaxKind[SyntaxKind["ConditionalExpression"] = 205] = "ConditionalExpression";
2809 SyntaxKind[SyntaxKind["TemplateExpression"] = 206] = "TemplateExpression";
2810 SyntaxKind[SyntaxKind["YieldExpression"] = 207] = "YieldExpression";
2811 SyntaxKind[SyntaxKind["SpreadElement"] = 208] = "SpreadElement";
2812 SyntaxKind[SyntaxKind["ClassExpression"] = 209] = "ClassExpression";
2813 SyntaxKind[SyntaxKind["OmittedExpression"] = 210] = "OmittedExpression";
2814 SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 211] = "ExpressionWithTypeArguments";
2815 SyntaxKind[SyntaxKind["AsExpression"] = 212] = "AsExpression";
2816 SyntaxKind[SyntaxKind["NonNullExpression"] = 213] = "NonNullExpression";
2817 SyntaxKind[SyntaxKind["MetaProperty"] = 214] = "MetaProperty";
2818 SyntaxKind[SyntaxKind["SyntheticExpression"] = 215] = "SyntheticExpression";
2819 // Misc
2820 SyntaxKind[SyntaxKind["TemplateSpan"] = 216] = "TemplateSpan";
2821 SyntaxKind[SyntaxKind["SemicolonClassElement"] = 217] = "SemicolonClassElement";
2822 // Element
2823 SyntaxKind[SyntaxKind["Block"] = 218] = "Block";
2824 SyntaxKind[SyntaxKind["VariableStatement"] = 219] = "VariableStatement";
2825 SyntaxKind[SyntaxKind["EmptyStatement"] = 220] = "EmptyStatement";
2826 SyntaxKind[SyntaxKind["ExpressionStatement"] = 221] = "ExpressionStatement";
2827 SyntaxKind[SyntaxKind["IfStatement"] = 222] = "IfStatement";
2828 SyntaxKind[SyntaxKind["DoStatement"] = 223] = "DoStatement";
2829 SyntaxKind[SyntaxKind["WhileStatement"] = 224] = "WhileStatement";
2830 SyntaxKind[SyntaxKind["ForStatement"] = 225] = "ForStatement";
2831 SyntaxKind[SyntaxKind["ForInStatement"] = 226] = "ForInStatement";
2832 SyntaxKind[SyntaxKind["ForOfStatement"] = 227] = "ForOfStatement";
2833 SyntaxKind[SyntaxKind["ContinueStatement"] = 228] = "ContinueStatement";
2834 SyntaxKind[SyntaxKind["BreakStatement"] = 229] = "BreakStatement";
2835 SyntaxKind[SyntaxKind["ReturnStatement"] = 230] = "ReturnStatement";
2836 SyntaxKind[SyntaxKind["WithStatement"] = 231] = "WithStatement";
2837 SyntaxKind[SyntaxKind["SwitchStatement"] = 232] = "SwitchStatement";
2838 SyntaxKind[SyntaxKind["LabeledStatement"] = 233] = "LabeledStatement";
2839 SyntaxKind[SyntaxKind["ThrowStatement"] = 234] = "ThrowStatement";
2840 SyntaxKind[SyntaxKind["TryStatement"] = 235] = "TryStatement";
2841 SyntaxKind[SyntaxKind["DebuggerStatement"] = 236] = "DebuggerStatement";
2842 SyntaxKind[SyntaxKind["VariableDeclaration"] = 237] = "VariableDeclaration";
2843 SyntaxKind[SyntaxKind["VariableDeclarationList"] = 238] = "VariableDeclarationList";
2844 SyntaxKind[SyntaxKind["FunctionDeclaration"] = 239] = "FunctionDeclaration";
2845 SyntaxKind[SyntaxKind["ClassDeclaration"] = 240] = "ClassDeclaration";
2846 SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 241] = "InterfaceDeclaration";
2847 SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 242] = "TypeAliasDeclaration";
2848 SyntaxKind[SyntaxKind["EnumDeclaration"] = 243] = "EnumDeclaration";
2849 SyntaxKind[SyntaxKind["ModuleDeclaration"] = 244] = "ModuleDeclaration";
2850 SyntaxKind[SyntaxKind["ModuleBlock"] = 245] = "ModuleBlock";
2851 SyntaxKind[SyntaxKind["CaseBlock"] = 246] = "CaseBlock";
2852 SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 247] = "NamespaceExportDeclaration";
2853 SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 248] = "ImportEqualsDeclaration";
2854 SyntaxKind[SyntaxKind["ImportDeclaration"] = 249] = "ImportDeclaration";
2855 SyntaxKind[SyntaxKind["ImportClause"] = 250] = "ImportClause";
2856 SyntaxKind[SyntaxKind["NamespaceImport"] = 251] = "NamespaceImport";
2857 SyntaxKind[SyntaxKind["NamedImports"] = 252] = "NamedImports";
2858 SyntaxKind[SyntaxKind["ImportSpecifier"] = 253] = "ImportSpecifier";
2859 SyntaxKind[SyntaxKind["ExportAssignment"] = 254] = "ExportAssignment";
2860 SyntaxKind[SyntaxKind["ExportDeclaration"] = 255] = "ExportDeclaration";
2861 SyntaxKind[SyntaxKind["NamedExports"] = 256] = "NamedExports";
2862 SyntaxKind[SyntaxKind["ExportSpecifier"] = 257] = "ExportSpecifier";
2863 SyntaxKind[SyntaxKind["MissingDeclaration"] = 258] = "MissingDeclaration";
2864 // Module references
2865 SyntaxKind[SyntaxKind["ExternalModuleReference"] = 259] = "ExternalModuleReference";
2866 // JSX
2867 SyntaxKind[SyntaxKind["JsxElement"] = 260] = "JsxElement";
2868 SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 261] = "JsxSelfClosingElement";
2869 SyntaxKind[SyntaxKind["JsxOpeningElement"] = 262] = "JsxOpeningElement";
2870 SyntaxKind[SyntaxKind["JsxClosingElement"] = 263] = "JsxClosingElement";
2871 SyntaxKind[SyntaxKind["JsxFragment"] = 264] = "JsxFragment";
2872 SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 265] = "JsxOpeningFragment";
2873 SyntaxKind[SyntaxKind["JsxClosingFragment"] = 266] = "JsxClosingFragment";
2874 SyntaxKind[SyntaxKind["JsxAttribute"] = 267] = "JsxAttribute";
2875 SyntaxKind[SyntaxKind["JsxAttributes"] = 268] = "JsxAttributes";
2876 SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 269] = "JsxSpreadAttribute";
2877 SyntaxKind[SyntaxKind["JsxExpression"] = 270] = "JsxExpression";
2878 // Clauses
2879 SyntaxKind[SyntaxKind["CaseClause"] = 271] = "CaseClause";
2880 SyntaxKind[SyntaxKind["DefaultClause"] = 272] = "DefaultClause";
2881 SyntaxKind[SyntaxKind["HeritageClause"] = 273] = "HeritageClause";
2882 SyntaxKind[SyntaxKind["CatchClause"] = 274] = "CatchClause";
2883 // Property assignments
2884 SyntaxKind[SyntaxKind["PropertyAssignment"] = 275] = "PropertyAssignment";
2885 SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 276] = "ShorthandPropertyAssignment";
2886 SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
2887 // Enum
2888 SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
2889 // Unparsed
2890 SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
2891 SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
2892 SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
2893 SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
2894 SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
2895 // Top-level nodes
2896 SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
2897 SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
2898 SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
2899 SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
2900 // JSDoc nodes
2901 SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
2902 // The * type
2903 SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
2904 // The ? type
2905 SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
2906 SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
2907 SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
2908 SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
2909 SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
2910 SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
2911 SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
2912 SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
2913 SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
2914 SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
2915 SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
2916 SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
2917 SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
2918 SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
2919 SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
2920 SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
2921 SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
2922 SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
2923 SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
2924 SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
2925 SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
2926 // Synthesized list
2927 SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
2928 // Transformation nodes
2929 SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
2930 SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
2931 SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
2932 SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
2933 SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
2934 // Enum value count
2935 SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
2936 // Markers
2937 SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
2938 SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
2939 SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 60] = "FirstCompoundAssignment";
2940 SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 71] = "LastCompoundAssignment";
2941 SyntaxKind[SyntaxKind["FirstReservedWord"] = 73] = "FirstReservedWord";
2942 SyntaxKind[SyntaxKind["LastReservedWord"] = 108] = "LastReservedWord";
2943 SyntaxKind[SyntaxKind["FirstKeyword"] = 73] = "FirstKeyword";
2944 SyntaxKind[SyntaxKind["LastKeyword"] = 147] = "LastKeyword";
2945 SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 109] = "FirstFutureReservedWord";
2946 SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 117] = "LastFutureReservedWord";
2947 SyntaxKind[SyntaxKind["FirstTypeNode"] = 163] = "FirstTypeNode";
2948 SyntaxKind[SyntaxKind["LastTypeNode"] = 183] = "LastTypeNode";
2949 SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
2950 SyntaxKind[SyntaxKind["LastPunctuation"] = 71] = "LastPunctuation";
2951 SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
2952 SyntaxKind[SyntaxKind["LastToken"] = 147] = "LastToken";
2953 SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
2954 SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
2955 SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
2956 SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
2957 SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
2958 SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
2959 SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
2960 SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
2961 SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
2962 SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
2963 SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
2964 SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
2965 SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
2966 /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
2967 /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
2968 })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
2969 var NodeFlags;
2970 (function (NodeFlags) {
2971 NodeFlags[NodeFlags["None"] = 0] = "None";
2972 NodeFlags[NodeFlags["Let"] = 1] = "Let";
2973 NodeFlags[NodeFlags["Const"] = 2] = "Const";
2974 NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
2975 NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
2976 NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
2977 NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext";
2978 NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis";
2979 NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn";
2980 NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn";
2981 NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation";
2982 NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions";
2983 NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext";
2984 NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext";
2985 NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext";
2986 NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext";
2987 NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError";
2988 NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile";
2989 NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError";
2990 NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData";
2991 // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
2992 // walking the tree if the flags are not set. However, these flags are just a approximation
2993 // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
2994 // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
2995 // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
2996 // However, the removal operation should not occur often and in the case of the
2997 // removal, it is likely that users will add the import anyway.
2998 // The advantage of this approach is its simplicity. For the case of batch compilation,
2999 // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
3000 /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport";
3001 /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta";
3002 NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc";
3003 /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient";
3004 /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement";
3005 NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile";
3006 NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
3007 NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags";
3008 NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags";
3009 // Parsing context flags
3010 NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags";
3011 // Exclude these flags when parsing a Type
3012 NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags";
3013 // Represents all flags that are potentially set once and
3014 // never cleared on SourceFiles which get re-used in between incremental parses.
3015 // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
3016 /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags";
3017 })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
3018 var ModifierFlags;
3019 (function (ModifierFlags) {
3020 ModifierFlags[ModifierFlags["None"] = 0] = "None";
3021 ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
3022 ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
3023 ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
3024 ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
3025 ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
3026 ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
3027 ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
3028 ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
3029 ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
3030 ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
3031 ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
3032 ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
3033 ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
3034 // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
3035 ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
3036 ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
3037 ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
3038 ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
3039 ModifierFlags[ModifierFlags["All"] = 3071] = "All";
3040 })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
3041 var JsxFlags;
3042 (function (JsxFlags) {
3043 JsxFlags[JsxFlags["None"] = 0] = "None";
3044 /** An element from a named property of the JSX.IntrinsicElements interface */
3045 JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
3046 /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
3047 JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
3048 JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
3049 })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
3050 /* @internal */
3051 var RelationComparisonResult;
3052 (function (RelationComparisonResult) {
3053 RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
3054 RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
3055 RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported";
3056 })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
3057 /*@internal*/
3058 var GeneratedIdentifierFlags;
3059 (function (GeneratedIdentifierFlags) {
3060 // Kinds
3061 GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
3062 GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
3063 GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
3064 GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
3065 GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
3066 GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
3067 // Flags
3068 GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
3069 GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
3070 GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
3071 })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
3072 var TokenFlags;
3073 (function (TokenFlags) {
3074 TokenFlags[TokenFlags["None"] = 0] = "None";
3075 /* @internal */
3076 TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
3077 /* @internal */
3078 TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
3079 /* @internal */
3080 TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
3081 /* @internal */
3082 TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
3083 TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
3084 TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
3085 TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
3086 TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
3087 TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
3088 /* @internal */
3089 TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
3090 /* @internal */
3091 TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
3092 /* @internal */
3093 TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
3094 })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
3095 var FlowFlags;
3096 (function (FlowFlags) {
3097 FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
3098 FlowFlags[FlowFlags["Start"] = 2] = "Start";
3099 FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
3100 FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
3101 FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
3102 FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
3103 FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
3104 FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
3105 FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
3106 FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced";
3107 FlowFlags[FlowFlags["Shared"] = 1024] = "Shared";
3108 FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally";
3109 FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally";
3110 FlowFlags[FlowFlags["Label"] = 12] = "Label";
3111 FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
3112 })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
3113 var OperationCanceledException = /** @class */ (function () {
3114 function OperationCanceledException() {
3115 }
3116 return OperationCanceledException;
3117 }());
3118 ts.OperationCanceledException = OperationCanceledException;
3119 /* @internal */
3120 var StructureIsReused;
3121 (function (StructureIsReused) {
3122 StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
3123 StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
3124 StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
3125 })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
3126 /** Return code used by getEmitOutput function to indicate status of the function */
3127 var ExitStatus;
3128 (function (ExitStatus) {
3129 // Compiler ran successfully. Either this was a simple do-nothing compilation (for example,
3130 // when -version or -help was provided, or this was a normal compilation, no diagnostics
3131 // were produced, and all outputs were generated successfully.
3132 ExitStatus[ExitStatus["Success"] = 0] = "Success";
3133 // Diagnostics were produced and because of them no code was generated.
3134 ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
3135 // Diagnostics were produced and outputs were generated in spite of them.
3136 ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
3137 })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
3138 /* @internal */
3139 var UnionReduction;
3140 (function (UnionReduction) {
3141 UnionReduction[UnionReduction["None"] = 0] = "None";
3142 UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
3143 UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
3144 })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
3145 // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
3146 var NodeBuilderFlags;
3147 (function (NodeBuilderFlags) {
3148 NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
3149 // Options
3150 NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
3151 NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3152 NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
3153 NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3154 NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
3155 NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3156 NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3157 NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
3158 NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3159 NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
3160 NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3161 NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3162 NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3163 NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3164 NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3165 // Error handling
3166 NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
3167 NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
3168 NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
3169 NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
3170 NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
3171 NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3172 NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
3173 // Errors (cont.)
3174 NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
3175 /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
3176 NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
3177 // State
3178 NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
3179 NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3180 NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
3181 NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
3182 })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
3183 // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
3184 var TypeFormatFlags;
3185 (function (TypeFormatFlags) {
3186 TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
3187 TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
3188 TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3189 // hole because there's a hole in node builder flags
3190 TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3191 // hole because there's a hole in node builder flags
3192 TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3193 TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3194 // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
3195 TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3196 // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
3197 TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3198 TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3199 TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3200 TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3201 TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3202 // even though `T` can't be accessed in the current scope.
3203 // Error Handling
3204 TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3205 // TypeFormatFlags exclusive
3206 TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
3207 TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
3208 // State
3209 TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
3210 TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
3211 TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
3212 TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3213 /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
3214 TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask";
3215 })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
3216 var SymbolFormatFlags;
3217 (function (SymbolFormatFlags) {
3218 SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
3219 // Write symbols's type argument if it is instantiated symbol
3220 // eg. class C<T> { p: T } <-- Show p as C<T>.p here
3221 // var a: C<number>;
3222 // var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
3223 SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
3224 // Use only external alias information to get the symbol name in the given context
3225 // eg. module m { export class c { } } import x = m.c;
3226 // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
3227 SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
3228 // Build symbol name using any nodes needed, instead of just components of an entity name
3229 SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
3230 // Prefer aliases which are not directly visible
3231 SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
3232 // Skip building an accessible symbol chain
3233 /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
3234 })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
3235 /* @internal */
3236 var SymbolAccessibility;
3237 (function (SymbolAccessibility) {
3238 SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
3239 SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
3240 SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
3241 })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
3242 /* @internal */
3243 var SyntheticSymbolKind;
3244 (function (SyntheticSymbolKind) {
3245 SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
3246 SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
3247 })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
3248 var TypePredicateKind;
3249 (function (TypePredicateKind) {
3250 TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
3251 TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
3252 })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
3253 /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
3254 /* @internal */
3255 var TypeReferenceSerializationKind;
3256 (function (TypeReferenceSerializationKind) {
3257 TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
3258 // should be emitted using a safe fallback.
3259 TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
3260 // function that can be reached at runtime (e.g. a `class`
3261 // declaration or a `var` declaration for the static side
3262 // of a type, such as the global `Promise` type in lib.d.ts).
3263 TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
3264 TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
3265 TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
3266 TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
3267 TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
3268 TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
3269 TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
3270 TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
3271 TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
3272 // with call signatures.
3273 TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
3274 })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
3275 var SymbolFlags;
3276 (function (SymbolFlags) {
3277 SymbolFlags[SymbolFlags["None"] = 0] = "None";
3278 SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
3279 SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
3280 SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
3281 SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
3282 SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
3283 SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
3284 SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
3285 SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
3286 SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
3287 SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
3288 SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
3289 SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
3290 SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
3291 SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
3292 SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
3293 SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
3294 SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
3295 SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
3296 SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
3297 SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
3298 SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
3299 SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
3300 SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
3301 SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
3302 SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
3303 SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
3304 SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
3305 SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
3306 /* @internal */
3307 SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
3308 SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
3309 SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
3310 SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value";
3311 SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type";
3312 SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
3313 SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
3314 SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
3315 // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
3316 // same name, or any other value that is not a variable, e.g. ValueModule or Class
3317 SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes";
3318 // Block-scoped declarations are not allowed to be re-declared
3319 // they can not merge with anything in the value space
3320 SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes";
3321 SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes";
3322 SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
3323 SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes";
3324 SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes";
3325 SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes";
3326 SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes";
3327 SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes";
3328 SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes";
3329 SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
3330 SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
3331 SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes";
3332 SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes";
3333 SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes";
3334 SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes";
3335 SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes";
3336 SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
3337 SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
3338 SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
3339 SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
3340 SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
3341 SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
3342 /* @internal */
3343 // The set of things we consider semantically classifiable. Used to speed up the LS during
3344 // classification.
3345 SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
3346 /* @internal */
3347 SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer";
3348 })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
3349 /* @internal */
3350 var EnumKind;
3351 (function (EnumKind) {
3352 EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
3353 EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
3354 })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
3355 /* @internal */
3356 var CheckFlags;
3357 (function (CheckFlags) {
3358 CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
3359 CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
3360 CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
3361 CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
3362 CheckFlags[CheckFlags["Partial"] = 16] = "Partial";
3363 CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType";
3364 CheckFlags[CheckFlags["HasLiteralType"] = 64] = "HasLiteralType";
3365 CheckFlags[CheckFlags["ContainsPublic"] = 128] = "ContainsPublic";
3366 CheckFlags[CheckFlags["ContainsProtected"] = 256] = "ContainsProtected";
3367 CheckFlags[CheckFlags["ContainsPrivate"] = 512] = "ContainsPrivate";
3368 CheckFlags[CheckFlags["ContainsStatic"] = 1024] = "ContainsStatic";
3369 CheckFlags[CheckFlags["Late"] = 2048] = "Late";
3370 CheckFlags[CheckFlags["ReverseMapped"] = 4096] = "ReverseMapped";
3371 CheckFlags[CheckFlags["OptionalParameter"] = 8192] = "OptionalParameter";
3372 CheckFlags[CheckFlags["RestParameter"] = 16384] = "RestParameter";
3373 CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
3374 CheckFlags[CheckFlags["Discriminant"] = 96] = "Discriminant";
3375 })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
3376 var InternalSymbolName;
3377 (function (InternalSymbolName) {
3378 InternalSymbolName["Call"] = "__call";
3379 InternalSymbolName["Constructor"] = "__constructor";
3380 InternalSymbolName["New"] = "__new";
3381 InternalSymbolName["Index"] = "__index";
3382 InternalSymbolName["ExportStar"] = "__export";
3383 InternalSymbolName["Global"] = "__global";
3384 InternalSymbolName["Missing"] = "__missing";
3385 InternalSymbolName["Type"] = "__type";
3386 InternalSymbolName["Object"] = "__object";
3387 InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
3388 InternalSymbolName["Class"] = "__class";
3389 InternalSymbolName["Function"] = "__function";
3390 InternalSymbolName["Computed"] = "__computed";
3391 InternalSymbolName["Resolving"] = "__resolving__";
3392 InternalSymbolName["ExportEquals"] = "export=";
3393 InternalSymbolName["Default"] = "default";
3394 InternalSymbolName["This"] = "this";
3395 })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
3396 /* @internal */
3397 var NodeCheckFlags;
3398 (function (NodeCheckFlags) {
3399 NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
3400 NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
3401 NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
3402 NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
3403 NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
3404 NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
3405 NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
3406 NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
3407 NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
3408 NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
3409 NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
3410 NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
3411 NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
3412 NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
3413 NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
3414 NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
3415 NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
3416 NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
3417 NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
3418 NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
3419 NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
3420 NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
3421 })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
3422 var TypeFlags;
3423 (function (TypeFlags) {
3424 TypeFlags[TypeFlags["Any"] = 1] = "Any";
3425 TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
3426 TypeFlags[TypeFlags["String"] = 4] = "String";
3427 TypeFlags[TypeFlags["Number"] = 8] = "Number";
3428 TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
3429 TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
3430 TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
3431 TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
3432 TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
3433 TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
3434 TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
3435 TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
3436 TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
3437 TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
3438 TypeFlags[TypeFlags["Void"] = 16384] = "Void";
3439 TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
3440 TypeFlags[TypeFlags["Null"] = 65536] = "Null";
3441 TypeFlags[TypeFlags["Never"] = 131072] = "Never";
3442 TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
3443 TypeFlags[TypeFlags["Object"] = 524288] = "Object";
3444 TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
3445 TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
3446 TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
3447 TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
3448 TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
3449 TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
3450 TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
3451 /* @internal */
3452 TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
3453 /* @internal */
3454 TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
3455 TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
3456 TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
3457 TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
3458 /* @internal */
3459 TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
3460 /* @internal */
3461 TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
3462 TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
3463 /* @internal */
3464 TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
3465 /* @internal */
3466 TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
3467 TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike";
3468 TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
3469 TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
3470 TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
3471 TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
3472 TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
3473 TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
3474 /* @internal */
3475 TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains";
3476 TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
3477 TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
3478 TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
3479 TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
3480 TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
3481 TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
3482 TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
3483 /* @internal */
3484 TypeFlags[TypeFlags["ObjectFlagsType"] = 3899392] = "ObjectFlagsType";
3485 // 'Narrowable' types are types where narrowing actually narrows.
3486 // This *should* be every type other than null, undefined, void, and never
3487 TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
3488 TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
3489 /* @internal */
3490 TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
3491 // The following flags are aggregated during union and intersection type construction
3492 /* @internal */
3493 TypeFlags[TypeFlags["IncludesMask"] = 1835007] = "IncludesMask";
3494 // The following flags are used for different purposes during union and intersection type construction
3495 /* @internal */
3496 TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
3497 /* @internal */
3498 TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType";
3499 /* @internal */
3500 TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard";
3501 /* @internal */
3502 TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject";
3503 // The following flag is used for different purposes by maybeTypeOfKind
3504 /* @internal */
3505 TypeFlags[TypeFlags["GenericMappedType"] = 131072] = "GenericMappedType";
3506 })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
3507 var ObjectFlags;
3508 (function (ObjectFlags) {
3509 ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
3510 ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
3511 ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
3512 ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
3513 ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
3514 ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
3515 ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
3516 ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
3517 ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
3518 ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
3519 ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
3520 ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
3521 ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
3522 ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
3523 ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
3524 ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
3525 /* @internal */
3526 ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion";
3527 /* @internal */
3528 ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType";
3529 /* @internal */
3530 ObjectFlags[ObjectFlags["ContainsObjectLiteral"] = 262144] = "ContainsObjectLiteral";
3531 /* @internal */
3532 ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType";
3533 ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
3534 /* @internal */
3535 ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening";
3536 /* @internal */
3537 ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags";
3538 })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
3539 /* @internal */
3540 var Variance;
3541 (function (Variance) {
3542 Variance[Variance["Invariant"] = 0] = "Invariant";
3543 Variance[Variance["Covariant"] = 1] = "Covariant";
3544 Variance[Variance["Contravariant"] = 2] = "Contravariant";
3545 Variance[Variance["Bivariant"] = 3] = "Bivariant";
3546 Variance[Variance["Independent"] = 4] = "Independent";
3547 })(Variance = ts.Variance || (ts.Variance = {}));
3548 /* @internal */
3549 var JsxReferenceKind;
3550 (function (JsxReferenceKind) {
3551 JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
3552 JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
3553 JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
3554 })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
3555 var SignatureKind;
3556 (function (SignatureKind) {
3557 SignatureKind[SignatureKind["Call"] = 0] = "Call";
3558 SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
3559 })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
3560 var IndexKind;
3561 (function (IndexKind) {
3562 IndexKind[IndexKind["String"] = 0] = "String";
3563 IndexKind[IndexKind["Number"] = 1] = "Number";
3564 })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
3565 var InferencePriority;
3566 (function (InferencePriority) {
3567 InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
3568 InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
3569 InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint";
3570 InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType";
3571 InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof";
3572 InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints";
3573 InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict";
3574 InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination";
3575 })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
3576 /* @internal */
3577 var InferenceFlags;
3578 (function (InferenceFlags) {
3579 InferenceFlags[InferenceFlags["None"] = 0] = "None";
3580 InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
3581 InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
3582 InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
3583 })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
3584 /**
3585 * Ternary values are defined such that
3586 * x & y is False if either x or y is False.
3587 * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
3588 * x & y is True if both x and y are True.
3589 * x | y is False if both x and y are False.
3590 * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
3591 * x | y is True if either x or y is True.
3592 */
3593 /* @internal */
3594 var Ternary;
3595 (function (Ternary) {
3596 Ternary[Ternary["False"] = 0] = "False";
3597 Ternary[Ternary["Maybe"] = 1] = "Maybe";
3598 Ternary[Ternary["True"] = -1] = "True";
3599 })(Ternary = ts.Ternary || (ts.Ternary = {}));
3600 /* @internal */
3601 var AssignmentDeclarationKind;
3602 (function (AssignmentDeclarationKind) {
3603 AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
3604 /// exports.name = expr
3605 AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
3606 /// module.exports = expr
3607 AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
3608 /// className.prototype.name = expr
3609 AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
3610 /// this.name = expr
3611 AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
3612 // F.name = expr
3613 AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
3614 // F.prototype = { ... }
3615 AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
3616 // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
3617 // Object.defineProperty(x, 'name', { get: Function, set: Function });
3618 // Object.defineProperty(x, 'name', { get: Function });
3619 // Object.defineProperty(x, 'name', { set: Function });
3620 AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
3621 // Object.defineProperty(exports || module.exports, 'name', ...);
3622 AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
3623 // Object.defineProperty(Foo.prototype, 'name', ...);
3624 AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
3625 })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
3626 var DiagnosticCategory;
3627 (function (DiagnosticCategory) {
3628 DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
3629 DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
3630 DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
3631 DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
3632 })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
3633 /* @internal */
3634 function diagnosticCategoryName(d, lowerCase) {
3635 if (lowerCase === void 0) { lowerCase = true; }
3636 var name = DiagnosticCategory[d.category];
3637 return lowerCase ? name.toLowerCase() : name;
3638 }
3639 ts.diagnosticCategoryName = diagnosticCategoryName;
3640 var ModuleResolutionKind;
3641 (function (ModuleResolutionKind) {
3642 ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
3643 ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
3644 })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
3645 var ModuleKind;
3646 (function (ModuleKind) {
3647 ModuleKind[ModuleKind["None"] = 0] = "None";
3648 ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
3649 ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
3650 ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
3651 ModuleKind[ModuleKind["System"] = 4] = "System";
3652 ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
3653 ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext";
3654 })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
3655 var JsxEmit;
3656 (function (JsxEmit) {
3657 JsxEmit[JsxEmit["None"] = 0] = "None";
3658 JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
3659 JsxEmit[JsxEmit["React"] = 2] = "React";
3660 JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
3661 })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
3662 var NewLineKind;
3663 (function (NewLineKind) {
3664 NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
3665 NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
3666 })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
3667 var ScriptKind;
3668 (function (ScriptKind) {
3669 ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
3670 ScriptKind[ScriptKind["JS"] = 1] = "JS";
3671 ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
3672 ScriptKind[ScriptKind["TS"] = 3] = "TS";
3673 ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
3674 ScriptKind[ScriptKind["External"] = 5] = "External";
3675 ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
3676 /**
3677 * Used on extensions that doesn't define the ScriptKind but the content defines it.
3678 * Deferred extensions are going to be included in all project contexts.
3679 */
3680 ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
3681 })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
3682 var ScriptTarget;
3683 (function (ScriptTarget) {
3684 ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
3685 ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
3686 ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
3687 ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
3688 ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
3689 ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
3690 ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
3691 ScriptTarget[ScriptTarget["ESNext"] = 7] = "ESNext";
3692 ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
3693 ScriptTarget[ScriptTarget["Latest"] = 7] = "Latest";
3694 })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
3695 var LanguageVariant;
3696 (function (LanguageVariant) {
3697 LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
3698 LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
3699 })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
3700 var WatchDirectoryFlags;
3701 (function (WatchDirectoryFlags) {
3702 WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
3703 WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
3704 })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
3705 /* @internal */
3706 var CharacterCodes;
3707 (function (CharacterCodes) {
3708 CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
3709 CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
3710 CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
3711 CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
3712 CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
3713 CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
3714 CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
3715 // Unicode 3.0 space characters
3716 CharacterCodes[CharacterCodes["space"] = 32] = "space";
3717 CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
3718 CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
3719 CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
3720 CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
3721 CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
3722 CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
3723 CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
3724 CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
3725 CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
3726 CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
3727 CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
3728 CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
3729 CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
3730 CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
3731 CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
3732 CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
3733 CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
3734 CharacterCodes[CharacterCodes["_"] = 95] = "_";
3735 CharacterCodes[CharacterCodes["$"] = 36] = "$";
3736 CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
3737 CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
3738 CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
3739 CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
3740 CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
3741 CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
3742 CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
3743 CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
3744 CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
3745 CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
3746 CharacterCodes[CharacterCodes["a"] = 97] = "a";
3747 CharacterCodes[CharacterCodes["b"] = 98] = "b";
3748 CharacterCodes[CharacterCodes["c"] = 99] = "c";
3749 CharacterCodes[CharacterCodes["d"] = 100] = "d";
3750 CharacterCodes[CharacterCodes["e"] = 101] = "e";
3751 CharacterCodes[CharacterCodes["f"] = 102] = "f";
3752 CharacterCodes[CharacterCodes["g"] = 103] = "g";
3753 CharacterCodes[CharacterCodes["h"] = 104] = "h";
3754 CharacterCodes[CharacterCodes["i"] = 105] = "i";
3755 CharacterCodes[CharacterCodes["j"] = 106] = "j";
3756 CharacterCodes[CharacterCodes["k"] = 107] = "k";
3757 CharacterCodes[CharacterCodes["l"] = 108] = "l";
3758 CharacterCodes[CharacterCodes["m"] = 109] = "m";
3759 CharacterCodes[CharacterCodes["n"] = 110] = "n";
3760 CharacterCodes[CharacterCodes["o"] = 111] = "o";
3761 CharacterCodes[CharacterCodes["p"] = 112] = "p";
3762 CharacterCodes[CharacterCodes["q"] = 113] = "q";
3763 CharacterCodes[CharacterCodes["r"] = 114] = "r";
3764 CharacterCodes[CharacterCodes["s"] = 115] = "s";
3765 CharacterCodes[CharacterCodes["t"] = 116] = "t";
3766 CharacterCodes[CharacterCodes["u"] = 117] = "u";
3767 CharacterCodes[CharacterCodes["v"] = 118] = "v";
3768 CharacterCodes[CharacterCodes["w"] = 119] = "w";
3769 CharacterCodes[CharacterCodes["x"] = 120] = "x";
3770 CharacterCodes[CharacterCodes["y"] = 121] = "y";
3771 CharacterCodes[CharacterCodes["z"] = 122] = "z";
3772 CharacterCodes[CharacterCodes["A"] = 65] = "A";
3773 CharacterCodes[CharacterCodes["B"] = 66] = "B";
3774 CharacterCodes[CharacterCodes["C"] = 67] = "C";
3775 CharacterCodes[CharacterCodes["D"] = 68] = "D";
3776 CharacterCodes[CharacterCodes["E"] = 69] = "E";
3777 CharacterCodes[CharacterCodes["F"] = 70] = "F";
3778 CharacterCodes[CharacterCodes["G"] = 71] = "G";
3779 CharacterCodes[CharacterCodes["H"] = 72] = "H";
3780 CharacterCodes[CharacterCodes["I"] = 73] = "I";
3781 CharacterCodes[CharacterCodes["J"] = 74] = "J";
3782 CharacterCodes[CharacterCodes["K"] = 75] = "K";
3783 CharacterCodes[CharacterCodes["L"] = 76] = "L";
3784 CharacterCodes[CharacterCodes["M"] = 77] = "M";
3785 CharacterCodes[CharacterCodes["N"] = 78] = "N";
3786 CharacterCodes[CharacterCodes["O"] = 79] = "O";
3787 CharacterCodes[CharacterCodes["P"] = 80] = "P";
3788 CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
3789 CharacterCodes[CharacterCodes["R"] = 82] = "R";
3790 CharacterCodes[CharacterCodes["S"] = 83] = "S";
3791 CharacterCodes[CharacterCodes["T"] = 84] = "T";
3792 CharacterCodes[CharacterCodes["U"] = 85] = "U";
3793 CharacterCodes[CharacterCodes["V"] = 86] = "V";
3794 CharacterCodes[CharacterCodes["W"] = 87] = "W";
3795 CharacterCodes[CharacterCodes["X"] = 88] = "X";
3796 CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
3797 CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
3798 CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
3799 CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
3800 CharacterCodes[CharacterCodes["at"] = 64] = "at";
3801 CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
3802 CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
3803 CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
3804 CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
3805 CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
3806 CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
3807 CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
3808 CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
3809 CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
3810 CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
3811 CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
3812 CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
3813 CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
3814 CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
3815 CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
3816 CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
3817 CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
3818 CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
3819 CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
3820 CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
3821 CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
3822 CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
3823 CharacterCodes[CharacterCodes["question"] = 63] = "question";
3824 CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
3825 CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
3826 CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
3827 CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
3828 CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
3829 CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
3830 CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
3831 CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
3832 CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
3833 })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
3834 var Extension;
3835 (function (Extension) {
3836 Extension["Ts"] = ".ts";
3837 Extension["Tsx"] = ".tsx";
3838 Extension["Dts"] = ".d.ts";
3839 Extension["Js"] = ".js";
3840 Extension["Jsx"] = ".jsx";
3841 Extension["Json"] = ".json";
3842 Extension["TsBuildInfo"] = ".tsbuildinfo";
3843 })(Extension = ts.Extension || (ts.Extension = {}));
3844 /* @internal */
3845 var TransformFlags;
3846 (function (TransformFlags) {
3847 TransformFlags[TransformFlags["None"] = 0] = "None";
3848 // Facts
3849 // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
3850 TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
3851 TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
3852 TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
3853 TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019";
3854 TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018";
3855 TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017";
3856 TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016";
3857 TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015";
3858 TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator";
3859 TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment";
3860 // Markers
3861 // - Flags used to indicate that a subtree contains a specific transformation.
3862 TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax";
3863 TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis";
3864 TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread";
3865 TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread";
3866 TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName";
3867 TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding";
3868 TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern";
3869 TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield";
3870 TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion";
3871 TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport";
3872 // Please leave this as 1 << 29.
3873 // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
3874 // It is a good reminder of how much room we have left
3875 TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
3876 // Assertions
3877 // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
3878 TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
3879 TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
3880 TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
3881 TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019";
3882 TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018";
3883 TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017";
3884 TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016";
3885 TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015";
3886 TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator";
3887 TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment";
3888 // Scope Exclusions
3889 // - Bitmasks that exclude flags from propagating out of a specific context
3890 // into the subtree flags of their container.
3891 TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
3892 TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
3893 TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
3894 TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes";
3895 TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes";
3896 TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes";
3897 TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes";
3898 TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes";
3899 TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes";
3900 TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes";
3901 TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
3902 TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes";
3903 TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes";
3904 TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes";
3905 TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
3906 TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes";
3907 TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes";
3908 // Propagating flags
3909 // - Bitmasks for flags that should propagate from a child
3910 TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags";
3911 // Masks
3912 // - Additional bitmasks
3913 })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
3914 var EmitFlags;
3915 (function (EmitFlags) {
3916 EmitFlags[EmitFlags["None"] = 0] = "None";
3917 EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
3918 EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
3919 EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
3920 EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
3921 EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
3922 EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
3923 EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
3924 EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
3925 EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
3926 EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
3927 EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
3928 EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
3929 EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
3930 EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
3931 EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
3932 EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
3933 EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
3934 EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
3935 EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
3936 EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
3937 EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
3938 EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
3939 EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
3940 EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
3941 EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
3942 EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
3943 EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
3944 EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
3945 /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
3946 /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
3947 })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
3948 /**
3949 * Used by the checker, this enum keeps track of external emit helpers that should be type
3950 * checked.
3951 */
3952 /* @internal */
3953 var ExternalEmitHelpers;
3954 (function (ExternalEmitHelpers) {
3955 ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
3956 ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
3957 ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
3958 ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
3959 ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
3960 ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
3961 ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
3962 ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
3963 ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
3964 ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
3965 ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
3966 ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await";
3967 ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator";
3968 ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator";
3969 ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues";
3970 ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar";
3971 ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject";
3972 ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
3973 ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper";
3974 // Helpers included by ES2015 for..of
3975 ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
3976 // Helpers included by ES2017 for..await..of
3977 ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes";
3978 // Helpers included by ES2017 async generators
3979 ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes";
3980 // Helpers included by yield* in ES2017 async generators
3981 ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes";
3982 // Helpers included by ES2015 spread
3983 ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
3984 })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
3985 var EmitHint;
3986 (function (EmitHint) {
3987 EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
3988 EmitHint[EmitHint["Expression"] = 1] = "Expression";
3989 EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
3990 EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
3991 EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
3992 EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
3993 })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
3994 /*@internal*/
3995 var BundleFileSectionKind;
3996 (function (BundleFileSectionKind) {
3997 BundleFileSectionKind["Prologue"] = "prologue";
3998 BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
3999 BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
4000 BundleFileSectionKind["Reference"] = "reference";
4001 BundleFileSectionKind["Type"] = "type";
4002 BundleFileSectionKind["Lib"] = "lib";
4003 BundleFileSectionKind["Prepend"] = "prepend";
4004 BundleFileSectionKind["Text"] = "text";
4005 BundleFileSectionKind["Internal"] = "internal";
4006 // comments?
4007 })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
4008 var ListFormat;
4009 (function (ListFormat) {
4010 ListFormat[ListFormat["None"] = 0] = "None";
4011 // Line separators
4012 ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
4013 ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
4014 ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
4015 ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
4016 // Delimiters
4017 ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
4018 ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
4019 ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
4020 ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
4021 ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
4022 ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
4023 ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
4024 // Whitespace
4025 ListFormat[ListFormat["Indented"] = 128] = "Indented";
4026 ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
4027 ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
4028 // Brackets/Braces
4029 ListFormat[ListFormat["Braces"] = 1024] = "Braces";
4030 ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
4031 ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
4032 ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
4033 ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
4034 ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
4035 ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
4036 ListFormat[ListFormat["Optional"] = 49152] = "Optional";
4037 // Other
4038 ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
4039 ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
4040 ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
4041 ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
4042 ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
4043 // Precomputed Formats
4044 ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
4045 ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
4046 ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
4047 ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
4048 ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements";
4049 ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
4050 ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
4051 ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
4052 ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
4053 ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
4054 ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
4055 ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
4056 ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
4057 ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
4058 ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
4059 ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
4060 ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
4061 ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
4062 ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
4063 ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
4064 ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
4065 ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
4066 ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
4067 ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
4068 ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
4069 ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
4070 ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
4071 ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
4072 ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
4073 ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
4074 ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
4075 ListFormat[ListFormat["Decorators"] = 49153] = "Decorators";
4076 ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
4077 ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
4078 ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
4079 ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
4080 ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
4081 })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
4082 /* @internal */
4083 var PragmaKindFlags;
4084 (function (PragmaKindFlags) {
4085 PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
4086 /**
4087 * Triple slash comment of the form
4088 * /// <pragma-name argname="value" />
4089 */
4090 PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
4091 /**
4092 * Single line comment of the form
4093 * // @pragma-name argval1 argval2
4094 * or
4095 * /// @pragma-name argval1 argval2
4096 */
4097 PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
4098 /**
4099 * Multiline non-jsdoc pragma of the form
4100 * /* @pragma-name argval1 argval2 * /
4101 */
4102 PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
4103 PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
4104 PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
4105 })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
4106 /**
4107 * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas`
4108 */
4109 /* @internal */
4110 function _contextuallyTypePragmas(args) {
4111 return args;
4112 }
4113 // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
4114 // fancy effectively defining it twice, once in value-space and once in type-space
4115 /* @internal */
4116 ts.commentPragmas = _contextuallyTypePragmas({
4117 "reference": {
4118 args: [
4119 { name: "types", optional: true, captureSpan: true },
4120 { name: "lib", optional: true, captureSpan: true },
4121 { name: "path", optional: true, captureSpan: true },
4122 { name: "no-default-lib", optional: true }
4123 ],
4124 kind: 1 /* TripleSlashXML */
4125 },
4126 "amd-dependency": {
4127 args: [{ name: "path" }, { name: "name", optional: true }],
4128 kind: 1 /* TripleSlashXML */
4129 },
4130 "amd-module": {
4131 args: [{ name: "name" }],
4132 kind: 1 /* TripleSlashXML */
4133 },
4134 "ts-check": {
4135 kind: 2 /* SingleLine */
4136 },
4137 "ts-nocheck": {
4138 kind: 2 /* SingleLine */
4139 },
4140 "jsx": {
4141 args: [{ name: "factory" }],
4142 kind: 4 /* MultiLine */
4143 },
4144 });
4145})(ts || (ts = {}));
4146var ts;
4147(function (ts) {
4148 /**
4149 * djb2 hashing algorithm
4150 * http://www.cse.yorku.ca/~oz/hash.html
4151 */
4152 /* @internal */
4153 function generateDjb2Hash(data) {
4154 var acc = 5381;
4155 for (var i = 0; i < data.length; i++) {
4156 acc = ((acc << 5) + acc) + data.charCodeAt(i);
4157 }
4158 return acc.toString();
4159 }
4160 ts.generateDjb2Hash = generateDjb2Hash;
4161 /**
4162 * Set a high stack trace limit to provide more information in case of an error.
4163 * Called for command-line and server use cases.
4164 * Not called if TypeScript is used as a library.
4165 */
4166 /* @internal */
4167 function setStackTraceLimit() {
4168 if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
4169 Error.stackTraceLimit = 100;
4170 }
4171 }
4172 ts.setStackTraceLimit = setStackTraceLimit;
4173 var FileWatcherEventKind;
4174 (function (FileWatcherEventKind) {
4175 FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
4176 FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
4177 FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
4178 })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
4179 /* @internal */
4180 var PollingInterval;
4181 (function (PollingInterval) {
4182 PollingInterval[PollingInterval["High"] = 2000] = "High";
4183 PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
4184 PollingInterval[PollingInterval["Low"] = 250] = "Low";
4185 })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
4186 /* @internal */
4187 ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
4188 function createPollingIntervalBasedLevels(levels) {
4189 var _a;
4190 return _a = {},
4191 _a[PollingInterval.Low] = levels.Low,
4192 _a[PollingInterval.Medium] = levels.Medium,
4193 _a[PollingInterval.High] = levels.High,
4194 _a;
4195 }
4196 var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
4197 var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
4198 /* @internal */
4199 ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
4200 /* @internal */
4201 function setCustomPollingValues(system) {
4202 if (!system.getEnvironmentVariable) {
4203 return;
4204 }
4205 var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
4206 pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
4207 ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
4208 function getLevel(envVar, level) {
4209 return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
4210 }
4211 function getCustomLevels(baseVariable) {
4212 var customLevels;
4213 setCustomLevel("Low");
4214 setCustomLevel("Medium");
4215 setCustomLevel("High");
4216 return customLevels;
4217 function setCustomLevel(level) {
4218 var customLevel = getLevel(baseVariable, level);
4219 if (customLevel) {
4220 (customLevels || (customLevels = {}))[level] = Number(customLevel);
4221 }
4222 }
4223 }
4224 function setCustomLevels(baseVariable, levels) {
4225 var customLevels = getCustomLevels(baseVariable);
4226 if (customLevels) {
4227 setLevel("Low");
4228 setLevel("Medium");
4229 setLevel("High");
4230 return true;
4231 }
4232 return false;
4233 function setLevel(level) {
4234 levels[level] = customLevels[level] || levels[level];
4235 }
4236 }
4237 function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
4238 var customLevels = getCustomLevels(baseVariable);
4239 return (pollingIntervalChanged || customLevels) &&
4240 createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels);
4241 }
4242 }
4243 ts.setCustomPollingValues = setCustomPollingValues;
4244 /* @internal */
4245 function createDynamicPriorityPollingWatchFile(host) {
4246 var watchedFiles = [];
4247 var changedFilesInLastPoll = [];
4248 var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
4249 var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
4250 var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
4251 return watchFile;
4252 function watchFile(fileName, callback, defaultPollingInterval) {
4253 var file = {
4254 fileName: fileName,
4255 callback: callback,
4256 unchangedPolls: 0,
4257 mtime: getModifiedTime(fileName)
4258 };
4259 watchedFiles.push(file);
4260 addToPollingIntervalQueue(file, defaultPollingInterval);
4261 return {
4262 close: function () {
4263 file.isClosed = true;
4264 // Remove from watchedFiles
4265 ts.unorderedRemoveItem(watchedFiles, file);
4266 // Do not update polling interval queue since that will happen as part of polling
4267 }
4268 };
4269 }
4270 function createPollingIntervalQueue(pollingInterval) {
4271 var queue = [];
4272 queue.pollingInterval = pollingInterval;
4273 queue.pollIndex = 0;
4274 queue.pollScheduled = false;
4275 return queue;
4276 }
4277 function pollPollingIntervalQueue(queue) {
4278 queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
4279 // Set the next polling index and timeout
4280 if (queue.length) {
4281 scheduleNextPoll(queue.pollingInterval);
4282 }
4283 else {
4284 ts.Debug.assert(queue.pollIndex === 0);
4285 queue.pollScheduled = false;
4286 }
4287 }
4288 function pollLowPollingIntervalQueue(queue) {
4289 // Always poll complete list of changedFilesInLastPoll
4290 pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
4291 // Finally do the actual polling of the queue
4292 pollPollingIntervalQueue(queue);
4293 // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
4294 // as pollPollingIntervalQueue wont schedule for next poll
4295 if (!queue.pollScheduled && changedFilesInLastPoll.length) {
4296 scheduleNextPoll(PollingInterval.Low);
4297 }
4298 }
4299 function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
4300 // Max visit would be all elements of the queue
4301 var needsVisit = queue.length;
4302 var definedValueCopyToIndex = pollIndex;
4303 for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
4304 var watchedFile = queue[pollIndex];
4305 if (!watchedFile) {
4306 continue;
4307 }
4308 else if (watchedFile.isClosed) {
4309 queue[pollIndex] = undefined;
4310 continue;
4311 }
4312 polled++;
4313 var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
4314 if (watchedFile.isClosed) {
4315 // Closed watcher as part of callback
4316 queue[pollIndex] = undefined;
4317 }
4318 else if (fileChanged) {
4319 watchedFile.unchangedPolls = 0;
4320 // Changed files go to changedFilesInLastPoll queue
4321 if (queue !== changedFilesInLastPoll) {
4322 queue[pollIndex] = undefined;
4323 addChangedFileToLowPollingIntervalQueue(watchedFile);
4324 }
4325 }
4326 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
4327 watchedFile.unchangedPolls++;
4328 }
4329 else if (queue === changedFilesInLastPoll) {
4330 // Restart unchangedPollCount for unchanged file and move to low polling interval queue
4331 watchedFile.unchangedPolls = 1;
4332 queue[pollIndex] = undefined;
4333 addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
4334 }
4335 else if (pollingInterval !== PollingInterval.High) {
4336 watchedFile.unchangedPolls++;
4337 queue[pollIndex] = undefined;
4338 addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
4339 }
4340 if (queue[pollIndex]) {
4341 // Copy this file to the non hole location
4342 if (definedValueCopyToIndex < pollIndex) {
4343 queue[definedValueCopyToIndex] = watchedFile;
4344 queue[pollIndex] = undefined;
4345 }
4346 definedValueCopyToIndex++;
4347 }
4348 }
4349 // Return next poll index
4350 return pollIndex;
4351 function nextPollIndex() {
4352 pollIndex++;
4353 if (pollIndex === queue.length) {
4354 if (definedValueCopyToIndex < pollIndex) {
4355 // There are holes from nextDefinedValueIndex to end of queue, change queue size
4356 queue.length = definedValueCopyToIndex;
4357 }
4358 pollIndex = 0;
4359 definedValueCopyToIndex = 0;
4360 }
4361 }
4362 }
4363 function pollingIntervalQueue(pollingInterval) {
4364 switch (pollingInterval) {
4365 case PollingInterval.Low:
4366 return lowPollingIntervalQueue;
4367 case PollingInterval.Medium:
4368 return mediumPollingIntervalQueue;
4369 case PollingInterval.High:
4370 return highPollingIntervalQueue;
4371 }
4372 }
4373 function addToPollingIntervalQueue(file, pollingInterval) {
4374 pollingIntervalQueue(pollingInterval).push(file);
4375 scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
4376 }
4377 function addChangedFileToLowPollingIntervalQueue(file) {
4378 changedFilesInLastPoll.push(file);
4379 scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
4380 }
4381 function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
4382 if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
4383 scheduleNextPoll(pollingInterval);
4384 }
4385 }
4386 function scheduleNextPoll(pollingInterval) {
4387 pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
4388 }
4389 function getModifiedTime(fileName) {
4390 return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
4391 }
4392 }
4393 ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
4394 /**
4395 * Returns true if file status changed
4396 */
4397 /*@internal*/
4398 function onWatchedFileStat(watchedFile, modifiedTime) {
4399 var oldTime = watchedFile.mtime.getTime();
4400 var newTime = modifiedTime.getTime();
4401 if (oldTime !== newTime) {
4402 watchedFile.mtime = modifiedTime;
4403 watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
4404 return true;
4405 }
4406 return false;
4407 }
4408 ts.onWatchedFileStat = onWatchedFileStat;
4409 /*@internal*/
4410 function getFileWatcherEventKind(oldTime, newTime) {
4411 return oldTime === 0
4412 ? FileWatcherEventKind.Created
4413 : newTime === 0
4414 ? FileWatcherEventKind.Deleted
4415 : FileWatcherEventKind.Changed;
4416 }
4417 ts.getFileWatcherEventKind = getFileWatcherEventKind;
4418 /*@internal*/
4419 ts.ignoredPaths = ["/node_modules/.", "/.git"];
4420 /**
4421 * Watch the directory recursively using host provided method to watch child directories
4422 * that means if this is recursive watcher, watch the children directories as well
4423 * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
4424 */
4425 /*@internal*/
4426 function createRecursiveDirectoryWatcher(host) {
4427 var cache = ts.createMap();
4428 var callbackCache = ts.createMultiMap();
4429 var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
4430 var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
4431 return createDirectoryWatcher;
4432 /**
4433 * Create the directory watcher for the dirPath.
4434 */
4435 function createDirectoryWatcher(dirName, callback) {
4436 var dirPath = toCanonicalFilePath(dirName);
4437 var directoryWatcher = cache.get(dirPath);
4438 if (directoryWatcher) {
4439 directoryWatcher.refCount++;
4440 }
4441 else {
4442 directoryWatcher = {
4443 watcher: host.watchDirectory(dirName, function (fileName) {
4444 if (isIgnoredPath(fileName))
4445 return;
4446 // Call the actual callback
4447 callbackCache.forEach(function (callbacks, rootDirName) {
4448 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
4449 callbacks.forEach(function (callback) { return callback(fileName); });
4450 }
4451 });
4452 // Iterate through existing children and update the watches if needed
4453 updateChildWatches(dirName, dirPath);
4454 }),
4455 refCount: 1,
4456 childWatches: ts.emptyArray
4457 };
4458 cache.set(dirPath, directoryWatcher);
4459 updateChildWatches(dirName, dirPath);
4460 }
4461 if (callback) {
4462 callbackCache.add(dirPath, callback);
4463 }
4464 return {
4465 dirName: dirName,
4466 close: function () {
4467 var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath));
4468 if (callback)
4469 callbackCache.remove(dirPath, callback);
4470 directoryWatcher.refCount--;
4471 if (directoryWatcher.refCount)
4472 return;
4473 cache.delete(dirPath);
4474 ts.closeFileWatcherOf(directoryWatcher);
4475 directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
4476 }
4477 };
4478 }
4479 function updateChildWatches(dirName, dirPath) {
4480 // Iterate through existing children and update the watches if needed
4481 var parentWatcher = cache.get(dirPath);
4482 if (parentWatcher) {
4483 parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches);
4484 }
4485 }
4486 /**
4487 * Watch the directories in the parentDir
4488 */
4489 function watchChildDirectories(parentDir, existingChildWatches) {
4490 var newChildWatches;
4491 ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
4492 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
4493 // Filter our the symbolic link directories since those arent included in recursive watch
4494 // which is same behaviour when recursive: true is passed to fs.watch
4495 return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
4496 }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
4497 return newChildWatches || ts.emptyArray;
4498 /**
4499 * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
4500 */
4501 function createAndAddChildDirectoryWatcher(childName) {
4502 var result = createDirectoryWatcher(childName);
4503 addChildDirectoryWatcher(result);
4504 }
4505 /**
4506 * Add child directory watcher to the new ChildDirectoryWatcher list
4507 */
4508 function addChildDirectoryWatcher(childWatcher) {
4509 (newChildWatches || (newChildWatches = [])).push(childWatcher);
4510 }
4511 }
4512 function isIgnoredPath(path) {
4513 return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
4514 }
4515 function isInPath(path, searchPath) {
4516 if (ts.stringContains(path, searchPath))
4517 return true;
4518 if (host.useCaseSensitiveFileNames)
4519 return false;
4520 return ts.stringContains(toCanonicalFilePath(path), searchPath);
4521 }
4522 }
4523 ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
4524 function getNodeMajorVersion() {
4525 if (typeof process === "undefined") {
4526 return undefined;
4527 }
4528 var version = process.version;
4529 if (!version) {
4530 return undefined;
4531 }
4532 var dot = version.indexOf(".");
4533 if (dot === -1) {
4534 return undefined;
4535 }
4536 return parseInt(version.substring(1, dot));
4537 }
4538 ts.getNodeMajorVersion = getNodeMajorVersion;
4539 // TODO: GH#18217 this is used as if it's certainly defined in many places.
4540 ts.sys = (function () {
4541 // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
4542 // byte order mark from the specified encoding. Using any other byte order mark does
4543 // not actually work.
4544 var byteOrderMarkIndicator = "\uFEFF";
4545 function getNodeSystem() {
4546 var _fs = require("fs");
4547 var _path = require("path");
4548 var _os = require("os");
4549 // crypto can be absent on reduced node installations
4550 var _crypto;
4551 try {
4552 _crypto = require("crypto");
4553 }
4554 catch (_a) {
4555 _crypto = undefined;
4556 }
4557 var Buffer = require("buffer").Buffer;
4558 var nodeVersion = getNodeMajorVersion();
4559 var isNode4OrLater = nodeVersion >= 4;
4560 var platform = _os.platform();
4561 var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
4562 var FileSystemEntryKind;
4563 (function (FileSystemEntryKind) {
4564 FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
4565 FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
4566 })(FileSystemEntryKind || (FileSystemEntryKind = {}));
4567 var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER;
4568 var tscWatchFile = process.env.TSC_WATCHFILE;
4569 var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY;
4570 var dynamicPollingWatchFile;
4571 var nodeSystem = {
4572 args: process.argv.slice(2),
4573 newLine: _os.EOL,
4574 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
4575 write: function (s) {
4576 process.stdout.write(s);
4577 },
4578 writeOutputIsTTY: function () {
4579 return process.stdout.isTTY;
4580 },
4581 readFile: readFile,
4582 writeFile: writeFile,
4583 watchFile: getWatchFile(),
4584 watchDirectory: getWatchDirectory(),
4585 resolvePath: function (path) { return _path.resolve(path); },
4586 fileExists: fileExists,
4587 directoryExists: directoryExists,
4588 createDirectory: function (directoryName) {
4589 if (!nodeSystem.directoryExists(directoryName)) {
4590 // Wrapped in a try-catch to prevent crashing if we are in a race
4591 // with another copy of ourselves to create the same directory
4592 try {
4593 _fs.mkdirSync(directoryName);
4594 }
4595 catch (e) {
4596 if (e.code !== "EEXIST") {
4597 // Failed for some other reason (access denied?); still throw
4598 throw e;
4599 }
4600 }
4601 }
4602 },
4603 getExecutingFilePath: function () {
4604 return __filename;
4605 },
4606 getCurrentDirectory: function () {
4607 return process.cwd();
4608 },
4609 getDirectories: getDirectories,
4610 getEnvironmentVariable: function (name) {
4611 return process.env[name] || "";
4612 },
4613 readDirectory: readDirectory,
4614 getModifiedTime: getModifiedTime,
4615 setModifiedTime: setModifiedTime,
4616 deleteFile: deleteFile,
4617 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
4618 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
4619 getMemoryUsage: function () {
4620 if (global.gc) {
4621 global.gc();
4622 }
4623 return process.memoryUsage().heapUsed;
4624 },
4625 getFileSize: function (path) {
4626 try {
4627 var stat = _fs.statSync(path);
4628 if (stat.isFile()) {
4629 return stat.size;
4630 }
4631 }
4632 catch ( /*ignore*/_a) { /*ignore*/ }
4633 return 0;
4634 },
4635 exit: function (exitCode) {
4636 process.exit(exitCode);
4637 },
4638 realpath: realpath,
4639 debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
4640 tryEnableSourceMapsForHost: function () {
4641 try {
4642 require("source-map-support").install();
4643 }
4644 catch (_a) {
4645 // Could not enable source maps.
4646 }
4647 },
4648 setTimeout: setTimeout,
4649 clearTimeout: clearTimeout,
4650 clearScreen: function () {
4651 process.stdout.write("\x1Bc");
4652 },
4653 setBlocking: function () {
4654 if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
4655 process.stdout._handle.setBlocking(true);
4656 }
4657 },
4658 bufferFrom: bufferFrom,
4659 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
4660 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
4661 };
4662 return nodeSystem;
4663 function bufferFrom(input, encoding) {
4664 // See https://github.com/Microsoft/TypeScript/issues/25652
4665 return Buffer.from && Buffer.from !== Int8Array.from
4666 ? Buffer.from(input, encoding)
4667 : new Buffer(input, encoding);
4668 }
4669 function isFileSystemCaseSensitive() {
4670 // win32\win64 are case insensitive platforms
4671 if (platform === "win32" || platform === "win64") {
4672 return false;
4673 }
4674 // If this file exists under a different case, we must be case-insensitve.
4675 return !fileExists(swapCase(__filename));
4676 }
4677 /** Convert all lowercase chars to uppercase, and vice-versa */
4678 function swapCase(s) {
4679 return s.replace(/\w/g, function (ch) {
4680 var up = ch.toUpperCase();
4681 return ch === up ? ch.toLowerCase() : up;
4682 });
4683 }
4684 function getWatchFile() {
4685 switch (tscWatchFile) {
4686 case "PriorityPollingInterval":
4687 // Use polling interval based on priority when create watch using host.watchFile
4688 return fsWatchFile;
4689 case "DynamicPriorityPolling":
4690 // Use polling interval but change the interval depending on file changes and their default polling interval
4691 return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout });
4692 case "UseFsEvents":
4693 // Use notifications from FS to watch with falling back to fs.watchFile
4694 return watchFileUsingFsWatch;
4695 case "UseFsEventsWithFallbackDynamicPolling":
4696 // Use notifications from FS to watch with falling back to dynamic watch file
4697 dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout });
4698 return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile);
4699 case "UseFsEventsOnParentDirectory":
4700 // Use notifications from FS to watch with falling back to fs.watchFile
4701 return createNonPollingWatchFile();
4702 }
4703 return useNonPollingWatchers ?
4704 createNonPollingWatchFile() :
4705 // Default to do not use polling interval as it is before this experiment branch
4706 function (fileName, callback) { return fsWatchFile(fileName, callback); };
4707 }
4708 function getWatchDirectory() {
4709 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
4710 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
4711 var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
4712 if (fsSupportsRecursive) {
4713 return watchDirectoryUsingFsWatch;
4714 }
4715 var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ?
4716 createWatchDirectoryUsing(fsWatchFile) :
4717 tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ?
4718 createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) :
4719 watchDirectoryUsingFsWatch;
4720 var watchDirectoryRecursively = createRecursiveDirectoryWatcher({
4721 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
4722 directoryExists: directoryExists,
4723 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
4724 watchDirectory: watchDirectory,
4725 realpath: realpath
4726 });
4727 return function (directoryName, callback, recursive) {
4728 if (recursive) {
4729 return watchDirectoryRecursively(directoryName, callback);
4730 }
4731 return watchDirectory(directoryName, callback);
4732 };
4733 }
4734 function createNonPollingWatchFile() {
4735 // One file can have multiple watchers
4736 var fileWatcherCallbacks = ts.createMultiMap();
4737 var dirWatchers = ts.createMap();
4738 var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
4739 return nonPollingWatchFile;
4740 function nonPollingWatchFile(fileName, callback) {
4741 var filePath = toCanonicalName(fileName);
4742 fileWatcherCallbacks.add(filePath, callback);
4743 var dirPath = ts.getDirectoryPath(filePath) || ".";
4744 var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath);
4745 watcher.referenceCount++;
4746 return {
4747 close: function () {
4748 if (watcher.referenceCount === 1) {
4749 watcher.close();
4750 dirWatchers.delete(dirPath);
4751 }
4752 else {
4753 watcher.referenceCount--;
4754 }
4755 fileWatcherCallbacks.remove(filePath, callback);
4756 }
4757 };
4758 }
4759 function createDirectoryWatcher(dirName, dirPath) {
4760 var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) {
4761 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
4762 if (!ts.isString(relativeFileName)) {
4763 return;
4764 }
4765 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
4766 // Some applications save a working file via rename operations
4767 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
4768 if (callbacks) {
4769 for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
4770 var fileCallback = callbacks_1[_i];
4771 fileCallback(fileName, FileWatcherEventKind.Changed);
4772 }
4773 }
4774 });
4775 watcher.referenceCount = 0;
4776 dirWatchers.set(dirPath, watcher);
4777 return watcher;
4778 }
4779 }
4780 function fsWatchFile(fileName, callback, pollingInterval) {
4781 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged);
4782 var eventKind;
4783 return {
4784 close: function () { return _fs.unwatchFile(fileName, fileChanged); }
4785 };
4786 function fileChanged(curr, prev) {
4787 // 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)
4788 // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
4789 var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
4790 if (+curr.mtime === 0) {
4791 if (isPreviouslyDeleted) {
4792 // Already deleted file, no need to callback again
4793 return;
4794 }
4795 eventKind = FileWatcherEventKind.Deleted;
4796 }
4797 else if (isPreviouslyDeleted) {
4798 eventKind = FileWatcherEventKind.Created;
4799 }
4800 // If there is no change in modified time, ignore the event
4801 else if (+curr.mtime === +prev.mtime) {
4802 return;
4803 }
4804 else {
4805 // File changed
4806 eventKind = FileWatcherEventKind.Changed;
4807 }
4808 callback(fileName, eventKind);
4809 }
4810 }
4811 function createFileWatcherCallback(callback) {
4812 return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
4813 }
4814 function createFsWatchCallbackForFileWatcherCallback(fileName, callback) {
4815 return function (eventName) {
4816 if (eventName === "rename") {
4817 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
4818 }
4819 else {
4820 // Change
4821 callback(fileName, FileWatcherEventKind.Changed);
4822 }
4823 };
4824 }
4825 function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
4826 return function (eventName, relativeFileName) {
4827 // In watchDirectory we only care about adding and removing files (when event name is
4828 // "rename"); changes made within files are handled by corresponding fileWatchers (when
4829 // event name is "change")
4830 if (eventName === "rename") {
4831 // When deleting a file, the passed baseFileName is null
4832 callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
4833 }
4834 };
4835 }
4836 function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) {
4837 var options;
4838 /** Watcher for the file system entry depending on whether it is missing or present */
4839 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
4840 watchMissingFileSystemEntry() :
4841 watchPresentFileSystemEntry();
4842 return {
4843 close: function () {
4844 // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
4845 watcher.close();
4846 watcher = undefined;
4847 }
4848 };
4849 /**
4850 * Invoke the callback with rename and update the watcher if not closed
4851 * @param createWatcher
4852 */
4853 function invokeCallbackAndUpdateWatcher(createWatcher) {
4854 // Call the callback for current directory
4855 callback("rename", "");
4856 // If watcher is not closed, update it
4857 if (watcher) {
4858 watcher.close();
4859 watcher = createWatcher();
4860 }
4861 }
4862 /**
4863 * Watch the file or directory that is currently present
4864 * and when the watched file or directory is deleted, switch to missing file system entry watcher
4865 */
4866 function watchPresentFileSystemEntry() {
4867 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
4868 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
4869 if (options === undefined) {
4870 if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) {
4871 options = { persistent: true, recursive: !!recursive };
4872 }
4873 else {
4874 options = { persistent: true };
4875 }
4876 }
4877 try {
4878 var presentWatcher = _fs.watch(fileOrDirectory, options, callback);
4879 // Watch the missing file or directory or error
4880 presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
4881 return presentWatcher;
4882 }
4883 catch (e) {
4884 // Catch the exception and use polling instead
4885 // 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
4886 // so instead of throwing error, use fs.watchFile
4887 return watchPresentFileSystemEntryWithFsWatchFile();
4888 }
4889 }
4890 /**
4891 * Watch the file or directory using fs.watchFile since fs.watch threw exception
4892 * 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
4893 */
4894 function watchPresentFileSystemEntryWithFsWatchFile() {
4895 return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval);
4896 }
4897 /**
4898 * Watch the file or directory that is missing
4899 * and switch to existing file or directory when the missing filesystem entry is created
4900 */
4901 function watchMissingFileSystemEntry() {
4902 return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) {
4903 if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
4904 // Call the callback for current file or directory
4905 // For now it could be callback for the inner directory creation,
4906 // but just return current directory, better than current no-op
4907 invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
4908 }
4909 }, pollingInterval);
4910 }
4911 }
4912 function watchFileUsingFsWatch(fileName, callback, pollingInterval) {
4913 return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval);
4914 }
4915 function createWatchFileUsingDynamicWatchFile(watchFile) {
4916 return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); };
4917 }
4918 function fsWatchDirectory(directoryName, callback, recursive) {
4919 return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile);
4920 }
4921 function watchDirectoryUsingFsWatch(directoryName, callback, recursive) {
4922 return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive);
4923 }
4924 function createWatchDirectoryUsing(fsWatchFile) {
4925 return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); };
4926 }
4927 function readFile(fileName, _encoding) {
4928 if (!fileExists(fileName)) {
4929 return undefined;
4930 }
4931 var buffer = _fs.readFileSync(fileName);
4932 var len = buffer.length;
4933 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
4934 // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
4935 // flip all byte pairs and treat as little endian.
4936 len &= ~1; // Round down to a multiple of 2
4937 for (var i = 0; i < len; i += 2) {
4938 var temp = buffer[i];
4939 buffer[i] = buffer[i + 1];
4940 buffer[i + 1] = temp;
4941 }
4942 return buffer.toString("utf16le", 2);
4943 }
4944 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
4945 // Little endian UTF-16 byte order mark detected
4946 return buffer.toString("utf16le", 2);
4947 }
4948 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
4949 // UTF-8 byte order mark detected
4950 return buffer.toString("utf8", 3);
4951 }
4952 // Default is UTF-8 with no byte order mark
4953 return buffer.toString("utf8");
4954 }
4955 function writeFile(fileName, data, writeByteOrderMark) {
4956 // If a BOM is required, emit one
4957 if (writeByteOrderMark) {
4958 data = byteOrderMarkIndicator + data;
4959 }
4960 var fd;
4961 try {
4962 fd = _fs.openSync(fileName, "w");
4963 _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
4964 }
4965 finally {
4966 if (fd !== undefined) {
4967 _fs.closeSync(fd);
4968 }
4969 }
4970 }
4971 function getAccessibleFileSystemEntries(path) {
4972 try {
4973 var entries = _fs.readdirSync(path || ".").sort();
4974 var files = [];
4975 var directories = [];
4976 for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {
4977 var entry = entries_2[_i];
4978 // This is necessary because on some file system node fails to exclude
4979 // "." and "..". See https://github.com/nodejs/node/issues/4002
4980 if (entry === "." || entry === "..") {
4981 continue;
4982 }
4983 var name = ts.combinePaths(path, entry);
4984 var stat = void 0;
4985 try {
4986 stat = _fs.statSync(name);
4987 }
4988 catch (e) {
4989 continue;
4990 }
4991 if (stat.isFile()) {
4992 files.push(entry);
4993 }
4994 else if (stat.isDirectory()) {
4995 directories.push(entry);
4996 }
4997 }
4998 return { files: files, directories: directories };
4999 }
5000 catch (e) {
5001 return ts.emptyFileSystemEntries;
5002 }
5003 }
5004 function readDirectory(path, extensions, excludes, includes, depth) {
5005 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
5006 }
5007 function fileSystemEntryExists(path, entryKind) {
5008 try {
5009 var stat = _fs.statSync(path);
5010 switch (entryKind) {
5011 case 0 /* File */: return stat.isFile();
5012 case 1 /* Directory */: return stat.isDirectory();
5013 default: return false;
5014 }
5015 }
5016 catch (e) {
5017 return false;
5018 }
5019 }
5020 function fileExists(path) {
5021 return fileSystemEntryExists(path, 0 /* File */);
5022 }
5023 function directoryExists(path) {
5024 return fileSystemEntryExists(path, 1 /* Directory */);
5025 }
5026 function getDirectories(path) {
5027 return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); });
5028 }
5029 function realpath(path) {
5030 try {
5031 return _fs.realpathSync(path);
5032 }
5033 catch (_a) {
5034 return path;
5035 }
5036 }
5037 function getModifiedTime(path) {
5038 try {
5039 return _fs.statSync(path).mtime;
5040 }
5041 catch (e) {
5042 return undefined;
5043 }
5044 }
5045 function setModifiedTime(path, time) {
5046 try {
5047 _fs.utimesSync(path, time, time);
5048 }
5049 catch (e) {
5050 return;
5051 }
5052 }
5053 function deleteFile(path) {
5054 try {
5055 return _fs.unlinkSync(path);
5056 }
5057 catch (e) {
5058 return;
5059 }
5060 }
5061 function createSHA256Hash(data) {
5062 var hash = _crypto.createHash("sha256");
5063 hash.update(data);
5064 return hash.digest("hex");
5065 }
5066 }
5067 function getChakraSystem() {
5068 var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
5069 return {
5070 newLine: ChakraHost.newLine || "\r\n",
5071 args: ChakraHost.args,
5072 useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames,
5073 write: ChakraHost.echo,
5074 readFile: function (path, _encoding) {
5075 // encoding is automatically handled by the implementation in ChakraHost
5076 return ChakraHost.readFile(path);
5077 },
5078 writeFile: function (path, data, writeByteOrderMark) {
5079 // If a BOM is required, emit one
5080 if (writeByteOrderMark) {
5081 data = byteOrderMarkIndicator + data;
5082 }
5083 ChakraHost.writeFile(path, data);
5084 },
5085 resolvePath: ChakraHost.resolvePath,
5086 fileExists: ChakraHost.fileExists,
5087 deleteFile: ChakraHost.deleteFile,
5088 getModifiedTime: ChakraHost.getModifiedTime,
5089 setModifiedTime: ChakraHost.setModifiedTime,
5090 directoryExists: ChakraHost.directoryExists,
5091 createDirectory: ChakraHost.createDirectory,
5092 getExecutingFilePath: function () { return ChakraHost.executingFile; },
5093 getCurrentDirectory: function () { return ChakraHost.currentDirectory; },
5094 getDirectories: ChakraHost.getDirectories,
5095 getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }),
5096 readDirectory: function (path, extensions, excludes, includes, _depth) {
5097 var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory);
5098 return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern);
5099 },
5100 exit: ChakraHost.quit,
5101 realpath: realpath
5102 };
5103 }
5104 function recursiveCreateDirectory(directoryPath, sys) {
5105 var basePath = ts.getDirectoryPath(directoryPath);
5106 var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath);
5107 if (shouldCreateParent) {
5108 recursiveCreateDirectory(basePath, sys);
5109 }
5110 if (shouldCreateParent || !sys.directoryExists(directoryPath)) {
5111 sys.createDirectory(directoryPath);
5112 }
5113 }
5114 var sys;
5115 if (typeof ChakraHost !== "undefined") {
5116 sys = getChakraSystem();
5117 }
5118 else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
5119 // process and process.nextTick checks if current environment is node-like
5120 // process.browser check excludes webpack and browserify
5121 sys = getNodeSystem();
5122 }
5123 if (sys) {
5124 // patch writefile to create folder before writing the file
5125 var originalWriteFile_1 = sys.writeFile;
5126 sys.writeFile = function (path, data, writeBom) {
5127 var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path));
5128 if (directoryPath && !sys.directoryExists(directoryPath)) {
5129 recursiveCreateDirectory(directoryPath, sys);
5130 }
5131 originalWriteFile_1.call(sys, path, data, writeBom);
5132 };
5133 }
5134 return sys;
5135 })();
5136 if (ts.sys && ts.sys.getEnvironmentVariable) {
5137 setCustomPollingValues(ts.sys);
5138 ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
5139 ? 1 /* Normal */
5140 : 0 /* None */;
5141 }
5142 if (ts.sys && ts.sys.debugMode) {
5143 ts.Debug.isDebugging = true;
5144 }
5145})(ts || (ts = {}));
5146// <auto-generated />
5147// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
5148/* @internal */
5149var ts;
5150(function (ts) {
5151 function diag(code, category, key, message, reportsUnnecessary) {
5152 return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary };
5153 }
5154 // tslint:disable-next-line variable-name
5155 ts.Diagnostics = {
5156 Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
5157 Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
5158 _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
5159 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."),
5160 Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
5161 Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
5162 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."),
5163 Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
5164 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."),
5165 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."),
5166 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."),
5167 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."),
5168 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."),
5169 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."),
5170 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."),
5171 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."),
5172 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."),
5173 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."),
5174 An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."),
5175 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."),
5176 Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
5177 _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
5178 _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
5179 _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."),
5180 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."),
5181 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."),
5182 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."),
5183 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."),
5184 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."),
5185 _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."),
5186 _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."),
5187 _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
5188 _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."),
5189 _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."),
5190 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."),
5191 A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."),
5192 A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
5193 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."),
5194 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."),
5195 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."),
5196 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."),
5197 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."),
5198 A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
5199 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."),
5200 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."),
5201 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."),
5202 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."),
5203 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."),
5204 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."),
5205 Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
5206 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."),
5207 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."),
5208 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<T> type."),
5209 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."),
5210 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."),
5211 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."),
5212 _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."),
5213 _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."),
5214 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."),
5215 Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
5216 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}'."),
5217 An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."),
5218 _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."),
5219 _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."),
5220 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."),
5221 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."),
5222 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."),
5223 An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
5224 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."),
5225 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."),
5226 _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
5227 Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
5228 Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
5229 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."),
5230 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."),
5231 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."),
5232 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."),
5233 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."),
5234 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."),
5235 Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
5236 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."),
5237 Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
5238 Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
5239 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."),
5240 Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
5241 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."),
5242 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."),
5243 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."),
5244 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."),
5245 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."),
5246 An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
5247 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."),
5248 Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
5249 Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
5250 Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
5251 Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
5252 Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
5253 Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
5254 Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
5255 case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
5256 Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
5257 Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
5258 Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
5259 Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
5260 Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
5261 Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
5262 Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
5263 Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
5264 Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
5265 String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
5266 Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
5267 or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
5268 Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
5269 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."),
5270 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'."),
5271 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."),
5272 new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead."),
5273 const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
5274 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."),
5275 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."),
5276 Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
5277 Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
5278 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."),
5279 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."),
5280 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."),
5281 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."),
5282 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."),
5283 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."),
5284 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."),
5285 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."),
5286 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."),
5287 extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
5288 extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
5289 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."),
5290 implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
5291 Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
5292 Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
5293 Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
5294 Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
5295 Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
5296 Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
5297 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."),
5298 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."),
5299 Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
5300 Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
5301 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."),
5302 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."),
5303 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."),
5304 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."),
5305 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."),
5306 An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
5307 Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
5308 An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
5309 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."),
5310 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."),
5311 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."),
5312 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."),
5313 Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
5314 Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
5315 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."),
5316 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."),
5317 Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."),
5318 Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
5319 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."),
5320 Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."),
5321 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."),
5322 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."),
5323 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."),
5324 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."),
5325 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."),
5326 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."),
5327 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."),
5328 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'."),
5329 Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_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 to remove this warning."),
5330 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."),
5331 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."),
5332 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."),
5333 _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
5334 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."),
5335 Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
5336 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}'."),
5337 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}'."),
5338 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."),
5339 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."),
5340 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."),
5341 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."),
5342 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."),
5343 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."),
5344 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."),
5345 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."),
5346 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'."),
5347 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'."),
5348 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."),
5349 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."),
5350 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."),
5351 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."),
5352 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."),
5353 _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."),
5354 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."),
5355 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."),
5356 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."),
5357 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."),
5358 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."),
5359 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."),
5360 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'."),
5361 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."),
5362 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."),
5363 _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."),
5364 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."),
5365 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."),
5366 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."),
5367 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."),
5368 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."),
5369 await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."),
5370 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."),
5371 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."),
5372 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."),
5373 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."),
5374 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."),
5375 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."),
5376 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."),
5377 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."),
5378 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."),
5379 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."),
5380 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."),
5381 Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."),
5382 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."),
5383 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."),
5384 Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
5385 String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
5386 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."),
5387 _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}()'?"),
5388 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'."),
5389 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'."),
5390 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'."),
5391 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."),
5392 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."),
5393 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."),
5394 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."),
5395 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."),
5396 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."),
5397 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."),
5398 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}')'?"),
5399 Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
5400 The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."),
5401 A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
5402 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"),
5403 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."),
5404 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."),
5405 Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
5406 use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
5407 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."),
5408 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."),
5409 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."),
5410 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."),
5411 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."),
5412 A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal_1355", "A 'const' assertion can only be applied to a string, number, boolean, array, or object literal."),
5413 Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
5414 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."),
5415 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."),
5416 Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
5417 Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
5418 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}'."),
5419 File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
5420 Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."),
5421 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."),
5422 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."),
5423 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."),
5424 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."),
5425 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."),
5426 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."),
5427 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)."),
5428 Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
5429 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."),
5430 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)."),
5431 Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
5432 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."),
5433 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}'."),
5434 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}'."),
5435 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}'."),
5436 Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
5437 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}'."),
5438 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}'."),
5439 Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
5440 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}'."),
5441 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."),
5442 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}'."),
5443 Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
5444 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."),
5445 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."),
5446 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."),
5447 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."),
5448 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."),
5449 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."),
5450 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."),
5451 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."),
5452 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}'."),
5453 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."),
5454 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}'."),
5455 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'."),
5456 This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."),
5457 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}'."),
5458 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}'."),
5459 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."),
5460 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."),
5461 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'?"),
5462 Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."),
5463 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."),
5464 Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."),
5465 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."),
5466 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}'."),
5467 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."),
5468 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."),
5469 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."),
5470 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."),
5471 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."),
5472 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."),
5473 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'."),
5474 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."),
5475 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."),
5476 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."),
5477 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."),
5478 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}'."),
5479 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'."),
5480 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."),
5481 Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
5482 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."),
5483 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."),
5484 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."),
5485 Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."),
5486 Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."),
5487 Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
5488 Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
5489 A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: 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 or has parameter properties."),
5490 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."),
5491 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."),
5492 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."),
5493 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."),
5494 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."),
5495 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."),
5496 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."),
5497 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."),
5498 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."),
5499 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."),
5500 Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
5501 Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
5502 Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
5503 Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
5504 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."),
5505 Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
5506 Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
5507 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."),
5508 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."),
5509 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."),
5510 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}'."),
5511 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."),
5512 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."),
5513 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."),
5514 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."),
5515 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}'."),
5516 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."),
5517 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'."),
5518 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."),
5519 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}'."),
5520 Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
5521 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."),
5522 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'."),
5523 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}'."),
5524 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}'."),
5525 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}'."),
5526 Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
5527 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}'."),
5528 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}'."),
5529 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}'."),
5530 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}'."),
5531 Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
5532 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."),
5533 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."),
5534 Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."),
5535 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."),
5536 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."),
5537 Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
5538 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."),
5539 Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
5540 Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
5541 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."),
5542 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."),
5543 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."),
5544 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."),
5545 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."),
5546 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."),
5547 Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
5548 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."),
5549 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}'."),
5550 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."),
5551 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}'."),
5552 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}'."),
5553 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}'."),
5554 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."),
5555 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}'."),
5556 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."),
5557 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."),
5558 Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
5559 Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
5560 Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
5561 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."),
5562 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."),
5563 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."),
5564 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}'."),
5565 Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
5566 Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
5567 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."),
5568 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."),
5569 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."),
5570 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."),
5571 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'."),
5572 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."),
5573 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."),
5574 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."),
5575 Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
5576 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'."),
5577 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."),
5578 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'."),
5579 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."),
5580 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."),
5581 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."),
5582 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."),
5583 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."),
5584 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."),
5585 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'."),
5586 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}'."),
5587 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."),
5588 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}'."),
5589 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."),
5590 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}'."),
5591 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."),
5592 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."),
5593 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."),
5594 The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."),
5595 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."),
5596 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."),
5597 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}'."),
5598 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."),
5599 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."),
5600 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."),
5601 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."),
5602 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 *'."),
5603 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."),
5604 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."),
5605 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."),
5606 _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."),
5607 Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
5608 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."),
5609 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."),
5610 _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."),
5611 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."),
5612 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."),
5613 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."),
5614 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."),
5615 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."),
5616 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."),
5617 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."),
5618 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."),
5619 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}'."),
5620 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."),
5621 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."),
5622 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."),
5623 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."),
5624 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."),
5625 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."),
5626 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."),
5627 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."),
5628 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."),
5629 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."),
5630 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."),
5631 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."),
5632 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."),
5633 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."),
5634 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."),
5635 Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
5636 Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
5637 Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
5638 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."),
5639 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."),
5640 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}'."),
5641 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}'."),
5642 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."),
5643 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."),
5644 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."),
5645 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."),
5646 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."),
5647 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."),
5648 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."),
5649 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[]'."),
5650 Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."),
5651 The_type_returned_by_the_next_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_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."),
5652 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."),
5653 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."),
5654 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}'?"),
5655 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}'?"),
5656 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."),
5657 Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
5658 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}."),
5659 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."),
5660 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."),
5661 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}."),
5662 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}'."),
5663 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?"),
5664 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}'?"),
5665 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."),
5666 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."),
5667 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."),
5668 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."),
5669 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."),
5670 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."),
5671 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."),
5672 Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"),
5673 Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
5674 Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
5675 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."),
5676 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."),
5677 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."),
5678 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}'"),
5679 Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
5680 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`."),
5681 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`."),
5682 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`."),
5683 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."),
5684 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'."),
5685 _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."),
5686 Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
5687 JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
5688 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."),
5689 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."),
5690 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."),
5691 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."),
5692 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."),
5693 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."),
5694 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."),
5695 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."),
5696 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."),
5697 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}'."),
5698 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."),
5699 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."),
5700 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."),
5701 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."),
5702 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."),
5703 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."),
5704 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."),
5705 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."),
5706 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."),
5707 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}'."),
5708 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."),
5709 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."),
5710 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."),
5711 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}'."),
5712 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."),
5713 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."),
5714 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."),
5715 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}'?"),
5716 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}'?"),
5717 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."),
5718 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."),
5719 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."),
5720 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."),
5721 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."),
5722 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."),
5723 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."),
5724 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."),
5725 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."),
5726 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."),
5727 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."),
5728 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."),
5729 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."),
5730 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."),
5731 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}'."),
5732 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'."),
5733 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."),
5734 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."),
5735 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."),
5736 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."),
5737 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}'."),
5738 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."),
5739 _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."),
5740 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."),
5741 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}'."),
5742 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'?"),
5743 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."),
5744 _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."),
5745 _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."),
5746 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}'."),
5747 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),
5748 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?"),
5749 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."),
5750 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."),
5751 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}'."),
5752 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."),
5753 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."),
5754 _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."),
5755 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."),
5756 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."),
5757 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."),
5758 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."),
5759 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."),
5760 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."),
5761 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."),
5762 _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."),
5763 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."),
5764 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."),
5765 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}\"]'?"),
5766 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."),
5767 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."),
5768 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."),
5769 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}'."),
5770 Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
5771 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."),
5772 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?"),
5773 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'."),
5774 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'."),
5775 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'."),
5776 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}'?"),
5777 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}."),
5778 Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
5779 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}'?"),
5780 _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
5781 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."),
5782 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."),
5783 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(...)'."),
5784 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"),
5785 Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
5786 It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."),
5787 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}'?"),
5788 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}'."),
5789 BigInt_literals_are_not_available_when_targeting_lower_than_ESNext: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737", "BigInt literals are not available when targeting lower than ESNext."),
5790 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."),
5791 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}"),
5792 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."),
5793 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}'."),
5794 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."),
5795 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."),
5796 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."),
5797 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."),
5798 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."),
5799 _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}'."),
5800 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."),
5801 _0_refers_to_a_value_but_is_being_used_as_a_type_here: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_2749", "'{0}' refers to a value, but is being used as a type here."),
5802 The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
5803 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."),
5804 The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
5805 Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
5806 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}'."),
5807 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}'."),
5808 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}'."),
5809 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}'."),
5810 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}'."),
5811 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}'."),
5812 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}'."),
5813 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}'."),
5814 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}'."),
5815 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}'."),
5816 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}'."),
5817 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}'."),
5818 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."),
5819 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}'."),
5820 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}'."),
5821 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."),
5822 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}'."),
5823 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}'."),
5824 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."),
5825 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}'."),
5826 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}'."),
5827 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}'."),
5828 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}'."),
5829 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}'."),
5830 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}'."),
5831 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}'."),
5832 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}'."),
5833 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."),
5834 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}'."),
5835 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}'."),
5836 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."),
5837 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}'."),
5838 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}'."),
5839 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}'."),
5840 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}'."),
5841 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}'."),
5842 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}'."),
5843 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}'."),
5844 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}'."),
5845 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."),
5846 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}'."),
5847 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}'."),
5848 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."),
5849 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}'."),
5850 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}'."),
5851 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}'."),
5852 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}'."),
5853 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."),
5854 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}'."),
5855 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}'."),
5856 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."),
5857 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}'."),
5858 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}'."),
5859 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}'."),
5860 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}'."),
5861 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}'."),
5862 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}'."),
5863 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."),
5864 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}'."),
5865 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}'."),
5866 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."),
5867 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}'."),
5868 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}'."),
5869 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}'."),
5870 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}'."),
5871 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."),
5872 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}'."),
5873 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}'."),
5874 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}'."),
5875 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}'."),
5876 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}'."),
5877 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."),
5878 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}'."),
5879 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}'."),
5880 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."),
5881 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."),
5882 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}'."),
5883 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}'."),
5884 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."),
5885 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}'."),
5886 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}'."),
5887 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}'."),
5888 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}'."),
5889 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}'."),
5890 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."),
5891 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."),
5892 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}'."),
5893 Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
5894 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}."),
5895 Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
5896 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}."),
5897 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}."),
5898 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."),
5899 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."),
5900 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."),
5901 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}'."),
5902 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}'."),
5903 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}'."),
5904 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."),
5905 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."),
5906 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}'."),
5907 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}'."),
5908 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."),
5909 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."),
5910 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."),
5911 Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."),
5912 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."),
5913 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}'."),
5914 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}'."),
5915 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."),
5916 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."),
5917 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."),
5918 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}'."),
5919 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."),
5920 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'."),
5921 Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
5922 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}."),
5923 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."),
5924 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."),
5925 Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
5926 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."),
5927 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."),
5928 Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
5929 Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
5930 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."),
5931 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."),
5932 Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
5933 Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
5934 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."),
5935 Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
5936 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."),
5937 Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
5938 Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'."),
5939 Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."),
5940 Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
5941 Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
5942 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'."),
5943 Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
5944 options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
5945 file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
5946 Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
5947 Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
5948 Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
5949 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."),
5950 Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
5951 File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
5952 KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
5953 FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
5954 VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
5955 LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
5956 DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
5957 STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
5958 FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
5959 Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
5960 Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
5961 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}'."),
5962 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}."),
5963 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 <language> or <language>-<territory>. For example '{0}' or '{1}'."),
5964 Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
5965 Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
5966 Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
5967 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."),
5968 File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
5969 File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."),
5970 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."),
5971 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."),
5972 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."),
5973 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."),
5974 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)."),
5975 NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
5976 Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."),
5977 Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
5978 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."),
5979 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."),
5980 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)."),
5981 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."),
5982 Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
5983 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."),
5984 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)."),
5985 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."),
5986 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."),
5987 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."),
5988 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."),
5989 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."),
5990 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."),
5991 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'."),
5992 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."),
5993 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}."),
5994 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."),
5995 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"),
5996 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."),
5997 Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
5998 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}'."),
5999 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}'."),
6000 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}'. ========"),
6001 Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
6002 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}'."),
6003 Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
6004 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}'."),
6005 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}'."),
6006 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}'."),
6007 File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
6008 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."),
6009 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}'."),
6010 Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
6011 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."),
6012 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}'."),
6013 Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
6014 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."),
6015 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}'."),
6016 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}'."),
6017 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}'."),
6018 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}'."),
6019 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}'."),
6020 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}'."),
6021 Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
6022 Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
6023 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."),
6024 Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
6025 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'?"),
6026 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."),
6027 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}'. ========"),
6028 Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
6029 Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
6030 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}. ========"),
6031 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. ========"),
6032 Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
6033 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."),
6034 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. ========"),
6035 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."),
6036 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}'."),
6037 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."),
6038 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}'. ========"),
6039 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. ========"),
6040 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}'."),
6041 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'."),
6042 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."),
6043 _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),
6044 Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
6045 Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
6046 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."),
6047 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}'."),
6048 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),
6049 Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
6050 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}'."),
6051 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."),
6052 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."),
6053 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}'."),
6054 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."),
6055 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'."),
6056 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}'."),
6057 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."),
6058 Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
6059 Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
6060 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."),
6061 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."),
6062 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')."),
6063 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."),
6064 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."),
6065 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')"),
6066 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."),
6067 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)."),
6068 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."),
6069 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."),
6070 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."),
6071 Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
6072 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."),
6073 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."),
6074 Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
6075 Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
6076 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'."),
6077 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."),
6078 Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
6079 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"),
6080 Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
6081 Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
6082 Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
6083 Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
6084 Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
6085 Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
6086 Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
6087 Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
6088 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'."),
6089 Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
6090 List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
6091 Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
6092 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."),
6093 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."),
6094 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."),
6095 Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
6096 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."),
6097 Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
6098 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."),
6099 Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."),
6100 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."),
6101 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),
6102 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."),
6103 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."),
6104 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)."),
6105 _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),
6106 Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
6107 All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
6108 All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
6109 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}"),
6110 Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
6111 _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
6112 and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
6113 All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
6114 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."),
6115 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}'."),
6116 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}'."),
6117 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."),
6118 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."),
6119 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."),
6120 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?"),
6121 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?"),
6122 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."),
6123 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}'."),
6124 Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
6125 Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
6126 Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
6127 Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
6128 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}"),
6129 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."),
6130 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}'."),
6131 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."),
6132 File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."),
6133 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"),
6134 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"),
6135 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}'"),
6136 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}'"),
6137 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"),
6138 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"),
6139 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"),
6140 Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
6141 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}"),
6142 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}'"),
6143 Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
6144 Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
6145 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"),
6146 Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
6147 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"),
6148 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"),
6149 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"),
6150 Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
6151 Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
6152 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')"),
6153 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"),
6154 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."),
6155 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."),
6156 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}'..."),
6157 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"),
6158 Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
6159 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}'"),
6160 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}'"),
6161 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}'"),
6162 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}'"),
6163 Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
6164 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."),
6165 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"),
6166 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}'"),
6167 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}'"),
6168 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."),
6169 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."),
6170 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."),
6171 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."),
6172 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."),
6173 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."),
6174 _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."),
6175 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."),
6176 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."),
6177 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."),
6178 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'."),
6179 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."),
6180 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."),
6181 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."),
6182 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."),
6183 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."),
6184 _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."),
6185 _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."),
6186 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."),
6187 Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."),
6188 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."),
6189 Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
6190 Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
6191 Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
6192 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."),
6193 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."),
6194 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."),
6195 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."),
6196 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."),
6197 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}';`"),
6198 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}'."),
6199 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'."),
6200 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."),
6201 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."),
6202 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}`"),
6203 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'."),
6204 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."),
6205 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."),
6206 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."),
6207 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."),
6208 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."),
6209 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."),
6210 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."),
6211 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."),
6212 _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."),
6213 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}'?"),
6214 You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
6215 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."),
6216 import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."),
6217 export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."),
6218 type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."),
6219 implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."),
6220 interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."),
6221 module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."),
6222 type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."),
6223 _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."),
6224 types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."),
6225 type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."),
6226 parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."),
6227 non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."),
6228 enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."),
6229 type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."),
6230 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}'."),
6231 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}'."),
6232 Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
6233 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."),
6234 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."),
6235 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."),
6236 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."),
6237 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."),
6238 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."),
6239 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."),
6240 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."),
6241 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."),
6242 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."),
6243 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."),
6244 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."),
6245 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}'."),
6246 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."),
6247 class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
6248 Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
6249 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'."),
6250 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."),
6251 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}'."),
6252 JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
6253 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."),
6254 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'."),
6255 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."),
6256 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."),
6257 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."),
6258 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."),
6259 Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
6260 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."),
6261 _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}'?"),
6262 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."),
6263 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."),
6264 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."),
6265 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"),
6266 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"),
6267 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}"),
6268 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."),
6269 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."),
6270 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}'."),
6271 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."),
6272 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."),
6273 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."),
6274 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."),
6275 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."),
6276 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."),
6277 Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
6278 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"),
6279 Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
6280 Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"),
6281 Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
6282 Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
6283 Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
6284 Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
6285 Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
6286 Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
6287 Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
6288 Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
6289 Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
6290 Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
6291 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}\""),
6292 Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
6293 Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
6294 Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
6295 Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
6296 Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
6297 Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
6298 Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
6299 Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
6300 Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
6301 Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
6302 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}'"),
6303 Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
6304 Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
6305 Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
6306 Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
6307 Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
6308 Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
6309 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}\""),
6310 Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
6311 Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
6312 Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
6313 Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
6314 Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
6315 Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
6316 Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
6317 Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
6318 Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
6319 Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
6320 Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
6321 Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
6322 Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
6323 Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
6324 Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
6325 Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
6326 Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
6327 Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
6328 Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
6329 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}'"),
6330 Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
6331 Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
6332 Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
6333 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"),
6334 Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
6335 Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
6336 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"),
6337 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"),
6338 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"),
6339 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)"),
6340 Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
6341 Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
6342 Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
6343 Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
6344 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"),
6345 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"),
6346 Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
6347 Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
6348 Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
6349 Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
6350 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"),
6351 Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
6352 Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
6353 Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
6354 Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
6355 Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
6356 Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
6357 Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
6358 Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
6359 Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
6360 Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
6361 Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
6362 Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
6363 Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
6364 Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
6365 Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
6366 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"),
6367 Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
6368 Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
6369 Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
6370 Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
6371 Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
6372 Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
6373 Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
6374 Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
6375 Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"),
6376 Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"),
6377 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"),
6378 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"),
6379 Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
6380 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"),
6381 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"),
6382 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"),
6383 Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
6384 };
6385})(ts || (ts = {}));
6386var ts;
6387(function (ts) {
6388 var _a;
6389 /* @internal */
6390 function tokenIsIdentifierOrKeyword(token) {
6391 return token >= 72 /* Identifier */;
6392 }
6393 ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
6394 /* @internal */
6395 function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
6396 return token === 30 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
6397 }
6398 ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
6399 var textToKeywordObj = (_a = {
6400 abstract: 118 /* AbstractKeyword */,
6401 any: 120 /* AnyKeyword */,
6402 as: 119 /* AsKeyword */,
6403 bigint: 146 /* BigIntKeyword */,
6404 boolean: 123 /* BooleanKeyword */,
6405 break: 73 /* BreakKeyword */,
6406 case: 74 /* CaseKeyword */,
6407 catch: 75 /* CatchKeyword */,
6408 class: 76 /* ClassKeyword */,
6409 continue: 78 /* ContinueKeyword */,
6410 const: 77 /* ConstKeyword */
6411 },
6412 _a["" + "constructor"] = 124 /* ConstructorKeyword */,
6413 _a.debugger = 79 /* DebuggerKeyword */,
6414 _a.declare = 125 /* DeclareKeyword */,
6415 _a.default = 80 /* DefaultKeyword */,
6416 _a.delete = 81 /* DeleteKeyword */,
6417 _a.do = 82 /* DoKeyword */,
6418 _a.else = 83 /* ElseKeyword */,
6419 _a.enum = 84 /* EnumKeyword */,
6420 _a.export = 85 /* ExportKeyword */,
6421 _a.extends = 86 /* ExtendsKeyword */,
6422 _a.false = 87 /* FalseKeyword */,
6423 _a.finally = 88 /* FinallyKeyword */,
6424 _a.for = 89 /* ForKeyword */,
6425 _a.from = 144 /* FromKeyword */,
6426 _a.function = 90 /* FunctionKeyword */,
6427 _a.get = 126 /* GetKeyword */,
6428 _a.if = 91 /* IfKeyword */,
6429 _a.implements = 109 /* ImplementsKeyword */,
6430 _a.import = 92 /* ImportKeyword */,
6431 _a.in = 93 /* InKeyword */,
6432 _a.infer = 127 /* InferKeyword */,
6433 _a.instanceof = 94 /* InstanceOfKeyword */,
6434 _a.interface = 110 /* InterfaceKeyword */,
6435 _a.is = 128 /* IsKeyword */,
6436 _a.keyof = 129 /* KeyOfKeyword */,
6437 _a.let = 111 /* LetKeyword */,
6438 _a.module = 130 /* ModuleKeyword */,
6439 _a.namespace = 131 /* NamespaceKeyword */,
6440 _a.never = 132 /* NeverKeyword */,
6441 _a.new = 95 /* NewKeyword */,
6442 _a.null = 96 /* NullKeyword */,
6443 _a.number = 135 /* NumberKeyword */,
6444 _a.object = 136 /* ObjectKeyword */,
6445 _a.package = 112 /* PackageKeyword */,
6446 _a.private = 113 /* PrivateKeyword */,
6447 _a.protected = 114 /* ProtectedKeyword */,
6448 _a.public = 115 /* PublicKeyword */,
6449 _a.readonly = 133 /* ReadonlyKeyword */,
6450 _a.require = 134 /* RequireKeyword */,
6451 _a.global = 145 /* GlobalKeyword */,
6452 _a.return = 97 /* ReturnKeyword */,
6453 _a.set = 137 /* SetKeyword */,
6454 _a.static = 116 /* StaticKeyword */,
6455 _a.string = 138 /* StringKeyword */,
6456 _a.super = 98 /* SuperKeyword */,
6457 _a.switch = 99 /* SwitchKeyword */,
6458 _a.symbol = 139 /* SymbolKeyword */,
6459 _a.this = 100 /* ThisKeyword */,
6460 _a.throw = 101 /* ThrowKeyword */,
6461 _a.true = 102 /* TrueKeyword */,
6462 _a.try = 103 /* TryKeyword */,
6463 _a.type = 140 /* TypeKeyword */,
6464 _a.typeof = 104 /* TypeOfKeyword */,
6465 _a.undefined = 141 /* UndefinedKeyword */,
6466 _a.unique = 142 /* UniqueKeyword */,
6467 _a.unknown = 143 /* UnknownKeyword */,
6468 _a.var = 105 /* VarKeyword */,
6469 _a.void = 106 /* VoidKeyword */,
6470 _a.while = 107 /* WhileKeyword */,
6471 _a.with = 108 /* WithKeyword */,
6472 _a.yield = 117 /* YieldKeyword */,
6473 _a.async = 121 /* AsyncKeyword */,
6474 _a.await = 122 /* AwaitKeyword */,
6475 _a.of = 147 /* OfKeyword */,
6476 _a);
6477 var textToKeyword = ts.createMapFromTemplate(textToKeywordObj);
6478 var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 28 /* LessThanToken */, ">": 30 /* GreaterThanToken */, "<=": 31 /* LessThanEqualsToken */, ">=": 32 /* GreaterThanEqualsToken */, "==": 33 /* EqualsEqualsToken */, "!=": 34 /* ExclamationEqualsToken */, "===": 35 /* EqualsEqualsEqualsToken */, "!==": 36 /* ExclamationEqualsEqualsToken */, "=>": 37 /* EqualsGreaterThanToken */, "+": 38 /* PlusToken */, "-": 39 /* MinusToken */, "**": 41 /* AsteriskAsteriskToken */, "*": 40 /* AsteriskToken */, "/": 42 /* SlashToken */, "%": 43 /* PercentToken */, "++": 44 /* PlusPlusToken */, "--": 45 /* MinusMinusToken */, "<<": 46 /* LessThanLessThanToken */, "</": 29 /* LessThanSlashToken */, ">>": 47 /* GreaterThanGreaterThanToken */, ">>>": 48 /* GreaterThanGreaterThanGreaterThanToken */, "&": 49 /* AmpersandToken */, "|": 50 /* BarToken */, "^": 51 /* CaretToken */, "!": 52 /* ExclamationToken */, "~": 53 /* TildeToken */, "&&": 54 /* AmpersandAmpersandToken */, "||": 55 /* BarBarToken */, "?": 56 /* QuestionToken */, ":": 57 /* ColonToken */, "=": 59 /* EqualsToken */, "+=": 60 /* PlusEqualsToken */, "-=": 61 /* MinusEqualsToken */, "*=": 62 /* AsteriskEqualsToken */, "**=": 63 /* AsteriskAsteriskEqualsToken */, "/=": 64 /* SlashEqualsToken */, "%=": 65 /* PercentEqualsToken */, "<<=": 66 /* LessThanLessThanEqualsToken */, ">>=": 67 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 69 /* AmpersandEqualsToken */, "|=": 70 /* BarEqualsToken */, "^=": 71 /* CaretEqualsToken */, "@": 58 /* AtToken */ }));
6479 /*
6480 As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
6481 IdentifierStart ::
6482 Can contain Unicode 3.0.0 categories:
6483 Uppercase letter (Lu),
6484 Lowercase letter (Ll),
6485 Titlecase letter (Lt),
6486 Modifier letter (Lm),
6487 Other letter (Lo), or
6488 Letter number (Nl).
6489 IdentifierPart :: =
6490 Can contain IdentifierStart + Unicode 3.0.0 categories:
6491 Non-spacing mark (Mn),
6492 Combining spacing mark (Mc),
6493 Decimal number (Nd), or
6494 Connector punctuation (Pc).
6495
6496 Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
6497 http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
6498 */
6499 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,];
6500 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,];
6501 /*
6502 As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
6503 IdentifierStart ::
6504 Can contain Unicode 6.2 categories:
6505 Uppercase letter (Lu),
6506 Lowercase letter (Ll),
6507 Titlecase letter (Lt),
6508 Modifier letter (Lm),
6509 Other letter (Lo), or
6510 Letter number (Nl).
6511 IdentifierPart ::
6512 Can contain IdentifierStart + Unicode 6.2 categories:
6513 Non-spacing mark (Mn),
6514 Combining spacing mark (Mc),
6515 Decimal number (Nd),
6516 Connector punctuation (Pc),
6517 <ZWNJ>, or
6518 <ZWJ>.
6519
6520 Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
6521 http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
6522 */
6523 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,];
6524 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,];
6525 function lookupInUnicodeMap(code, map) {
6526 // Bail out quickly if it couldn't possibly be in the map.
6527 if (code < map[0]) {
6528 return false;
6529 }
6530 // Perform binary search in one of the Unicode range maps
6531 var lo = 0;
6532 var hi = map.length;
6533 var mid;
6534 while (lo + 1 < hi) {
6535 mid = lo + (hi - lo) / 2;
6536 // mid has to be even to catch a range's beginning
6537 mid -= mid % 2;
6538 if (map[mid] <= code && code <= map[mid + 1]) {
6539 return true;
6540 }
6541 if (code < map[mid]) {
6542 hi = mid;
6543 }
6544 else {
6545 lo = mid + 2;
6546 }
6547 }
6548 return false;
6549 }
6550 /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
6551 return languageVersion >= 1 /* ES5 */ ?
6552 lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
6553 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
6554 }
6555 ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
6556 function isUnicodeIdentifierPart(code, languageVersion) {
6557 return languageVersion >= 1 /* ES5 */ ?
6558 lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
6559 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
6560 }
6561 function makeReverseMap(source) {
6562 var result = [];
6563 source.forEach(function (value, name) {
6564 result[value] = name;
6565 });
6566 return result;
6567 }
6568 var tokenStrings = makeReverseMap(textToToken);
6569 function tokenToString(t) {
6570 return tokenStrings[t];
6571 }
6572 ts.tokenToString = tokenToString;
6573 /* @internal */
6574 function stringToToken(s) {
6575 return textToToken.get(s);
6576 }
6577 ts.stringToToken = stringToToken;
6578 /* @internal */
6579 function computeLineStarts(text) {
6580 var result = new Array();
6581 var pos = 0;
6582 var lineStart = 0;
6583 while (pos < text.length) {
6584 var ch = text.charCodeAt(pos);
6585 pos++;
6586 switch (ch) {
6587 case 13 /* carriageReturn */:
6588 if (text.charCodeAt(pos) === 10 /* lineFeed */) {
6589 pos++;
6590 }
6591 // falls through
6592 case 10 /* lineFeed */:
6593 result.push(lineStart);
6594 lineStart = pos;
6595 break;
6596 default:
6597 if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
6598 result.push(lineStart);
6599 lineStart = pos;
6600 }
6601 break;
6602 }
6603 }
6604 result.push(lineStart);
6605 return result;
6606 }
6607 ts.computeLineStarts = computeLineStarts;
6608 function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
6609 return sourceFile.getPositionOfLineAndCharacter ?
6610 sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
6611 computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
6612 }
6613 ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
6614 /* @internal */
6615 function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
6616 if (line < 0 || line >= lineStarts.length) {
6617 if (allowEdits) {
6618 // Clamp line to nearest allowable value
6619 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
6620 }
6621 else {
6622 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
6623 }
6624 }
6625 var res = lineStarts[line] + character;
6626 if (allowEdits) {
6627 // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
6628 // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
6629 // apply them to the computed position to improve accuracy
6630 return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
6631 }
6632 if (line < lineStarts.length - 1) {
6633 ts.Debug.assert(res < lineStarts[line + 1]);
6634 }
6635 else if (debugText !== undefined) {
6636 ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
6637 }
6638 return res;
6639 }
6640 ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
6641 /* @internal */
6642 function getLineStarts(sourceFile) {
6643 return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
6644 }
6645 ts.getLineStarts = getLineStarts;
6646 /* @internal */
6647 /**
6648 * We assume the first line starts at position 0 and 'position' is non-negative.
6649 */
6650 function computeLineAndCharacterOfPosition(lineStarts, position) {
6651 var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues);
6652 if (lineNumber < 0) {
6653 // If the actual position was not found,
6654 // the binary search returns the 2's-complement of the next line start
6655 // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
6656 // then the search will return -2.
6657 //
6658 // We want the index of the previous line start, so we subtract 1.
6659 // Review 2's-complement if this is confusing.
6660 lineNumber = ~lineNumber - 1;
6661 ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
6662 }
6663 return {
6664 line: lineNumber,
6665 character: position - lineStarts[lineNumber]
6666 };
6667 }
6668 ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
6669 function getLineAndCharacterOfPosition(sourceFile, position) {
6670 return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
6671 }
6672 ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
6673 function isWhiteSpaceLike(ch) {
6674 return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
6675 }
6676 ts.isWhiteSpaceLike = isWhiteSpaceLike;
6677 /** Does not include line breaks. For that, see isWhiteSpaceLike. */
6678 function isWhiteSpaceSingleLine(ch) {
6679 // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
6680 // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
6681 return ch === 32 /* space */ ||
6682 ch === 9 /* tab */ ||
6683 ch === 11 /* verticalTab */ ||
6684 ch === 12 /* formFeed */ ||
6685 ch === 160 /* nonBreakingSpace */ ||
6686 ch === 133 /* nextLine */ ||
6687 ch === 5760 /* ogham */ ||
6688 ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
6689 ch === 8239 /* narrowNoBreakSpace */ ||
6690 ch === 8287 /* mathematicalSpace */ ||
6691 ch === 12288 /* ideographicSpace */ ||
6692 ch === 65279 /* byteOrderMark */;
6693 }
6694 ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
6695 function isLineBreak(ch) {
6696 // ES5 7.3:
6697 // The ECMAScript line terminator characters are listed in Table 3.
6698 // Table 3: Line Terminator Characters
6699 // Code Unit Value Name Formal Name
6700 // \u000A Line Feed <LF>
6701 // \u000D Carriage Return <CR>
6702 // \u2028 Line separator <LS>
6703 // \u2029 Paragraph separator <PS>
6704 // Only the characters in Table 3 are treated as line terminators. Other new line or line
6705 // breaking characters are treated as white space but not as line terminators.
6706 return ch === 10 /* lineFeed */ ||
6707 ch === 13 /* carriageReturn */ ||
6708 ch === 8232 /* lineSeparator */ ||
6709 ch === 8233 /* paragraphSeparator */;
6710 }
6711 ts.isLineBreak = isLineBreak;
6712 function isDigit(ch) {
6713 return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
6714 }
6715 /* @internal */
6716 function isOctalDigit(ch) {
6717 return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
6718 }
6719 ts.isOctalDigit = isOctalDigit;
6720 function couldStartTrivia(text, pos) {
6721 // Keep in sync with skipTrivia
6722 var ch = text.charCodeAt(pos);
6723 switch (ch) {
6724 case 13 /* carriageReturn */:
6725 case 10 /* lineFeed */:
6726 case 9 /* tab */:
6727 case 11 /* verticalTab */:
6728 case 12 /* formFeed */:
6729 case 32 /* space */:
6730 case 47 /* slash */:
6731 // starts of normal trivia
6732 case 60 /* lessThan */:
6733 case 124 /* bar */:
6734 case 61 /* equals */:
6735 case 62 /* greaterThan */:
6736 // Starts of conflict marker trivia
6737 return true;
6738 case 35 /* hash */:
6739 // Only if its the beginning can we have #! trivia
6740 return pos === 0;
6741 default:
6742 return ch > 127 /* maxAsciiCharacter */;
6743 }
6744 }
6745 ts.couldStartTrivia = couldStartTrivia;
6746 /* @internal */
6747 function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
6748 if (stopAtComments === void 0) { stopAtComments = false; }
6749 if (ts.positionIsSynthesized(pos)) {
6750 return pos;
6751 }
6752 // Keep in sync with couldStartTrivia
6753 while (true) {
6754 var ch = text.charCodeAt(pos);
6755 switch (ch) {
6756 case 13 /* carriageReturn */:
6757 if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
6758 pos++;
6759 }
6760 // falls through
6761 case 10 /* lineFeed */:
6762 pos++;
6763 if (stopAfterLineBreak) {
6764 return pos;
6765 }
6766 continue;
6767 case 9 /* tab */:
6768 case 11 /* verticalTab */:
6769 case 12 /* formFeed */:
6770 case 32 /* space */:
6771 pos++;
6772 continue;
6773 case 47 /* slash */:
6774 if (stopAtComments) {
6775 break;
6776 }
6777 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
6778 pos += 2;
6779 while (pos < text.length) {
6780 if (isLineBreak(text.charCodeAt(pos))) {
6781 break;
6782 }
6783 pos++;
6784 }
6785 continue;
6786 }
6787 if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
6788 pos += 2;
6789 while (pos < text.length) {
6790 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
6791 pos += 2;
6792 break;
6793 }
6794 pos++;
6795 }
6796 continue;
6797 }
6798 break;
6799 case 60 /* lessThan */:
6800 case 124 /* bar */:
6801 case 61 /* equals */:
6802 case 62 /* greaterThan */:
6803 if (isConflictMarkerTrivia(text, pos)) {
6804 pos = scanConflictMarkerTrivia(text, pos);
6805 continue;
6806 }
6807 break;
6808 case 35 /* hash */:
6809 if (pos === 0 && isShebangTrivia(text, pos)) {
6810 pos = scanShebangTrivia(text, pos);
6811 continue;
6812 }
6813 break;
6814 default:
6815 if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
6816 pos++;
6817 continue;
6818 }
6819 break;
6820 }
6821 return pos;
6822 }
6823 }
6824 ts.skipTrivia = skipTrivia;
6825 // All conflict markers consist of the same character repeated seven times. If it is
6826 // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
6827 var mergeConflictMarkerLength = "<<<<<<<".length;
6828 function isConflictMarkerTrivia(text, pos) {
6829 ts.Debug.assert(pos >= 0);
6830 // Conflict markers must be at the start of a line.
6831 if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
6832 var ch = text.charCodeAt(pos);
6833 if ((pos + mergeConflictMarkerLength) < text.length) {
6834 for (var i = 0; i < mergeConflictMarkerLength; i++) {
6835 if (text.charCodeAt(pos + i) !== ch) {
6836 return false;
6837 }
6838 }
6839 return ch === 61 /* equals */ ||
6840 text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
6841 }
6842 }
6843 return false;
6844 }
6845 function scanConflictMarkerTrivia(text, pos, error) {
6846 if (error) {
6847 error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
6848 }
6849 var ch = text.charCodeAt(pos);
6850 var len = text.length;
6851 if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
6852 while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
6853 pos++;
6854 }
6855 }
6856 else {
6857 ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
6858 // Consume everything from the start of a ||||||| or ======= marker to the start
6859 // of the next ======= or >>>>>>> marker.
6860 while (pos < len) {
6861 var currentChar = text.charCodeAt(pos);
6862 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
6863 break;
6864 }
6865 pos++;
6866 }
6867 }
6868 return pos;
6869 }
6870 var shebangTriviaRegex = /^#!.*/;
6871 /*@internal*/
6872 function isShebangTrivia(text, pos) {
6873 // Shebangs check must only be done at the start of the file
6874 ts.Debug.assert(pos === 0);
6875 return shebangTriviaRegex.test(text);
6876 }
6877 ts.isShebangTrivia = isShebangTrivia;
6878 /*@internal*/
6879 function scanShebangTrivia(text, pos) {
6880 var shebang = shebangTriviaRegex.exec(text)[0];
6881 pos = pos + shebang.length;
6882 return pos;
6883 }
6884 ts.scanShebangTrivia = scanShebangTrivia;
6885 /**
6886 * Invokes a callback for each comment range following the provided position.
6887 *
6888 * Single-line comment ranges include the leading double-slash characters but not the ending
6889 * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
6890 * asterisk-slash characters.
6891 *
6892 * @param reduce If true, accumulates the result of calling the callback in a fashion similar
6893 * to reduceLeft. If false, iteration stops when the callback returns a truthy value.
6894 * @param text The source text to scan.
6895 * @param pos The position at which to start scanning.
6896 * @param trailing If false, whitespace is skipped until the first line break and comments
6897 * between that location and the next token are returned. If true, comments occurring
6898 * between the given position and the next line break are returned.
6899 * @param cb The callback to execute as each comment range is encountered.
6900 * @param state A state value to pass to each iteration of the callback.
6901 * @param initial An initial value to pass when accumulating results (when "reduce" is true).
6902 * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
6903 * return value of the callback.
6904 */
6905 function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
6906 var pendingPos;
6907 var pendingEnd;
6908 var pendingKind;
6909 var pendingHasTrailingNewLine;
6910 var hasPendingCommentRange = false;
6911 var collecting = trailing;
6912 var accumulator = initial;
6913 if (pos === 0) {
6914 collecting = true;
6915 var shebang = getShebang(text);
6916 if (shebang) {
6917 pos = shebang.length;
6918 }
6919 }
6920 scan: while (pos >= 0 && pos < text.length) {
6921 var ch = text.charCodeAt(pos);
6922 switch (ch) {
6923 case 13 /* carriageReturn */:
6924 if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
6925 pos++;
6926 }
6927 // falls through
6928 case 10 /* lineFeed */:
6929 pos++;
6930 if (trailing) {
6931 break scan;
6932 }
6933 collecting = true;
6934 if (hasPendingCommentRange) {
6935 pendingHasTrailingNewLine = true;
6936 }
6937 continue;
6938 case 9 /* tab */:
6939 case 11 /* verticalTab */:
6940 case 12 /* formFeed */:
6941 case 32 /* space */:
6942 pos++;
6943 continue;
6944 case 47 /* slash */:
6945 var nextChar = text.charCodeAt(pos + 1);
6946 var hasTrailingNewLine = false;
6947 if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
6948 var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
6949 var startPos = pos;
6950 pos += 2;
6951 if (nextChar === 47 /* slash */) {
6952 while (pos < text.length) {
6953 if (isLineBreak(text.charCodeAt(pos))) {
6954 hasTrailingNewLine = true;
6955 break;
6956 }
6957 pos++;
6958 }
6959 }
6960 else {
6961 while (pos < text.length) {
6962 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
6963 pos += 2;
6964 break;
6965 }
6966 pos++;
6967 }
6968 }
6969 if (collecting) {
6970 if (hasPendingCommentRange) {
6971 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
6972 if (!reduce && accumulator) {
6973 // If we are not reducing and we have a truthy result, return it.
6974 return accumulator;
6975 }
6976 }
6977 pendingPos = startPos;
6978 pendingEnd = pos;
6979 pendingKind = kind;
6980 pendingHasTrailingNewLine = hasTrailingNewLine;
6981 hasPendingCommentRange = true;
6982 }
6983 continue;
6984 }
6985 break scan;
6986 default:
6987 if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
6988 if (hasPendingCommentRange && isLineBreak(ch)) {
6989 pendingHasTrailingNewLine = true;
6990 }
6991 pos++;
6992 continue;
6993 }
6994 break scan;
6995 }
6996 }
6997 if (hasPendingCommentRange) {
6998 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
6999 }
7000 return accumulator;
7001 }
7002 function forEachLeadingCommentRange(text, pos, cb, state) {
7003 return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
7004 }
7005 ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
7006 function forEachTrailingCommentRange(text, pos, cb, state) {
7007 return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
7008 }
7009 ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
7010 function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
7011 return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
7012 }
7013 ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
7014 function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
7015 return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
7016 }
7017 ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
7018 function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
7019 if (!comments) {
7020 comments = [];
7021 }
7022 comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
7023 return comments;
7024 }
7025 function getLeadingCommentRanges(text, pos) {
7026 return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
7027 }
7028 ts.getLeadingCommentRanges = getLeadingCommentRanges;
7029 function getTrailingCommentRanges(text, pos) {
7030 return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
7031 }
7032 ts.getTrailingCommentRanges = getTrailingCommentRanges;
7033 /** Optionally, get the shebang */
7034 function getShebang(text) {
7035 var match = shebangTriviaRegex.exec(text);
7036 if (match) {
7037 return match[0];
7038 }
7039 }
7040 ts.getShebang = getShebang;
7041 function isIdentifierStart(ch, languageVersion) {
7042 return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
7043 ch === 36 /* $ */ || ch === 95 /* _ */ ||
7044 ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
7045 }
7046 ts.isIdentifierStart = isIdentifierStart;
7047 function isIdentifierPart(ch, languageVersion) {
7048 return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
7049 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
7050 ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
7051 }
7052 ts.isIdentifierPart = isIdentifierPart;
7053 /* @internal */
7054 function isIdentifierText(name, languageVersion) {
7055 if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) {
7056 return false;
7057 }
7058 for (var i = 1; i < name.length; i++) {
7059 if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) {
7060 return false;
7061 }
7062 }
7063 return true;
7064 }
7065 ts.isIdentifierText = isIdentifierText;
7066 // Creates a scanner over a (possibly unspecified) range of a piece of text.
7067 function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
7068 if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
7069 var text = textInitial;
7070 // Current position (end position of text of current token)
7071 var pos;
7072 // end of text
7073 var end;
7074 // Start position of whitespace before current token
7075 var startPos;
7076 // Start position of text of current token
7077 var tokenPos;
7078 var token;
7079 var tokenValue;
7080 var tokenFlags;
7081 var inJSDocType = 0;
7082 setText(text, start, length);
7083 return {
7084 getStartPos: function () { return startPos; },
7085 getTextPos: function () { return pos; },
7086 getToken: function () { return token; },
7087 getTokenPos: function () { return tokenPos; },
7088 getTokenText: function () { return text.substring(tokenPos, pos); },
7089 getTokenValue: function () { return tokenValue; },
7090 hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
7091 hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
7092 isIdentifier: function () { return token === 72 /* Identifier */ || token > 108 /* LastReservedWord */; },
7093 isReservedWord: function () { return token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */; },
7094 isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
7095 getTokenFlags: function () { return tokenFlags; },
7096 reScanGreaterToken: reScanGreaterToken,
7097 reScanSlashToken: reScanSlashToken,
7098 reScanTemplateToken: reScanTemplateToken,
7099 scanJsxIdentifier: scanJsxIdentifier,
7100 scanJsxAttributeValue: scanJsxAttributeValue,
7101 reScanJsxToken: reScanJsxToken,
7102 reScanLessThanToken: reScanLessThanToken,
7103 scanJsxToken: scanJsxToken,
7104 scanJSDocToken: scanJSDocToken,
7105 scan: scan,
7106 getText: getText,
7107 setText: setText,
7108 setScriptTarget: setScriptTarget,
7109 setLanguageVariant: setLanguageVariant,
7110 setOnError: setOnError,
7111 setTextPos: setTextPos,
7112 setInJSDocType: setInJSDocType,
7113 tryScan: tryScan,
7114 lookAhead: lookAhead,
7115 scanRange: scanRange,
7116 };
7117 function error(message, errPos, length) {
7118 if (errPos === void 0) { errPos = pos; }
7119 if (onError) {
7120 var oldPos = pos;
7121 pos = errPos;
7122 onError(message, length || 0);
7123 pos = oldPos;
7124 }
7125 }
7126 function scanNumberFragment() {
7127 var start = pos;
7128 var allowSeparator = false;
7129 var isPreviousTokenSeparator = false;
7130 var result = "";
7131 while (true) {
7132 var ch = text.charCodeAt(pos);
7133 if (ch === 95 /* _ */) {
7134 tokenFlags |= 512 /* ContainsSeparator */;
7135 if (allowSeparator) {
7136 allowSeparator = false;
7137 isPreviousTokenSeparator = true;
7138 result += text.substring(start, pos);
7139 }
7140 else if (isPreviousTokenSeparator) {
7141 error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
7142 }
7143 else {
7144 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
7145 }
7146 pos++;
7147 start = pos;
7148 continue;
7149 }
7150 if (isDigit(ch)) {
7151 allowSeparator = true;
7152 isPreviousTokenSeparator = false;
7153 pos++;
7154 continue;
7155 }
7156 break;
7157 }
7158 if (text.charCodeAt(pos - 1) === 95 /* _ */) {
7159 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
7160 }
7161 return result + text.substring(start, pos);
7162 }
7163 function scanNumber() {
7164 var start = pos;
7165 var mainFragment = scanNumberFragment();
7166 var decimalFragment;
7167 var scientificFragment;
7168 if (text.charCodeAt(pos) === 46 /* dot */) {
7169 pos++;
7170 decimalFragment = scanNumberFragment();
7171 }
7172 var end = pos;
7173 if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
7174 pos++;
7175 tokenFlags |= 16 /* Scientific */;
7176 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
7177 pos++;
7178 var preNumericPart = pos;
7179 var finalFragment = scanNumberFragment();
7180 if (!finalFragment) {
7181 error(ts.Diagnostics.Digit_expected);
7182 }
7183 else {
7184 scientificFragment = text.substring(end, preNumericPart) + finalFragment;
7185 end = pos;
7186 }
7187 }
7188 var result;
7189 if (tokenFlags & 512 /* ContainsSeparator */) {
7190 result = mainFragment;
7191 if (decimalFragment) {
7192 result += "." + decimalFragment;
7193 }
7194 if (scientificFragment) {
7195 result += scientificFragment;
7196 }
7197 }
7198 else {
7199 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
7200 }
7201 if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
7202 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
7203 return {
7204 type: 8 /* NumericLiteral */,
7205 value: "" + +result // if value is not an integer, it can be safely coerced to a number
7206 };
7207 }
7208 else {
7209 tokenValue = result;
7210 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
7211 checkForIdentifierStartAfterNumericLiteral(start);
7212 return { type: type, value: tokenValue };
7213 }
7214 }
7215 function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
7216 if (!isIdentifierStart(text.charCodeAt(pos), languageVersion)) {
7217 return;
7218 }
7219 var identifierStart = pos;
7220 var length = scanIdentifierParts().length;
7221 if (length === 1 && text[identifierStart] === "n") {
7222 if (isScientific) {
7223 error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
7224 }
7225 else {
7226 error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
7227 }
7228 }
7229 else {
7230 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
7231 pos = identifierStart;
7232 }
7233 }
7234 function scanOctalDigits() {
7235 var start = pos;
7236 while (isOctalDigit(text.charCodeAt(pos))) {
7237 pos++;
7238 }
7239 return +(text.substring(start, pos));
7240 }
7241 /**
7242 * Scans the given number of hexadecimal digits in the text,
7243 * returning -1 if the given number is unavailable.
7244 */
7245 function scanExactNumberOfHexDigits(count, canHaveSeparators) {
7246 var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
7247 return valueString ? parseInt(valueString, 16) : -1;
7248 }
7249 /**
7250 * Scans as many hexadecimal digits as are available in the text,
7251 * returning "" if the given number of digits was unavailable.
7252 */
7253 function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
7254 return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
7255 }
7256 function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
7257 var valueChars = [];
7258 var allowSeparator = false;
7259 var isPreviousTokenSeparator = false;
7260 while (valueChars.length < minCount || scanAsManyAsPossible) {
7261 var ch = text.charCodeAt(pos);
7262 if (canHaveSeparators && ch === 95 /* _ */) {
7263 tokenFlags |= 512 /* ContainsSeparator */;
7264 if (allowSeparator) {
7265 allowSeparator = false;
7266 isPreviousTokenSeparator = true;
7267 }
7268 else if (isPreviousTokenSeparator) {
7269 error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
7270 }
7271 else {
7272 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
7273 }
7274 pos++;
7275 continue;
7276 }
7277 allowSeparator = canHaveSeparators;
7278 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
7279 ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
7280 }
7281 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
7282 (ch >= 97 /* a */ && ch <= 102 /* f */))) {
7283 break;
7284 }
7285 valueChars.push(ch);
7286 pos++;
7287 isPreviousTokenSeparator = false;
7288 }
7289 if (valueChars.length < minCount) {
7290 valueChars = [];
7291 }
7292 if (text.charCodeAt(pos - 1) === 95 /* _ */) {
7293 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
7294 }
7295 return String.fromCharCode.apply(String, valueChars);
7296 }
7297 function scanString(jsxAttributeString) {
7298 if (jsxAttributeString === void 0) { jsxAttributeString = false; }
7299 var quote = text.charCodeAt(pos);
7300 pos++;
7301 var result = "";
7302 var start = pos;
7303 while (true) {
7304 if (pos >= end) {
7305 result += text.substring(start, pos);
7306 tokenFlags |= 4 /* Unterminated */;
7307 error(ts.Diagnostics.Unterminated_string_literal);
7308 break;
7309 }
7310 var ch = text.charCodeAt(pos);
7311 if (ch === quote) {
7312 result += text.substring(start, pos);
7313 pos++;
7314 break;
7315 }
7316 if (ch === 92 /* backslash */ && !jsxAttributeString) {
7317 result += text.substring(start, pos);
7318 result += scanEscapeSequence();
7319 start = pos;
7320 continue;
7321 }
7322 if (isLineBreak(ch) && !jsxAttributeString) {
7323 result += text.substring(start, pos);
7324 tokenFlags |= 4 /* Unterminated */;
7325 error(ts.Diagnostics.Unterminated_string_literal);
7326 break;
7327 }
7328 pos++;
7329 }
7330 return result;
7331 }
7332 /**
7333 * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
7334 * a literal component of a TemplateExpression.
7335 */
7336 function scanTemplateAndSetTokenValue() {
7337 var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
7338 pos++;
7339 var start = pos;
7340 var contents = "";
7341 var resultingToken;
7342 while (true) {
7343 if (pos >= end) {
7344 contents += text.substring(start, pos);
7345 tokenFlags |= 4 /* Unterminated */;
7346 error(ts.Diagnostics.Unterminated_template_literal);
7347 resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
7348 break;
7349 }
7350 var currChar = text.charCodeAt(pos);
7351 // '`'
7352 if (currChar === 96 /* backtick */) {
7353 contents += text.substring(start, pos);
7354 pos++;
7355 resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
7356 break;
7357 }
7358 // '${'
7359 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
7360 contents += text.substring(start, pos);
7361 pos += 2;
7362 resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
7363 break;
7364 }
7365 // Escape character
7366 if (currChar === 92 /* backslash */) {
7367 contents += text.substring(start, pos);
7368 contents += scanEscapeSequence();
7369 start = pos;
7370 continue;
7371 }
7372 // Speculated ECMAScript 6 Spec 11.8.6.1:
7373 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
7374 if (currChar === 13 /* carriageReturn */) {
7375 contents += text.substring(start, pos);
7376 pos++;
7377 if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
7378 pos++;
7379 }
7380 contents += "\n";
7381 start = pos;
7382 continue;
7383 }
7384 pos++;
7385 }
7386 ts.Debug.assert(resultingToken !== undefined);
7387 tokenValue = contents;
7388 return resultingToken;
7389 }
7390 function scanEscapeSequence() {
7391 pos++;
7392 if (pos >= end) {
7393 error(ts.Diagnostics.Unexpected_end_of_text);
7394 return "";
7395 }
7396 var ch = text.charCodeAt(pos);
7397 pos++;
7398 switch (ch) {
7399 case 48 /* _0 */:
7400 return "\0";
7401 case 98 /* b */:
7402 return "\b";
7403 case 116 /* t */:
7404 return "\t";
7405 case 110 /* n */:
7406 return "\n";
7407 case 118 /* v */:
7408 return "\v";
7409 case 102 /* f */:
7410 return "\f";
7411 case 114 /* r */:
7412 return "\r";
7413 case 39 /* singleQuote */:
7414 return "\'";
7415 case 34 /* doubleQuote */:
7416 return "\"";
7417 case 117 /* u */:
7418 // '\u{DDDDDDDD}'
7419 if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
7420 tokenFlags |= 8 /* ExtendedUnicodeEscape */;
7421 pos++;
7422 return scanExtendedUnicodeEscape();
7423 }
7424 // '\uDDDD'
7425 return scanHexadecimalEscape(/*numDigits*/ 4);
7426 case 120 /* x */:
7427 // '\xDD'
7428 return scanHexadecimalEscape(/*numDigits*/ 2);
7429 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
7430 // the line terminator is interpreted to be "the empty code unit sequence".
7431 case 13 /* carriageReturn */:
7432 if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
7433 pos++;
7434 }
7435 // falls through
7436 case 10 /* lineFeed */:
7437 case 8232 /* lineSeparator */:
7438 case 8233 /* paragraphSeparator */:
7439 return "";
7440 default:
7441 return String.fromCharCode(ch);
7442 }
7443 }
7444 function scanHexadecimalEscape(numDigits) {
7445 var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
7446 if (escapedValue >= 0) {
7447 return String.fromCharCode(escapedValue);
7448 }
7449 else {
7450 error(ts.Diagnostics.Hexadecimal_digit_expected);
7451 return "";
7452 }
7453 }
7454 function scanExtendedUnicodeEscape() {
7455 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
7456 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
7457 var isInvalidExtendedEscape = false;
7458 // Validate the value of the digit
7459 if (escapedValue < 0) {
7460 error(ts.Diagnostics.Hexadecimal_digit_expected);
7461 isInvalidExtendedEscape = true;
7462 }
7463 else if (escapedValue > 0x10FFFF) {
7464 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
7465 isInvalidExtendedEscape = true;
7466 }
7467 if (pos >= end) {
7468 error(ts.Diagnostics.Unexpected_end_of_text);
7469 isInvalidExtendedEscape = true;
7470 }
7471 else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
7472 // Only swallow the following character up if it's a '}'.
7473 pos++;
7474 }
7475 else {
7476 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
7477 isInvalidExtendedEscape = true;
7478 }
7479 if (isInvalidExtendedEscape) {
7480 return "";
7481 }
7482 return utf16EncodeAsString(escapedValue);
7483 }
7484 // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
7485 function utf16EncodeAsString(codePoint) {
7486 ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
7487 if (codePoint <= 65535) {
7488 return String.fromCharCode(codePoint);
7489 }
7490 var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
7491 var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
7492 return String.fromCharCode(codeUnit1, codeUnit2);
7493 }
7494 // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
7495 // and return code point value if valid Unicode escape is found. Otherwise return -1.
7496 function peekUnicodeEscape() {
7497 if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
7498 var start_1 = pos;
7499 pos += 2;
7500 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
7501 pos = start_1;
7502 return value;
7503 }
7504 return -1;
7505 }
7506 function scanIdentifierParts() {
7507 var result = "";
7508 var start = pos;
7509 while (pos < end) {
7510 var ch = text.charCodeAt(pos);
7511 if (isIdentifierPart(ch, languageVersion)) {
7512 pos++;
7513 }
7514 else if (ch === 92 /* backslash */) {
7515 ch = peekUnicodeEscape();
7516 if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
7517 break;
7518 }
7519 result += text.substring(start, pos);
7520 result += String.fromCharCode(ch);
7521 // Valid Unicode escape is always six characters
7522 pos += 6;
7523 start = pos;
7524 }
7525 else {
7526 break;
7527 }
7528 }
7529 result += text.substring(start, pos);
7530 return result;
7531 }
7532 function getIdentifierToken() {
7533 // Reserved words are between 2 and 11 characters long and start with a lowercase letter
7534 var len = tokenValue.length;
7535 if (len >= 2 && len <= 11) {
7536 var ch = tokenValue.charCodeAt(0);
7537 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
7538 var keyword = textToKeyword.get(tokenValue);
7539 if (keyword !== undefined) {
7540 return token = keyword;
7541 }
7542 }
7543 }
7544 return token = 72 /* Identifier */;
7545 }
7546 function scanBinaryOrOctalDigits(base) {
7547 var value = "";
7548 // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
7549 // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
7550 var separatorAllowed = false;
7551 var isPreviousTokenSeparator = false;
7552 while (true) {
7553 var ch = text.charCodeAt(pos);
7554 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
7555 if (ch === 95 /* _ */) {
7556 tokenFlags |= 512 /* ContainsSeparator */;
7557 if (separatorAllowed) {
7558 separatorAllowed = false;
7559 isPreviousTokenSeparator = true;
7560 }
7561 else if (isPreviousTokenSeparator) {
7562 error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
7563 }
7564 else {
7565 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
7566 }
7567 pos++;
7568 continue;
7569 }
7570 separatorAllowed = true;
7571 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
7572 break;
7573 }
7574 value += text[pos];
7575 pos++;
7576 isPreviousTokenSeparator = false;
7577 }
7578 if (text.charCodeAt(pos - 1) === 95 /* _ */) {
7579 // Literal ends with underscore - not allowed
7580 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
7581 }
7582 return value;
7583 }
7584 function checkBigIntSuffix() {
7585 if (text.charCodeAt(pos) === 110 /* n */) {
7586 tokenValue += "n";
7587 // Use base 10 instead of base 2 or base 8 for shorter literals
7588 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
7589 tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
7590 }
7591 pos++;
7592 return 9 /* BigIntLiteral */;
7593 }
7594 else { // not a bigint, so can convert to number in simplified form
7595 // Number() may not support 0b or 0o, so use parseInt() instead
7596 var numericValue = tokenFlags & 128 /* BinarySpecifier */
7597 ? parseInt(tokenValue.slice(2), 2) // skip "0b"
7598 : tokenFlags & 256 /* OctalSpecifier */
7599 ? parseInt(tokenValue.slice(2), 8) // skip "0o"
7600 : +tokenValue;
7601 tokenValue = "" + numericValue;
7602 return 8 /* NumericLiteral */;
7603 }
7604 }
7605 function scan() {
7606 var _a;
7607 startPos = pos;
7608 tokenFlags = 0;
7609 var asteriskSeen = false;
7610 while (true) {
7611 tokenPos = pos;
7612 if (pos >= end) {
7613 return token = 1 /* EndOfFileToken */;
7614 }
7615 var ch = text.charCodeAt(pos);
7616 // Special handling for shebang
7617 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
7618 pos = scanShebangTrivia(text, pos);
7619 if (skipTrivia) {
7620 continue;
7621 }
7622 else {
7623 return token = 6 /* ShebangTrivia */;
7624 }
7625 }
7626 switch (ch) {
7627 case 10 /* lineFeed */:
7628 case 13 /* carriageReturn */:
7629 tokenFlags |= 1 /* PrecedingLineBreak */;
7630 if (skipTrivia) {
7631 pos++;
7632 continue;
7633 }
7634 else {
7635 if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
7636 // consume both CR and LF
7637 pos += 2;
7638 }
7639 else {
7640 pos++;
7641 }
7642 return token = 4 /* NewLineTrivia */;
7643 }
7644 case 9 /* tab */:
7645 case 11 /* verticalTab */:
7646 case 12 /* formFeed */:
7647 case 32 /* space */:
7648 case 160 /* nonBreakingSpace */:
7649 case 5760 /* ogham */:
7650 case 8192 /* enQuad */:
7651 case 8193 /* emQuad */:
7652 case 8194 /* enSpace */:
7653 case 8195 /* emSpace */:
7654 case 8196 /* threePerEmSpace */:
7655 case 8197 /* fourPerEmSpace */:
7656 case 8198 /* sixPerEmSpace */:
7657 case 8199 /* figureSpace */:
7658 case 8200 /* punctuationSpace */:
7659 case 8201 /* thinSpace */:
7660 case 8202 /* hairSpace */:
7661 case 8203 /* zeroWidthSpace */:
7662 case 8239 /* narrowNoBreakSpace */:
7663 case 8287 /* mathematicalSpace */:
7664 case 12288 /* ideographicSpace */:
7665 case 65279 /* byteOrderMark */:
7666 if (skipTrivia) {
7667 pos++;
7668 continue;
7669 }
7670 else {
7671 while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
7672 pos++;
7673 }
7674 return token = 5 /* WhitespaceTrivia */;
7675 }
7676 case 33 /* exclamation */:
7677 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7678 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
7679 return pos += 3, token = 36 /* ExclamationEqualsEqualsToken */;
7680 }
7681 return pos += 2, token = 34 /* ExclamationEqualsToken */;
7682 }
7683 pos++;
7684 return token = 52 /* ExclamationToken */;
7685 case 34 /* doubleQuote */:
7686 case 39 /* singleQuote */:
7687 tokenValue = scanString();
7688 return token = 10 /* StringLiteral */;
7689 case 96 /* backtick */:
7690 return token = scanTemplateAndSetTokenValue();
7691 case 37 /* percent */:
7692 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7693 return pos += 2, token = 65 /* PercentEqualsToken */;
7694 }
7695 pos++;
7696 return token = 43 /* PercentToken */;
7697 case 38 /* ampersand */:
7698 if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
7699 return pos += 2, token = 54 /* AmpersandAmpersandToken */;
7700 }
7701 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7702 return pos += 2, token = 69 /* AmpersandEqualsToken */;
7703 }
7704 pos++;
7705 return token = 49 /* AmpersandToken */;
7706 case 40 /* openParen */:
7707 pos++;
7708 return token = 20 /* OpenParenToken */;
7709 case 41 /* closeParen */:
7710 pos++;
7711 return token = 21 /* CloseParenToken */;
7712 case 42 /* asterisk */:
7713 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7714 return pos += 2, token = 62 /* AsteriskEqualsToken */;
7715 }
7716 if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
7717 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
7718 return pos += 3, token = 63 /* AsteriskAsteriskEqualsToken */;
7719 }
7720 return pos += 2, token = 41 /* AsteriskAsteriskToken */;
7721 }
7722 pos++;
7723 if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
7724 // decoration at the start of a JSDoc comment line
7725 asteriskSeen = true;
7726 continue;
7727 }
7728 return token = 40 /* AsteriskToken */;
7729 case 43 /* plus */:
7730 if (text.charCodeAt(pos + 1) === 43 /* plus */) {
7731 return pos += 2, token = 44 /* PlusPlusToken */;
7732 }
7733 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7734 return pos += 2, token = 60 /* PlusEqualsToken */;
7735 }
7736 pos++;
7737 return token = 38 /* PlusToken */;
7738 case 44 /* comma */:
7739 pos++;
7740 return token = 27 /* CommaToken */;
7741 case 45 /* minus */:
7742 if (text.charCodeAt(pos + 1) === 45 /* minus */) {
7743 return pos += 2, token = 45 /* MinusMinusToken */;
7744 }
7745 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7746 return pos += 2, token = 61 /* MinusEqualsToken */;
7747 }
7748 pos++;
7749 return token = 39 /* MinusToken */;
7750 case 46 /* dot */:
7751 if (isDigit(text.charCodeAt(pos + 1))) {
7752 tokenValue = scanNumber().value;
7753 return token = 8 /* NumericLiteral */;
7754 }
7755 if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
7756 return pos += 3, token = 25 /* DotDotDotToken */;
7757 }
7758 pos++;
7759 return token = 24 /* DotToken */;
7760 case 47 /* slash */:
7761 // Single-line comment
7762 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
7763 pos += 2;
7764 while (pos < end) {
7765 if (isLineBreak(text.charCodeAt(pos))) {
7766 break;
7767 }
7768 pos++;
7769 }
7770 if (skipTrivia) {
7771 continue;
7772 }
7773 else {
7774 return token = 2 /* SingleLineCommentTrivia */;
7775 }
7776 }
7777 // Multi-line comment
7778 if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
7779 pos += 2;
7780 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
7781 tokenFlags |= 2 /* PrecedingJSDocComment */;
7782 }
7783 var commentClosed = false;
7784 while (pos < end) {
7785 var ch_1 = text.charCodeAt(pos);
7786 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
7787 pos += 2;
7788 commentClosed = true;
7789 break;
7790 }
7791 if (isLineBreak(ch_1)) {
7792 tokenFlags |= 1 /* PrecedingLineBreak */;
7793 }
7794 pos++;
7795 }
7796 if (!commentClosed) {
7797 error(ts.Diagnostics.Asterisk_Slash_expected);
7798 }
7799 if (skipTrivia) {
7800 continue;
7801 }
7802 else {
7803 if (!commentClosed) {
7804 tokenFlags |= 4 /* Unterminated */;
7805 }
7806 return token = 3 /* MultiLineCommentTrivia */;
7807 }
7808 }
7809 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7810 return pos += 2, token = 64 /* SlashEqualsToken */;
7811 }
7812 pos++;
7813 return token = 42 /* SlashToken */;
7814 case 48 /* _0 */:
7815 if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
7816 pos += 2;
7817 tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
7818 if (!tokenValue) {
7819 error(ts.Diagnostics.Hexadecimal_digit_expected);
7820 tokenValue = "0";
7821 }
7822 tokenValue = "0x" + tokenValue;
7823 tokenFlags |= 64 /* HexSpecifier */;
7824 return token = checkBigIntSuffix();
7825 }
7826 else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
7827 pos += 2;
7828 tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
7829 if (!tokenValue) {
7830 error(ts.Diagnostics.Binary_digit_expected);
7831 tokenValue = "0";
7832 }
7833 tokenValue = "0b" + tokenValue;
7834 tokenFlags |= 128 /* BinarySpecifier */;
7835 return token = checkBigIntSuffix();
7836 }
7837 else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
7838 pos += 2;
7839 tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
7840 if (!tokenValue) {
7841 error(ts.Diagnostics.Octal_digit_expected);
7842 tokenValue = "0";
7843 }
7844 tokenValue = "0o" + tokenValue;
7845 tokenFlags |= 256 /* OctalSpecifier */;
7846 return token = checkBigIntSuffix();
7847 }
7848 // Try to parse as an octal
7849 if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
7850 tokenValue = "" + scanOctalDigits();
7851 tokenFlags |= 32 /* Octal */;
7852 return token = 8 /* NumericLiteral */;
7853 }
7854 // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
7855 // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
7856 // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
7857 // falls through
7858 case 49 /* _1 */:
7859 case 50 /* _2 */:
7860 case 51 /* _3 */:
7861 case 52 /* _4 */:
7862 case 53 /* _5 */:
7863 case 54 /* _6 */:
7864 case 55 /* _7 */:
7865 case 56 /* _8 */:
7866 case 57 /* _9 */:
7867 (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
7868 return token;
7869 case 58 /* colon */:
7870 pos++;
7871 return token = 57 /* ColonToken */;
7872 case 59 /* semicolon */:
7873 pos++;
7874 return token = 26 /* SemicolonToken */;
7875 case 60 /* lessThan */:
7876 if (isConflictMarkerTrivia(text, pos)) {
7877 pos = scanConflictMarkerTrivia(text, pos, error);
7878 if (skipTrivia) {
7879 continue;
7880 }
7881 else {
7882 return token = 7 /* ConflictMarkerTrivia */;
7883 }
7884 }
7885 if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
7886 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
7887 return pos += 3, token = 66 /* LessThanLessThanEqualsToken */;
7888 }
7889 return pos += 2, token = 46 /* LessThanLessThanToken */;
7890 }
7891 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7892 return pos += 2, token = 31 /* LessThanEqualsToken */;
7893 }
7894 if (languageVariant === 1 /* JSX */ &&
7895 text.charCodeAt(pos + 1) === 47 /* slash */ &&
7896 text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
7897 return pos += 2, token = 29 /* LessThanSlashToken */;
7898 }
7899 pos++;
7900 return token = 28 /* LessThanToken */;
7901 case 61 /* equals */:
7902 if (isConflictMarkerTrivia(text, pos)) {
7903 pos = scanConflictMarkerTrivia(text, pos, error);
7904 if (skipTrivia) {
7905 continue;
7906 }
7907 else {
7908 return token = 7 /* ConflictMarkerTrivia */;
7909 }
7910 }
7911 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7912 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
7913 return pos += 3, token = 35 /* EqualsEqualsEqualsToken */;
7914 }
7915 return pos += 2, token = 33 /* EqualsEqualsToken */;
7916 }
7917 if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
7918 return pos += 2, token = 37 /* EqualsGreaterThanToken */;
7919 }
7920 pos++;
7921 return token = 59 /* EqualsToken */;
7922 case 62 /* greaterThan */:
7923 if (isConflictMarkerTrivia(text, pos)) {
7924 pos = scanConflictMarkerTrivia(text, pos, error);
7925 if (skipTrivia) {
7926 continue;
7927 }
7928 else {
7929 return token = 7 /* ConflictMarkerTrivia */;
7930 }
7931 }
7932 pos++;
7933 return token = 30 /* GreaterThanToken */;
7934 case 63 /* question */:
7935 pos++;
7936 return token = 56 /* QuestionToken */;
7937 case 91 /* openBracket */:
7938 pos++;
7939 return token = 22 /* OpenBracketToken */;
7940 case 93 /* closeBracket */:
7941 pos++;
7942 return token = 23 /* CloseBracketToken */;
7943 case 94 /* caret */:
7944 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7945 return pos += 2, token = 71 /* CaretEqualsToken */;
7946 }
7947 pos++;
7948 return token = 51 /* CaretToken */;
7949 case 123 /* openBrace */:
7950 pos++;
7951 return token = 18 /* OpenBraceToken */;
7952 case 124 /* bar */:
7953 if (isConflictMarkerTrivia(text, pos)) {
7954 pos = scanConflictMarkerTrivia(text, pos, error);
7955 if (skipTrivia) {
7956 continue;
7957 }
7958 else {
7959 return token = 7 /* ConflictMarkerTrivia */;
7960 }
7961 }
7962 if (text.charCodeAt(pos + 1) === 124 /* bar */) {
7963 return pos += 2, token = 55 /* BarBarToken */;
7964 }
7965 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
7966 return pos += 2, token = 70 /* BarEqualsToken */;
7967 }
7968 pos++;
7969 return token = 50 /* BarToken */;
7970 case 125 /* closeBrace */:
7971 pos++;
7972 return token = 19 /* CloseBraceToken */;
7973 case 126 /* tilde */:
7974 pos++;
7975 return token = 53 /* TildeToken */;
7976 case 64 /* at */:
7977 pos++;
7978 return token = 58 /* AtToken */;
7979 case 92 /* backslash */:
7980 var cookedChar = peekUnicodeEscape();
7981 if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
7982 pos += 6;
7983 tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
7984 return token = getIdentifierToken();
7985 }
7986 error(ts.Diagnostics.Invalid_character);
7987 pos++;
7988 return token = 0 /* Unknown */;
7989 default:
7990 if (isIdentifierStart(ch, languageVersion)) {
7991 pos++;
7992 while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
7993 pos++;
7994 tokenValue = text.substring(tokenPos, pos);
7995 if (ch === 92 /* backslash */) {
7996 tokenValue += scanIdentifierParts();
7997 }
7998 return token = getIdentifierToken();
7999 }
8000 else if (isWhiteSpaceSingleLine(ch)) {
8001 pos++;
8002 continue;
8003 }
8004 else if (isLineBreak(ch)) {
8005 tokenFlags |= 1 /* PrecedingLineBreak */;
8006 pos++;
8007 continue;
8008 }
8009 error(ts.Diagnostics.Invalid_character);
8010 pos++;
8011 return token = 0 /* Unknown */;
8012 }
8013 }
8014 }
8015 function reScanGreaterToken() {
8016 if (token === 30 /* GreaterThanToken */) {
8017 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
8018 if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
8019 if (text.charCodeAt(pos + 2) === 61 /* equals */) {
8020 return pos += 3, token = 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
8021 }
8022 return pos += 2, token = 48 /* GreaterThanGreaterThanGreaterThanToken */;
8023 }
8024 if (text.charCodeAt(pos + 1) === 61 /* equals */) {
8025 return pos += 2, token = 67 /* GreaterThanGreaterThanEqualsToken */;
8026 }
8027 pos++;
8028 return token = 47 /* GreaterThanGreaterThanToken */;
8029 }
8030 if (text.charCodeAt(pos) === 61 /* equals */) {
8031 pos++;
8032 return token = 32 /* GreaterThanEqualsToken */;
8033 }
8034 }
8035 return token;
8036 }
8037 function reScanSlashToken() {
8038 if (token === 42 /* SlashToken */ || token === 64 /* SlashEqualsToken */) {
8039 var p = tokenPos + 1;
8040 var inEscape = false;
8041 var inCharacterClass = false;
8042 while (true) {
8043 // If we reach the end of a file, or hit a newline, then this is an unterminated
8044 // regex. Report error and return what we have so far.
8045 if (p >= end) {
8046 tokenFlags |= 4 /* Unterminated */;
8047 error(ts.Diagnostics.Unterminated_regular_expression_literal);
8048 break;
8049 }
8050 var ch = text.charCodeAt(p);
8051 if (isLineBreak(ch)) {
8052 tokenFlags |= 4 /* Unterminated */;
8053 error(ts.Diagnostics.Unterminated_regular_expression_literal);
8054 break;
8055 }
8056 if (inEscape) {
8057 // Parsing an escape character;
8058 // reset the flag and just advance to the next char.
8059 inEscape = false;
8060 }
8061 else if (ch === 47 /* slash */ && !inCharacterClass) {
8062 // A slash within a character class is permissible,
8063 // but in general it signals the end of the regexp literal.
8064 p++;
8065 break;
8066 }
8067 else if (ch === 91 /* openBracket */) {
8068 inCharacterClass = true;
8069 }
8070 else if (ch === 92 /* backslash */) {
8071 inEscape = true;
8072 }
8073 else if (ch === 93 /* closeBracket */) {
8074 inCharacterClass = false;
8075 }
8076 p++;
8077 }
8078 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
8079 p++;
8080 }
8081 pos = p;
8082 tokenValue = text.substring(tokenPos, pos);
8083 token = 13 /* RegularExpressionLiteral */;
8084 }
8085 return token;
8086 }
8087 /**
8088 * Unconditionally back up and scan a template expression portion.
8089 */
8090 function reScanTemplateToken() {
8091 ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
8092 pos = tokenPos;
8093 return token = scanTemplateAndSetTokenValue();
8094 }
8095 function reScanJsxToken() {
8096 pos = tokenPos = startPos;
8097 return token = scanJsxToken();
8098 }
8099 function reScanLessThanToken() {
8100 if (token === 46 /* LessThanLessThanToken */) {
8101 pos = tokenPos + 1;
8102 return token = 28 /* LessThanToken */;
8103 }
8104 return token;
8105 }
8106 function scanJsxToken() {
8107 startPos = tokenPos = pos;
8108 if (pos >= end) {
8109 return token = 1 /* EndOfFileToken */;
8110 }
8111 var char = text.charCodeAt(pos);
8112 if (char === 60 /* lessThan */) {
8113 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
8114 pos += 2;
8115 return token = 29 /* LessThanSlashToken */;
8116 }
8117 pos++;
8118 return token = 28 /* LessThanToken */;
8119 }
8120 if (char === 123 /* openBrace */) {
8121 pos++;
8122 return token = 18 /* OpenBraceToken */;
8123 }
8124 // First non-whitespace character on this line.
8125 var firstNonWhitespace = 0;
8126 // These initial values are special because the first line is:
8127 // firstNonWhitespace = 0 to indicate that we want leading whitspace,
8128 while (pos < end) {
8129 char = text.charCodeAt(pos);
8130 if (char === 123 /* openBrace */) {
8131 break;
8132 }
8133 if (char === 60 /* lessThan */) {
8134 if (isConflictMarkerTrivia(text, pos)) {
8135 pos = scanConflictMarkerTrivia(text, pos, error);
8136 return token = 7 /* ConflictMarkerTrivia */;
8137 }
8138 break;
8139 }
8140 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
8141 // i.e (- : whitespace)
8142 // <div>----
8143 // </div> becomes <div></div>
8144 //
8145 // <div>----</div> becomes <div>----</div>
8146 if (isLineBreak(char) && firstNonWhitespace === 0) {
8147 firstNonWhitespace = -1;
8148 }
8149 else if (!isWhiteSpaceLike(char)) {
8150 firstNonWhitespace = pos;
8151 }
8152 pos++;
8153 }
8154 tokenValue = text.substring(startPos, pos);
8155 return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
8156 }
8157 // Scans a JSX identifier; these differ from normal identifiers in that
8158 // they allow dashes
8159 function scanJsxIdentifier() {
8160 if (tokenIsIdentifierOrKeyword(token)) {
8161 var firstCharPosition = pos;
8162 while (pos < end) {
8163 var ch = text.charCodeAt(pos);
8164 if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) {
8165 pos++;
8166 }
8167 else {
8168 break;
8169 }
8170 }
8171 tokenValue += text.substring(firstCharPosition, pos);
8172 }
8173 return token;
8174 }
8175 function scanJsxAttributeValue() {
8176 startPos = pos;
8177 switch (text.charCodeAt(pos)) {
8178 case 34 /* doubleQuote */:
8179 case 39 /* singleQuote */:
8180 tokenValue = scanString(/*jsxAttributeString*/ true);
8181 return token = 10 /* StringLiteral */;
8182 default:
8183 // If this scans anything other than `{`, it's a parse error.
8184 return scan();
8185 }
8186 }
8187 function scanJSDocToken() {
8188 startPos = tokenPos = pos;
8189 tokenFlags = 0;
8190 if (pos >= end) {
8191 return token = 1 /* EndOfFileToken */;
8192 }
8193 var ch = text.charCodeAt(pos);
8194 pos++;
8195 switch (ch) {
8196 case 9 /* tab */:
8197 case 11 /* verticalTab */:
8198 case 12 /* formFeed */:
8199 case 32 /* space */:
8200 while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
8201 pos++;
8202 }
8203 return token = 5 /* WhitespaceTrivia */;
8204 case 64 /* at */:
8205 return token = 58 /* AtToken */;
8206 case 10 /* lineFeed */:
8207 case 13 /* carriageReturn */:
8208 tokenFlags |= 1 /* PrecedingLineBreak */;
8209 return token = 4 /* NewLineTrivia */;
8210 case 42 /* asterisk */:
8211 return token = 40 /* AsteriskToken */;
8212 case 123 /* openBrace */:
8213 return token = 18 /* OpenBraceToken */;
8214 case 125 /* closeBrace */:
8215 return token = 19 /* CloseBraceToken */;
8216 case 91 /* openBracket */:
8217 return token = 22 /* OpenBracketToken */;
8218 case 93 /* closeBracket */:
8219 return token = 23 /* CloseBracketToken */;
8220 case 60 /* lessThan */:
8221 return token = 28 /* LessThanToken */;
8222 case 61 /* equals */:
8223 return token = 59 /* EqualsToken */;
8224 case 44 /* comma */:
8225 return token = 27 /* CommaToken */;
8226 case 46 /* dot */:
8227 return token = 24 /* DotToken */;
8228 case 96 /* backtick */:
8229 while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) {
8230 pos++;
8231 }
8232 tokenValue = text.substring(tokenPos + 1, pos);
8233 pos++;
8234 return token = 14 /* NoSubstitutionTemplateLiteral */;
8235 }
8236 if (isIdentifierStart(ch, 7 /* Latest */)) {
8237 while (isIdentifierPart(text.charCodeAt(pos), 7 /* Latest */) && pos < end) {
8238 pos++;
8239 }
8240 tokenValue = text.substring(tokenPos, pos);
8241 return token = getIdentifierToken();
8242 }
8243 else {
8244 return token = 0 /* Unknown */;
8245 }
8246 }
8247 function speculationHelper(callback, isLookahead) {
8248 var savePos = pos;
8249 var saveStartPos = startPos;
8250 var saveTokenPos = tokenPos;
8251 var saveToken = token;
8252 var saveTokenValue = tokenValue;
8253 var saveTokenFlags = tokenFlags;
8254 var result = callback();
8255 // If our callback returned something 'falsy' or we're just looking ahead,
8256 // then unconditionally restore us to where we were.
8257 if (!result || isLookahead) {
8258 pos = savePos;
8259 startPos = saveStartPos;
8260 tokenPos = saveTokenPos;
8261 token = saveToken;
8262 tokenValue = saveTokenValue;
8263 tokenFlags = saveTokenFlags;
8264 }
8265 return result;
8266 }
8267 function scanRange(start, length, callback) {
8268 var saveEnd = end;
8269 var savePos = pos;
8270 var saveStartPos = startPos;
8271 var saveTokenPos = tokenPos;
8272 var saveToken = token;
8273 var saveTokenValue = tokenValue;
8274 var saveTokenFlags = tokenFlags;
8275 setText(text, start, length);
8276 var result = callback();
8277 end = saveEnd;
8278 pos = savePos;
8279 startPos = saveStartPos;
8280 tokenPos = saveTokenPos;
8281 token = saveToken;
8282 tokenValue = saveTokenValue;
8283 tokenFlags = saveTokenFlags;
8284 return result;
8285 }
8286 function lookAhead(callback) {
8287 return speculationHelper(callback, /*isLookahead*/ true);
8288 }
8289 function tryScan(callback) {
8290 return speculationHelper(callback, /*isLookahead*/ false);
8291 }
8292 function getText() {
8293 return text;
8294 }
8295 function setText(newText, start, length) {
8296 text = newText || "";
8297 end = length === undefined ? text.length : start + length;
8298 setTextPos(start || 0);
8299 }
8300 function setOnError(errorCallback) {
8301 onError = errorCallback;
8302 }
8303 function setScriptTarget(scriptTarget) {
8304 languageVersion = scriptTarget;
8305 }
8306 function setLanguageVariant(variant) {
8307 languageVariant = variant;
8308 }
8309 function setTextPos(textPos) {
8310 ts.Debug.assert(textPos >= 0);
8311 pos = textPos;
8312 startPos = textPos;
8313 tokenPos = textPos;
8314 token = 0 /* Unknown */;
8315 tokenValue = undefined;
8316 tokenFlags = 0;
8317 }
8318 function setInJSDocType(inType) {
8319 inJSDocType += inType ? 1 : -1;
8320 }
8321 }
8322 ts.createScanner = createScanner;
8323})(ts || (ts = {}));
8324var ts;
8325(function (ts) {
8326 function isExternalModuleNameRelative(moduleName) {
8327 // TypeScript 1.0 spec (April 2014): 11.2.1
8328 // An external module name is "relative" if the first term is "." or "..".
8329 // 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.
8330 return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
8331 }
8332 ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
8333 function sortAndDeduplicateDiagnostics(diagnostics) {
8334 return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
8335 }
8336 ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
8337})(ts || (ts = {}));
8338/* @internal */
8339(function (ts) {
8340 ts.resolvingEmptyArray = [];
8341 ts.emptyMap = ts.createMap();
8342 ts.emptyUnderscoreEscapedMap = ts.emptyMap;
8343 ts.externalHelpersModuleNameText = "tslib";
8344 ts.defaultMaximumTruncationLength = 160;
8345 function getDeclarationOfKind(symbol, kind) {
8346 var declarations = symbol.declarations;
8347 if (declarations) {
8348 for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
8349 var declaration = declarations_1[_i];
8350 if (declaration.kind === kind) {
8351 return declaration;
8352 }
8353 }
8354 }
8355 return undefined;
8356 }
8357 ts.getDeclarationOfKind = getDeclarationOfKind;
8358 /** Create a new escaped identifier map. */
8359 function createUnderscoreEscapedMap() {
8360 return new ts.MapCtr();
8361 }
8362 ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
8363 function hasEntries(map) {
8364 return !!map && !!map.size;
8365 }
8366 ts.hasEntries = hasEntries;
8367 function createSymbolTable(symbols) {
8368 var result = ts.createMap();
8369 if (symbols) {
8370 for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
8371 var symbol = symbols_1[_i];
8372 result.set(symbol.escapedName, symbol);
8373 }
8374 }
8375 return result;
8376 }
8377 ts.createSymbolTable = createSymbolTable;
8378 var stringWriter = createSingleLineStringWriter();
8379 function createSingleLineStringWriter() {
8380 var str = "";
8381 var writeText = function (text) { return str += text; };
8382 return {
8383 getText: function () { return str; },
8384 write: writeText,
8385 rawWrite: writeText,
8386 writeKeyword: writeText,
8387 writeOperator: writeText,
8388 writePunctuation: writeText,
8389 writeSpace: writeText,
8390 writeStringLiteral: writeText,
8391 writeLiteral: writeText,
8392 writeParameter: writeText,
8393 writeProperty: writeText,
8394 writeSymbol: function (s, _) { return writeText(s); },
8395 writeTrailingSemicolon: writeText,
8396 writeComment: writeText,
8397 getTextPos: function () { return str.length; },
8398 getLine: function () { return 0; },
8399 getColumn: function () { return 0; },
8400 getIndent: function () { return 0; },
8401 isAtStartOfLine: function () { return false; },
8402 // Completely ignore indentation for string writers. And map newlines to
8403 // a single space.
8404 writeLine: function () { return str += " "; },
8405 increaseIndent: ts.noop,
8406 decreaseIndent: ts.noop,
8407 clear: function () { return str = ""; },
8408 trackSymbol: ts.noop,
8409 reportInaccessibleThisError: ts.noop,
8410 reportInaccessibleUniqueSymbolError: ts.noop,
8411 reportPrivateInBaseOfClassExpression: ts.noop,
8412 };
8413 }
8414 function toPath(fileName, basePath, getCanonicalFileName) {
8415 var nonCanonicalizedPath = ts.isRootedDiskPath(fileName)
8416 ? ts.normalizePath(fileName)
8417 : ts.getNormalizedAbsolutePath(fileName, basePath);
8418 return getCanonicalFileName(nonCanonicalizedPath);
8419 }
8420 ts.toPath = toPath;
8421 function changesAffectModuleResolution(oldOptions, newOptions) {
8422 return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) {
8423 return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o));
8424 });
8425 }
8426 ts.changesAffectModuleResolution = changesAffectModuleResolution;
8427 function findAncestor(node, callback) {
8428 while (node) {
8429 var result = callback(node);
8430 if (result === "quit") {
8431 return undefined;
8432 }
8433 else if (result) {
8434 return node;
8435 }
8436 node = node.parent;
8437 }
8438 return undefined;
8439 }
8440 ts.findAncestor = findAncestor;
8441 function forEachAncestor(node, callback) {
8442 while (true) {
8443 var res = callback(node);
8444 if (res === "quit")
8445 return undefined;
8446 if (res !== undefined)
8447 return res;
8448 if (ts.isSourceFile(node))
8449 return undefined;
8450 node = node.parent;
8451 }
8452 }
8453 ts.forEachAncestor = forEachAncestor;
8454 function forEachEntry(map, callback) {
8455 var _a;
8456 var iterator = map.entries();
8457 for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) {
8458 var key = pair[0], value = pair[1];
8459 var result = callback(value, key);
8460 if (result) {
8461 return result;
8462 }
8463 }
8464 return undefined;
8465 }
8466 ts.forEachEntry = forEachEntry;
8467 function forEachKey(map, callback) {
8468 var _a;
8469 var iterator = map.keys();
8470 for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) {
8471 var result = callback(key);
8472 if (result) {
8473 return result;
8474 }
8475 }
8476 return undefined;
8477 }
8478 ts.forEachKey = forEachKey;
8479 function copyEntries(source, target) {
8480 source.forEach(function (value, key) {
8481 target.set(key, value);
8482 });
8483 }
8484 ts.copyEntries = copyEntries;
8485 function arrayToSet(array, makeKey) {
8486 return ts.arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; });
8487 }
8488 ts.arrayToSet = arrayToSet;
8489 function cloneMap(map) {
8490 var clone = ts.createMap();
8491 copyEntries(map, clone);
8492 return clone;
8493 }
8494 ts.cloneMap = cloneMap;
8495 function usingSingleLineStringWriter(action) {
8496 var oldString = stringWriter.getText();
8497 try {
8498 action(stringWriter);
8499 return stringWriter.getText();
8500 }
8501 finally {
8502 stringWriter.clear();
8503 stringWriter.writeKeyword(oldString);
8504 }
8505 }
8506 ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
8507 function getFullWidth(node) {
8508 return node.end - node.pos;
8509 }
8510 ts.getFullWidth = getFullWidth;
8511 function getResolvedModule(sourceFile, moduleNameText) {
8512 return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
8513 }
8514 ts.getResolvedModule = getResolvedModule;
8515 function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
8516 if (!sourceFile.resolvedModules) {
8517 sourceFile.resolvedModules = ts.createMap();
8518 }
8519 sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
8520 }
8521 ts.setResolvedModule = setResolvedModule;
8522 function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
8523 if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
8524 sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
8525 }
8526 sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
8527 }
8528 ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
8529 function projectReferenceIsEqualTo(oldRef, newRef) {
8530 return oldRef.path === newRef.path &&
8531 !oldRef.prepend === !newRef.prepend &&
8532 !oldRef.circular === !newRef.circular;
8533 }
8534 ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
8535 function moduleResolutionIsEqualTo(oldResolution, newResolution) {
8536 return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
8537 oldResolution.extension === newResolution.extension &&
8538 oldResolution.resolvedFileName === newResolution.resolvedFileName &&
8539 oldResolution.originalPath === newResolution.originalPath &&
8540 packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
8541 }
8542 ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
8543 function packageIdIsEqual(a, b) {
8544 return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
8545 }
8546 function packageIdToString(_a) {
8547 var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
8548 var fullName = subModuleName ? name + "/" + subModuleName : name;
8549 return fullName + "@" + version;
8550 }
8551 ts.packageIdToString = packageIdToString;
8552 function typeDirectiveIsEqualTo(oldResolution, newResolution) {
8553 return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
8554 }
8555 ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
8556 function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
8557 ts.Debug.assert(names.length === newResolutions.length);
8558 for (var i = 0; i < names.length; i++) {
8559 var newResolution = newResolutions[i];
8560 var oldResolution = oldResolutions && oldResolutions.get(names[i]);
8561 var changed = oldResolution
8562 ? !newResolution || !comparer(oldResolution, newResolution)
8563 : newResolution;
8564 if (changed) {
8565 return true;
8566 }
8567 }
8568 return false;
8569 }
8570 ts.hasChangesInResolutions = hasChangesInResolutions;
8571 // Returns true if this node contains a parse error anywhere underneath it.
8572 function containsParseError(node) {
8573 aggregateChildData(node);
8574 return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0;
8575 }
8576 ts.containsParseError = containsParseError;
8577 function aggregateChildData(node) {
8578 if (!(node.flags & 262144 /* HasAggregatedChildData */)) {
8579 // A node is considered to contain a parse error if:
8580 // a) the parser explicitly marked that it had an error
8581 // b) any of it's children reported that it had an error.
8582 var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) ||
8583 ts.forEachChild(node, containsParseError);
8584 // If so, mark ourselves accordingly.
8585 if (thisNodeOrAnySubNodesHasError) {
8586 node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */;
8587 }
8588 // Also mark that we've propagated the child information to this node. This way we can
8589 // always consult the bit directly on this node without needing to check its children
8590 // again.
8591 node.flags |= 262144 /* HasAggregatedChildData */;
8592 }
8593 }
8594 function getSourceFileOfNode(node) {
8595 while (node && node.kind !== 284 /* SourceFile */) {
8596 node = node.parent;
8597 }
8598 return node;
8599 }
8600 ts.getSourceFileOfNode = getSourceFileOfNode;
8601 function isStatementWithLocals(node) {
8602 switch (node.kind) {
8603 case 218 /* Block */:
8604 case 246 /* CaseBlock */:
8605 case 225 /* ForStatement */:
8606 case 226 /* ForInStatement */:
8607 case 227 /* ForOfStatement */:
8608 return true;
8609 }
8610 return false;
8611 }
8612 ts.isStatementWithLocals = isStatementWithLocals;
8613 function getStartPositionOfLine(line, sourceFile) {
8614 ts.Debug.assert(line >= 0);
8615 return ts.getLineStarts(sourceFile)[line];
8616 }
8617 ts.getStartPositionOfLine = getStartPositionOfLine;
8618 // This is a useful function for debugging purposes.
8619 function nodePosToString(node) {
8620 var file = getSourceFileOfNode(node);
8621 var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
8622 return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
8623 }
8624 ts.nodePosToString = nodePosToString;
8625 function getEndLinePosition(line, sourceFile) {
8626 ts.Debug.assert(line >= 0);
8627 var lineStarts = ts.getLineStarts(sourceFile);
8628 var lineIndex = line;
8629 var sourceText = sourceFile.text;
8630 if (lineIndex + 1 === lineStarts.length) {
8631 // last line - return EOF
8632 return sourceText.length - 1;
8633 }
8634 else {
8635 // current line start
8636 var start = lineStarts[lineIndex];
8637 // take the start position of the next line - 1 = it should be some line break
8638 var pos = lineStarts[lineIndex + 1] - 1;
8639 ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
8640 // walk backwards skipping line breaks, stop the the beginning of current line.
8641 // i.e:
8642 // <some text>
8643 // $ <- end of line for this position should match the start position
8644 while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
8645 pos--;
8646 }
8647 return pos;
8648 }
8649 }
8650 ts.getEndLinePosition = getEndLinePosition;
8651 /**
8652 * Returns a value indicating whether a name is unique globally or within the current file.
8653 * 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`.
8654 */
8655 function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
8656 return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
8657 }
8658 ts.isFileLevelUniqueName = isFileLevelUniqueName;
8659 // Returns true if this node is missing from the actual source code. A 'missing' node is different
8660 // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
8661 // in the tree), it is definitely missing. However, a node may be defined, but still be
8662 // missing. This happens whenever the parser knows it needs to parse something, but can't
8663 // get anything in the source code that it expects at that location. For example:
8664 //
8665 // let a: ;
8666 //
8667 // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
8668 // code). So the parser will attempt to parse out a type, and will create an actual node.
8669 // However, this node will be 'missing' in the sense that no actual source-code/tokens are
8670 // contained within it.
8671 function nodeIsMissing(node) {
8672 if (node === undefined) {
8673 return true;
8674 }
8675 return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
8676 }
8677 ts.nodeIsMissing = nodeIsMissing;
8678 function nodeIsPresent(node) {
8679 return !nodeIsMissing(node);
8680 }
8681 ts.nodeIsPresent = nodeIsPresent;
8682 function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
8683 if (from === undefined || from.length === 0)
8684 return to;
8685 var statementIndex = 0;
8686 // skip all prologue directives to insert at the correct position
8687 for (; statementIndex < to.length; ++statementIndex) {
8688 if (!isPrologueDirective(to[statementIndex])) {
8689 break;
8690 }
8691 }
8692 to.splice.apply(to, [statementIndex, 0].concat(from));
8693 return to;
8694 }
8695 function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
8696 if (statement === undefined)
8697 return to;
8698 var statementIndex = 0;
8699 // skip all prologue directives to insert at the correct position
8700 for (; statementIndex < to.length; ++statementIndex) {
8701 if (!isPrologueDirective(to[statementIndex])) {
8702 break;
8703 }
8704 }
8705 to.splice(statementIndex, 0, statement);
8706 return to;
8707 }
8708 function isAnyPrologueDirective(node) {
8709 return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
8710 }
8711 /**
8712 * Prepends statements to an array while taking care of prologue directives.
8713 */
8714 function insertStatementsAfterStandardPrologue(to, from) {
8715 return insertStatementsAfterPrologue(to, from, isPrologueDirective);
8716 }
8717 ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
8718 function insertStatementsAfterCustomPrologue(to, from) {
8719 return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
8720 }
8721 ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
8722 /**
8723 * Prepends statements to an array while taking care of prologue directives.
8724 */
8725 function insertStatementAfterStandardPrologue(to, statement) {
8726 return insertStatementAfterPrologue(to, statement, isPrologueDirective);
8727 }
8728 ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
8729 function insertStatementAfterCustomPrologue(to, statement) {
8730 return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
8731 }
8732 ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
8733 /**
8734 * Determine if the given comment is a triple-slash
8735 *
8736 * @return true if the comment is a triple-slash comment else false
8737 */
8738 function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
8739 // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
8740 // so that we don't end up computing comment string and doing match for all // comments
8741 if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
8742 commentPos + 2 < commentEnd &&
8743 text.charCodeAt(commentPos + 2) === 47 /* slash */) {
8744 var textSubStr = text.substring(commentPos, commentEnd);
8745 return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
8746 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
8747 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
8748 textSubStr.match(defaultLibReferenceRegEx) ?
8749 true : false;
8750 }
8751 return false;
8752 }
8753 ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
8754 function isPinnedComment(text, start) {
8755 return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
8756 text.charCodeAt(start + 2) === 33 /* exclamation */;
8757 }
8758 ts.isPinnedComment = isPinnedComment;
8759 function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
8760 // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
8761 // want to skip trivia because this will launch us forward to the next token.
8762 if (nodeIsMissing(node)) {
8763 return node.pos;
8764 }
8765 if (ts.isJSDocNode(node)) {
8766 return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
8767 }
8768 if (includeJsDoc && ts.hasJSDocNodes(node)) {
8769 return getTokenPosOfNode(node.jsDoc[0]);
8770 }
8771 // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
8772 // the syntax list itself considers them as normal trivia. Therefore if we simply skip
8773 // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
8774 // first child to determine the actual position of its first token.
8775 if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
8776 return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
8777 }
8778 return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
8779 }
8780 ts.getTokenPosOfNode = getTokenPosOfNode;
8781 function getNonDecoratorTokenPosOfNode(node, sourceFile) {
8782 if (nodeIsMissing(node) || !node.decorators) {
8783 return getTokenPosOfNode(node, sourceFile);
8784 }
8785 return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
8786 }
8787 ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
8788 function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
8789 if (includeTrivia === void 0) { includeTrivia = false; }
8790 return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
8791 }
8792 ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
8793 function isJSDocTypeExpressionOrChild(node) {
8794 return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
8795 }
8796 function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
8797 if (includeTrivia === void 0) { includeTrivia = false; }
8798 if (nodeIsMissing(node)) {
8799 return "";
8800 }
8801 var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
8802 if (isJSDocTypeExpressionOrChild(node)) {
8803 // strip space + asterisk at line start
8804 text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
8805 }
8806 return text;
8807 }
8808 ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
8809 function getTextOfNode(node, includeTrivia) {
8810 if (includeTrivia === void 0) { includeTrivia = false; }
8811 return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
8812 }
8813 ts.getTextOfNode = getTextOfNode;
8814 function getPos(range) {
8815 return range.pos;
8816 }
8817 /**
8818 * Note: it is expected that the `nodeArray` and the `node` are within the same file.
8819 * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
8820 */
8821 function indexOfNode(nodeArray, node) {
8822 return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
8823 }
8824 ts.indexOfNode = indexOfNode;
8825 /**
8826 * Gets flags that control emit behavior of a node.
8827 */
8828 function getEmitFlags(node) {
8829 var emitNode = node.emitNode;
8830 return emitNode && emitNode.flags || 0;
8831 }
8832 ts.getEmitFlags = getEmitFlags;
8833 function getLiteralText(node, sourceFile, neverAsciiEscape) {
8834 // If we don't need to downlevel and we can reach the original source text using
8835 // the node's parent reference, then simply get the text as it was originally written.
8836 if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
8837 ts.isBigIntLiteral(node))) {
8838 return getSourceTextOfNodeFromSourceFile(sourceFile, node);
8839 }
8840 var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString;
8841 // If we can't reach the original source text, use the canonical form if it's a number,
8842 // or a (possibly escaped) quoted form of the original text if it's string-like.
8843 switch (node.kind) {
8844 case 10 /* StringLiteral */:
8845 if (node.singleQuote) {
8846 return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
8847 }
8848 else {
8849 return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
8850 }
8851 case 14 /* NoSubstitutionTemplateLiteral */:
8852 return "`" + escapeText(node.text, 96 /* backtick */) + "`";
8853 case 15 /* TemplateHead */:
8854 // tslint:disable-next-line no-invalid-template-strings
8855 return "`" + escapeText(node.text, 96 /* backtick */) + "${";
8856 case 16 /* TemplateMiddle */:
8857 // tslint:disable-next-line no-invalid-template-strings
8858 return "}" + escapeText(node.text, 96 /* backtick */) + "${";
8859 case 17 /* TemplateTail */:
8860 return "}" + escapeText(node.text, 96 /* backtick */) + "`";
8861 case 8 /* NumericLiteral */:
8862 case 9 /* BigIntLiteral */:
8863 case 13 /* RegularExpressionLiteral */:
8864 return node.text;
8865 }
8866 return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
8867 }
8868 ts.getLiteralText = getLiteralText;
8869 function getTextOfConstantValue(value) {
8870 return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
8871 }
8872 ts.getTextOfConstantValue = getTextOfConstantValue;
8873 // Make an identifier from an external module name by extracting the string after the last "/" and replacing
8874 // all non-alphanumeric characters with underscores
8875 function makeIdentifierFromModuleName(moduleName) {
8876 return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
8877 }
8878 ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
8879 function isBlockOrCatchScoped(declaration) {
8880 return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
8881 isCatchClauseVariableDeclarationOrBindingElement(declaration);
8882 }
8883 ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
8884 function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
8885 var node = getRootDeclaration(declaration);
8886 return node.kind === 237 /* VariableDeclaration */ && node.parent.kind === 274 /* CatchClause */;
8887 }
8888 ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
8889 function isAmbientModule(node) {
8890 return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
8891 }
8892 ts.isAmbientModule = isAmbientModule;
8893 function isModuleWithStringLiteralName(node) {
8894 return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
8895 }
8896 ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
8897 function isNonGlobalAmbientModule(node) {
8898 return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
8899 }
8900 ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
8901 /**
8902 * An effective module (namespace) declaration is either
8903 * 1. An actual declaration: namespace X { ... }
8904 * 2. A Javascript declaration, which is:
8905 * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
8906 */
8907 function isEffectiveModuleDeclaration(node) {
8908 return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
8909 }
8910 ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
8911 /** Given a symbol for a module, checks that it is a shorthand ambient module. */
8912 function isShorthandAmbientModuleSymbol(moduleSymbol) {
8913 return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
8914 }
8915 ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
8916 function isShorthandAmbientModule(node) {
8917 // The only kind of module that can be missing a body is a shorthand ambient module.
8918 return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
8919 }
8920 function isBlockScopedContainerTopLevel(node) {
8921 return node.kind === 284 /* SourceFile */ ||
8922 node.kind === 244 /* ModuleDeclaration */ ||
8923 ts.isFunctionLike(node);
8924 }
8925 ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
8926 function isGlobalScopeAugmentation(module) {
8927 return !!(module.flags & 512 /* GlobalAugmentation */);
8928 }
8929 ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
8930 function isExternalModuleAugmentation(node) {
8931 return isAmbientModule(node) && isModuleAugmentationExternal(node);
8932 }
8933 ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
8934 function isModuleAugmentationExternal(node) {
8935 // external module augmentation is a ambient module declaration that is either:
8936 // - defined in the top level scope and source file is an external module
8937 // - defined inside ambient module declaration located in the top level scope and source file not an external module
8938 switch (node.parent.kind) {
8939 case 284 /* SourceFile */:
8940 return ts.isExternalModule(node.parent);
8941 case 245 /* ModuleBlock */:
8942 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
8943 }
8944 return false;
8945 }
8946 ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
8947 function getNonAugmentationDeclaration(symbol) {
8948 return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
8949 }
8950 ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
8951 function isEffectiveExternalModule(node, compilerOptions) {
8952 return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
8953 }
8954 ts.isEffectiveExternalModule = isEffectiveExternalModule;
8955 function isBlockScope(node, parentNode) {
8956 switch (node.kind) {
8957 case 284 /* SourceFile */:
8958 case 246 /* CaseBlock */:
8959 case 274 /* CatchClause */:
8960 case 244 /* ModuleDeclaration */:
8961 case 225 /* ForStatement */:
8962 case 226 /* ForInStatement */:
8963 case 227 /* ForOfStatement */:
8964 case 157 /* Constructor */:
8965 case 156 /* MethodDeclaration */:
8966 case 158 /* GetAccessor */:
8967 case 159 /* SetAccessor */:
8968 case 239 /* FunctionDeclaration */:
8969 case 196 /* FunctionExpression */:
8970 case 197 /* ArrowFunction */:
8971 return true;
8972 case 218 /* Block */:
8973 // function block is not considered block-scope container
8974 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
8975 return !ts.isFunctionLike(parentNode);
8976 }
8977 return false;
8978 }
8979 ts.isBlockScope = isBlockScope;
8980 function isDeclarationWithTypeParameters(node) {
8981 switch (node.kind) {
8982 case 302 /* JSDocCallbackTag */:
8983 case 309 /* JSDocTypedefTag */:
8984 case 298 /* JSDocSignature */:
8985 return true;
8986 default:
8987 ts.assertType(node);
8988 return isDeclarationWithTypeParameterChildren(node);
8989 }
8990 }
8991 ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
8992 function isDeclarationWithTypeParameterChildren(node) {
8993 switch (node.kind) {
8994 case 160 /* CallSignature */:
8995 case 161 /* ConstructSignature */:
8996 case 155 /* MethodSignature */:
8997 case 162 /* IndexSignature */:
8998 case 165 /* FunctionType */:
8999 case 166 /* ConstructorType */:
9000 case 294 /* JSDocFunctionType */:
9001 case 240 /* ClassDeclaration */:
9002 case 209 /* ClassExpression */:
9003 case 241 /* InterfaceDeclaration */:
9004 case 242 /* TypeAliasDeclaration */:
9005 case 308 /* JSDocTemplateTag */:
9006 case 239 /* FunctionDeclaration */:
9007 case 156 /* MethodDeclaration */:
9008 case 157 /* Constructor */:
9009 case 158 /* GetAccessor */:
9010 case 159 /* SetAccessor */:
9011 case 196 /* FunctionExpression */:
9012 case 197 /* ArrowFunction */:
9013 return true;
9014 default:
9015 ts.assertType(node);
9016 return false;
9017 }
9018 }
9019 ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
9020 function isAnyImportSyntax(node) {
9021 switch (node.kind) {
9022 case 249 /* ImportDeclaration */:
9023 case 248 /* ImportEqualsDeclaration */:
9024 return true;
9025 default:
9026 return false;
9027 }
9028 }
9029 ts.isAnyImportSyntax = isAnyImportSyntax;
9030 function isLateVisibilityPaintedStatement(node) {
9031 switch (node.kind) {
9032 case 249 /* ImportDeclaration */:
9033 case 248 /* ImportEqualsDeclaration */:
9034 case 219 /* VariableStatement */:
9035 case 240 /* ClassDeclaration */:
9036 case 239 /* FunctionDeclaration */:
9037 case 244 /* ModuleDeclaration */:
9038 case 242 /* TypeAliasDeclaration */:
9039 case 241 /* InterfaceDeclaration */:
9040 case 243 /* EnumDeclaration */:
9041 return true;
9042 default:
9043 return false;
9044 }
9045 }
9046 ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
9047 function isAnyImportOrReExport(node) {
9048 return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
9049 }
9050 ts.isAnyImportOrReExport = isAnyImportOrReExport;
9051 // Gets the nearest enclosing block scope container that has the provided node
9052 // as a descendant, that is not the provided node.
9053 function getEnclosingBlockScopeContainer(node) {
9054 return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
9055 }
9056 ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
9057 // Return display name of an identifier
9058 // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
9059 // text of the expression in the computed property.
9060 function declarationNameToString(name) {
9061 return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
9062 }
9063 ts.declarationNameToString = declarationNameToString;
9064 function getNameFromIndexInfo(info) {
9065 return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
9066 }
9067 ts.getNameFromIndexInfo = getNameFromIndexInfo;
9068 function getTextOfPropertyName(name) {
9069 switch (name.kind) {
9070 case 72 /* Identifier */:
9071 return name.escapedText;
9072 case 10 /* StringLiteral */:
9073 case 8 /* NumericLiteral */:
9074 case 14 /* NoSubstitutionTemplateLiteral */:
9075 return ts.escapeLeadingUnderscores(name.text);
9076 case 149 /* ComputedPropertyName */:
9077 if (isStringOrNumericLiteralLike(name.expression))
9078 return ts.escapeLeadingUnderscores(name.expression.text);
9079 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
9080 default:
9081 return ts.Debug.assertNever(name);
9082 }
9083 }
9084 ts.getTextOfPropertyName = getTextOfPropertyName;
9085 function entityNameToString(name) {
9086 switch (name.kind) {
9087 case 72 /* Identifier */:
9088 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
9089 case 148 /* QualifiedName */:
9090 return entityNameToString(name.left) + "." + entityNameToString(name.right);
9091 case 189 /* PropertyAccessExpression */:
9092 return entityNameToString(name.expression) + "." + entityNameToString(name.name);
9093 default:
9094 throw ts.Debug.assertNever(name);
9095 }
9096 }
9097 ts.entityNameToString = entityNameToString;
9098 function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
9099 var sourceFile = getSourceFileOfNode(node);
9100 return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
9101 }
9102 ts.createDiagnosticForNode = createDiagnosticForNode;
9103 function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
9104 var start = ts.skipTrivia(sourceFile.text, nodes.pos);
9105 return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
9106 }
9107 ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
9108 function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
9109 var span = getErrorSpanForNode(sourceFile, node);
9110 return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
9111 }
9112 ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
9113 function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
9114 var sourceFile = getSourceFileOfNode(node);
9115 var span = getErrorSpanForNode(sourceFile, node);
9116 return {
9117 file: sourceFile,
9118 start: span.start,
9119 length: span.length,
9120 code: messageChain.code,
9121 category: messageChain.category,
9122 messageText: messageChain.next ? messageChain : messageChain.messageText,
9123 relatedInformation: relatedInformation
9124 };
9125 }
9126 ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
9127 function getSpanOfTokenAtPosition(sourceFile, pos) {
9128 var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
9129 scanner.scan();
9130 var start = scanner.getTokenPos();
9131 return ts.createTextSpanFromBounds(start, scanner.getTextPos());
9132 }
9133 ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
9134 function getErrorSpanForArrowFunction(sourceFile, node) {
9135 var pos = ts.skipTrivia(sourceFile.text, node.pos);
9136 if (node.body && node.body.kind === 218 /* Block */) {
9137 var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
9138 var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
9139 if (startLine < endLine) {
9140 // The arrow function spans multiple lines,
9141 // make the error span be the first line, inclusive.
9142 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
9143 }
9144 }
9145 return ts.createTextSpanFromBounds(pos, node.end);
9146 }
9147 function getErrorSpanForNode(sourceFile, node) {
9148 var errorNode = node;
9149 switch (node.kind) {
9150 case 284 /* SourceFile */:
9151 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
9152 if (pos_1 === sourceFile.text.length) {
9153 // file is empty - return span for the beginning of the file
9154 return ts.createTextSpan(0, 0);
9155 }
9156 return getSpanOfTokenAtPosition(sourceFile, pos_1);
9157 // This list is a work in progress. Add missing node kinds to improve their error
9158 // spans.
9159 case 237 /* VariableDeclaration */:
9160 case 186 /* BindingElement */:
9161 case 240 /* ClassDeclaration */:
9162 case 209 /* ClassExpression */:
9163 case 241 /* InterfaceDeclaration */:
9164 case 244 /* ModuleDeclaration */:
9165 case 243 /* EnumDeclaration */:
9166 case 278 /* EnumMember */:
9167 case 239 /* FunctionDeclaration */:
9168 case 196 /* FunctionExpression */:
9169 case 156 /* MethodDeclaration */:
9170 case 158 /* GetAccessor */:
9171 case 159 /* SetAccessor */:
9172 case 242 /* TypeAliasDeclaration */:
9173 case 154 /* PropertyDeclaration */:
9174 case 153 /* PropertySignature */:
9175 errorNode = node.name;
9176 break;
9177 case 197 /* ArrowFunction */:
9178 return getErrorSpanForArrowFunction(sourceFile, node);
9179 }
9180 if (errorNode === undefined) {
9181 // If we don't have a better node, then just set the error on the first token of
9182 // construct.
9183 return getSpanOfTokenAtPosition(sourceFile, node.pos);
9184 }
9185 var isMissing = nodeIsMissing(errorNode);
9186 var pos = isMissing || ts.isJsxText(node)
9187 ? errorNode.pos
9188 : ts.skipTrivia(sourceFile.text, errorNode.pos);
9189 // These asserts should all be satisfied for a properly constructed `errorNode`.
9190 if (isMissing) {
9191 ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
9192 ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
9193 }
9194 else {
9195 ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
9196 ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
9197 }
9198 return ts.createTextSpanFromBounds(pos, errorNode.end);
9199 }
9200 ts.getErrorSpanForNode = getErrorSpanForNode;
9201 function isExternalOrCommonJsModule(file) {
9202 return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
9203 }
9204 ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
9205 function isJsonSourceFile(file) {
9206 return file.scriptKind === 6 /* JSON */;
9207 }
9208 ts.isJsonSourceFile = isJsonSourceFile;
9209 function isEnumConst(node) {
9210 return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
9211 }
9212 ts.isEnumConst = isEnumConst;
9213 function isDeclarationReadonly(declaration) {
9214 return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration));
9215 }
9216 ts.isDeclarationReadonly = isDeclarationReadonly;
9217 function isVarConst(node) {
9218 return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
9219 }
9220 ts.isVarConst = isVarConst;
9221 function isLet(node) {
9222 return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
9223 }
9224 ts.isLet = isLet;
9225 function isSuperCall(n) {
9226 return n.kind === 191 /* CallExpression */ && n.expression.kind === 98 /* SuperKeyword */;
9227 }
9228 ts.isSuperCall = isSuperCall;
9229 function isImportCall(n) {
9230 return n.kind === 191 /* CallExpression */ && n.expression.kind === 92 /* ImportKeyword */;
9231 }
9232 ts.isImportCall = isImportCall;
9233 function isLiteralImportTypeNode(n) {
9234 return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
9235 }
9236 ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
9237 function isPrologueDirective(node) {
9238 return node.kind === 221 /* ExpressionStatement */
9239 && node.expression.kind === 10 /* StringLiteral */;
9240 }
9241 ts.isPrologueDirective = isPrologueDirective;
9242 function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
9243 return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
9244 }
9245 ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
9246 function getJSDocCommentRanges(node, text) {
9247 var commentRanges = (node.kind === 151 /* Parameter */ ||
9248 node.kind === 150 /* TypeParameter */ ||
9249 node.kind === 196 /* FunctionExpression */ ||
9250 node.kind === 197 /* ArrowFunction */ ||
9251 node.kind === 195 /* ParenthesizedExpression */) ?
9252 ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
9253 ts.getLeadingCommentRanges(text, node.pos);
9254 // True if the comment starts with '/**' but not if it is '/**/'
9255 return ts.filter(commentRanges, function (comment) {
9256 return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
9257 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
9258 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
9259 });
9260 }
9261 ts.getJSDocCommentRanges = getJSDocCommentRanges;
9262 ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
9263 var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
9264 ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
9265 var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
9266 function isPartOfTypeNode(node) {
9267 if (163 /* FirstTypeNode */ <= node.kind && node.kind <= 183 /* LastTypeNode */) {
9268 return true;
9269 }
9270 switch (node.kind) {
9271 case 120 /* AnyKeyword */:
9272 case 143 /* UnknownKeyword */:
9273 case 135 /* NumberKeyword */:
9274 case 146 /* BigIntKeyword */:
9275 case 138 /* StringKeyword */:
9276 case 123 /* BooleanKeyword */:
9277 case 139 /* SymbolKeyword */:
9278 case 136 /* ObjectKeyword */:
9279 case 141 /* UndefinedKeyword */:
9280 case 132 /* NeverKeyword */:
9281 return true;
9282 case 106 /* VoidKeyword */:
9283 return node.parent.kind !== 200 /* VoidExpression */;
9284 case 211 /* ExpressionWithTypeArguments */:
9285 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
9286 case 150 /* TypeParameter */:
9287 return node.parent.kind === 181 /* MappedType */ || node.parent.kind === 176 /* InferType */;
9288 // Identifiers and qualified names may be type nodes, depending on their context. Climb
9289 // above them to find the lowest container
9290 case 72 /* Identifier */:
9291 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
9292 if (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) {
9293 node = node.parent;
9294 }
9295 else if (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node) {
9296 node = node.parent;
9297 }
9298 // At this point, node is either a qualified name or an identifier
9299 ts.Debug.assert(node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */ || node.kind === 189 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
9300 // falls through
9301 case 148 /* QualifiedName */:
9302 case 189 /* PropertyAccessExpression */:
9303 case 100 /* ThisKeyword */: {
9304 var parent = node.parent;
9305 if (parent.kind === 167 /* TypeQuery */) {
9306 return false;
9307 }
9308 if (parent.kind === 183 /* ImportType */) {
9309 return !parent.isTypeOf;
9310 }
9311 // Do not recursively call isPartOfTypeNode on the parent. In the example:
9312 //
9313 // let a: A.B.C;
9314 //
9315 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
9316 // Only C and A.B.C are type nodes.
9317 if (163 /* FirstTypeNode */ <= parent.kind && parent.kind <= 183 /* LastTypeNode */) {
9318 return true;
9319 }
9320 switch (parent.kind) {
9321 case 211 /* ExpressionWithTypeArguments */:
9322 return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
9323 case 150 /* TypeParameter */:
9324 return node === parent.constraint;
9325 case 308 /* JSDocTemplateTag */:
9326 return node === parent.constraint;
9327 case 154 /* PropertyDeclaration */:
9328 case 153 /* PropertySignature */:
9329 case 151 /* Parameter */:
9330 case 237 /* VariableDeclaration */:
9331 return node === parent.type;
9332 case 239 /* FunctionDeclaration */:
9333 case 196 /* FunctionExpression */:
9334 case 197 /* ArrowFunction */:
9335 case 157 /* Constructor */:
9336 case 156 /* MethodDeclaration */:
9337 case 155 /* MethodSignature */:
9338 case 158 /* GetAccessor */:
9339 case 159 /* SetAccessor */:
9340 return node === parent.type;
9341 case 160 /* CallSignature */:
9342 case 161 /* ConstructSignature */:
9343 case 162 /* IndexSignature */:
9344 return node === parent.type;
9345 case 194 /* TypeAssertionExpression */:
9346 return node === parent.type;
9347 case 191 /* CallExpression */:
9348 case 192 /* NewExpression */:
9349 return ts.contains(parent.typeArguments, node);
9350 case 193 /* TaggedTemplateExpression */:
9351 // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
9352 return false;
9353 }
9354 }
9355 }
9356 return false;
9357 }
9358 ts.isPartOfTypeNode = isPartOfTypeNode;
9359 function isChildOfNodeWithKind(node, kind) {
9360 while (node) {
9361 if (node.kind === kind) {
9362 return true;
9363 }
9364 node = node.parent;
9365 }
9366 return false;
9367 }
9368 ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
9369 // Warning: This has the same semantics as the forEach family of functions,
9370 // in that traversal terminates in the event that 'visitor' supplies a truthy value.
9371 function forEachReturnStatement(body, visitor) {
9372 return traverse(body);
9373 function traverse(node) {
9374 switch (node.kind) {
9375 case 230 /* ReturnStatement */:
9376 return visitor(node);
9377 case 246 /* CaseBlock */:
9378 case 218 /* Block */:
9379 case 222 /* IfStatement */:
9380 case 223 /* DoStatement */:
9381 case 224 /* WhileStatement */:
9382 case 225 /* ForStatement */:
9383 case 226 /* ForInStatement */:
9384 case 227 /* ForOfStatement */:
9385 case 231 /* WithStatement */:
9386 case 232 /* SwitchStatement */:
9387 case 271 /* CaseClause */:
9388 case 272 /* DefaultClause */:
9389 case 233 /* LabeledStatement */:
9390 case 235 /* TryStatement */:
9391 case 274 /* CatchClause */:
9392 return ts.forEachChild(node, traverse);
9393 }
9394 }
9395 }
9396 ts.forEachReturnStatement = forEachReturnStatement;
9397 function forEachYieldExpression(body, visitor) {
9398 return traverse(body);
9399 function traverse(node) {
9400 switch (node.kind) {
9401 case 207 /* YieldExpression */:
9402 visitor(node);
9403 var operand = node.expression;
9404 if (operand) {
9405 traverse(operand);
9406 }
9407 return;
9408 case 243 /* EnumDeclaration */:
9409 case 241 /* InterfaceDeclaration */:
9410 case 244 /* ModuleDeclaration */:
9411 case 242 /* TypeAliasDeclaration */:
9412 case 240 /* ClassDeclaration */:
9413 case 209 /* ClassExpression */:
9414 // These are not allowed inside a generator now, but eventually they may be allowed
9415 // as local types. Regardless, any yield statements contained within them should be
9416 // skipped in this traversal.
9417 return;
9418 default:
9419 if (ts.isFunctionLike(node)) {
9420 if (node.name && node.name.kind === 149 /* ComputedPropertyName */) {
9421 // Note that we will not include methods/accessors of a class because they would require
9422 // first descending into the class. This is by design.
9423 traverse(node.name.expression);
9424 return;
9425 }
9426 }
9427 else if (!isPartOfTypeNode(node)) {
9428 // This is the general case, which should include mostly expressions and statements.
9429 // Also includes NodeArrays.
9430 ts.forEachChild(node, traverse);
9431 }
9432 }
9433 }
9434 }
9435 ts.forEachYieldExpression = forEachYieldExpression;
9436 /**
9437 * Gets the most likely element type for a TypeNode. This is not an exhaustive test
9438 * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
9439 *
9440 * @param node The type node.
9441 */
9442 function getRestParameterElementType(node) {
9443 if (node && node.kind === 169 /* ArrayType */) {
9444 return node.elementType;
9445 }
9446 else if (node && node.kind === 164 /* TypeReference */) {
9447 return ts.singleOrUndefined(node.typeArguments);
9448 }
9449 else {
9450 return undefined;
9451 }
9452 }
9453 ts.getRestParameterElementType = getRestParameterElementType;
9454 function getMembersOfDeclaration(node) {
9455 switch (node.kind) {
9456 case 241 /* InterfaceDeclaration */:
9457 case 240 /* ClassDeclaration */:
9458 case 209 /* ClassExpression */:
9459 case 168 /* TypeLiteral */:
9460 return node.members;
9461 case 188 /* ObjectLiteralExpression */:
9462 return node.properties;
9463 }
9464 }
9465 ts.getMembersOfDeclaration = getMembersOfDeclaration;
9466 function isVariableLike(node) {
9467 if (node) {
9468 switch (node.kind) {
9469 case 186 /* BindingElement */:
9470 case 278 /* EnumMember */:
9471 case 151 /* Parameter */:
9472 case 275 /* PropertyAssignment */:
9473 case 154 /* PropertyDeclaration */:
9474 case 153 /* PropertySignature */:
9475 case 276 /* ShorthandPropertyAssignment */:
9476 case 237 /* VariableDeclaration */:
9477 return true;
9478 }
9479 }
9480 return false;
9481 }
9482 ts.isVariableLike = isVariableLike;
9483 function isVariableLikeOrAccessor(node) {
9484 return isVariableLike(node) || ts.isAccessor(node);
9485 }
9486 ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
9487 function isVariableDeclarationInVariableStatement(node) {
9488 return node.parent.kind === 238 /* VariableDeclarationList */
9489 && node.parent.parent.kind === 219 /* VariableStatement */;
9490 }
9491 ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
9492 function isValidESSymbolDeclaration(node) {
9493 return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
9494 ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) :
9495 ts.isPropertySignature(node) && hasReadonlyModifier(node);
9496 }
9497 ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
9498 function introducesArgumentsExoticObject(node) {
9499 switch (node.kind) {
9500 case 156 /* MethodDeclaration */:
9501 case 155 /* MethodSignature */:
9502 case 157 /* Constructor */:
9503 case 158 /* GetAccessor */:
9504 case 159 /* SetAccessor */:
9505 case 239 /* FunctionDeclaration */:
9506 case 196 /* FunctionExpression */:
9507 return true;
9508 }
9509 return false;
9510 }
9511 ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
9512 function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
9513 while (true) {
9514 if (beforeUnwrapLabelCallback) {
9515 beforeUnwrapLabelCallback(node);
9516 }
9517 if (node.statement.kind !== 233 /* LabeledStatement */) {
9518 return node.statement;
9519 }
9520 node = node.statement;
9521 }
9522 }
9523 ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
9524 function isFunctionBlock(node) {
9525 return node && node.kind === 218 /* Block */ && ts.isFunctionLike(node.parent);
9526 }
9527 ts.isFunctionBlock = isFunctionBlock;
9528 function isObjectLiteralMethod(node) {
9529 return node && node.kind === 156 /* MethodDeclaration */ && node.parent.kind === 188 /* ObjectLiteralExpression */;
9530 }
9531 ts.isObjectLiteralMethod = isObjectLiteralMethod;
9532 function isObjectLiteralOrClassExpressionMethod(node) {
9533 return node.kind === 156 /* MethodDeclaration */ &&
9534 (node.parent.kind === 188 /* ObjectLiteralExpression */ ||
9535 node.parent.kind === 209 /* ClassExpression */);
9536 }
9537 ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
9538 function isIdentifierTypePredicate(predicate) {
9539 return predicate && predicate.kind === 1 /* Identifier */;
9540 }
9541 ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
9542 function isThisTypePredicate(predicate) {
9543 return predicate && predicate.kind === 0 /* This */;
9544 }
9545 ts.isThisTypePredicate = isThisTypePredicate;
9546 function getPropertyAssignment(objectLiteral, key, key2) {
9547 return objectLiteral.properties.filter(function (property) {
9548 if (property.kind === 275 /* PropertyAssignment */) {
9549 var propName = getTextOfPropertyName(property.name);
9550 return key === propName || (!!key2 && key2 === propName);
9551 }
9552 return false;
9553 });
9554 }
9555 ts.getPropertyAssignment = getPropertyAssignment;
9556 function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
9557 if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
9558 var expression = tsConfigSourceFile.statements[0].expression;
9559 return ts.tryCast(expression, ts.isObjectLiteralExpression);
9560 }
9561 }
9562 ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
9563 function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
9564 return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
9565 return ts.isArrayLiteralExpression(property.initializer) ?
9566 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
9567 undefined;
9568 });
9569 }
9570 ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
9571 function getTsConfigPropArray(tsConfigSourceFile, propKey) {
9572 var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
9573 return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
9574 }
9575 ts.getTsConfigPropArray = getTsConfigPropArray;
9576 function getContainingFunction(node) {
9577 return findAncestor(node.parent, ts.isFunctionLike);
9578 }
9579 ts.getContainingFunction = getContainingFunction;
9580 function getContainingClass(node) {
9581 return findAncestor(node.parent, ts.isClassLike);
9582 }
9583 ts.getContainingClass = getContainingClass;
9584 function getThisContainer(node, includeArrowFunctions) {
9585 ts.Debug.assert(node.kind !== 284 /* SourceFile */);
9586 while (true) {
9587 node = node.parent;
9588 if (!node) {
9589 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
9590 }
9591 switch (node.kind) {
9592 case 149 /* ComputedPropertyName */:
9593 // If the grandparent node is an object literal (as opposed to a class),
9594 // then the computed property is not a 'this' container.
9595 // A computed property name in a class needs to be a this container
9596 // so that we can error on it.
9597 if (ts.isClassLike(node.parent.parent)) {
9598 return node;
9599 }
9600 // If this is a computed property, then the parent should not
9601 // make it a this container. The parent might be a property
9602 // in an object literal, like a method or accessor. But in order for
9603 // such a parent to be a this container, the reference must be in
9604 // the *body* of the container.
9605 node = node.parent;
9606 break;
9607 case 152 /* Decorator */:
9608 // Decorators are always applied outside of the body of a class or method.
9609 if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
9610 // If the decorator's parent is a Parameter, we resolve the this container from
9611 // the grandparent class declaration.
9612 node = node.parent.parent;
9613 }
9614 else if (ts.isClassElement(node.parent)) {
9615 // If the decorator's parent is a class element, we resolve the 'this' container
9616 // from the parent class declaration.
9617 node = node.parent;
9618 }
9619 break;
9620 case 197 /* ArrowFunction */:
9621 if (!includeArrowFunctions) {
9622 continue;
9623 }
9624 // falls through
9625 case 239 /* FunctionDeclaration */:
9626 case 196 /* FunctionExpression */:
9627 case 244 /* ModuleDeclaration */:
9628 case 154 /* PropertyDeclaration */:
9629 case 153 /* PropertySignature */:
9630 case 156 /* MethodDeclaration */:
9631 case 155 /* MethodSignature */:
9632 case 157 /* Constructor */:
9633 case 158 /* GetAccessor */:
9634 case 159 /* SetAccessor */:
9635 case 160 /* CallSignature */:
9636 case 161 /* ConstructSignature */:
9637 case 162 /* IndexSignature */:
9638 case 243 /* EnumDeclaration */:
9639 case 284 /* SourceFile */:
9640 return node;
9641 }
9642 }
9643 }
9644 ts.getThisContainer = getThisContainer;
9645 function getNewTargetContainer(node) {
9646 var container = getThisContainer(node, /*includeArrowFunctions*/ false);
9647 if (container) {
9648 switch (container.kind) {
9649 case 157 /* Constructor */:
9650 case 239 /* FunctionDeclaration */:
9651 case 196 /* FunctionExpression */:
9652 return container;
9653 }
9654 }
9655 return undefined;
9656 }
9657 ts.getNewTargetContainer = getNewTargetContainer;
9658 /**
9659 * Given an super call/property node, returns the closest node where
9660 * - a super call/property access is legal in the node and not legal in the parent node the node.
9661 * i.e. super call is legal in constructor but not legal in the class body.
9662 * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
9663 * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
9664 * i.e. super property access is illegal in function declaration but can be legal in the statement list
9665 */
9666 function getSuperContainer(node, stopOnFunctions) {
9667 while (true) {
9668 node = node.parent;
9669 if (!node) {
9670 return node;
9671 }
9672 switch (node.kind) {
9673 case 149 /* ComputedPropertyName */:
9674 node = node.parent;
9675 break;
9676 case 239 /* FunctionDeclaration */:
9677 case 196 /* FunctionExpression */:
9678 case 197 /* ArrowFunction */:
9679 if (!stopOnFunctions) {
9680 continue;
9681 }
9682 // falls through
9683 case 154 /* PropertyDeclaration */:
9684 case 153 /* PropertySignature */:
9685 case 156 /* MethodDeclaration */:
9686 case 155 /* MethodSignature */:
9687 case 157 /* Constructor */:
9688 case 158 /* GetAccessor */:
9689 case 159 /* SetAccessor */:
9690 return node;
9691 case 152 /* Decorator */:
9692 // Decorators are always applied outside of the body of a class or method.
9693 if (node.parent.kind === 151 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
9694 // If the decorator's parent is a Parameter, we resolve the this container from
9695 // the grandparent class declaration.
9696 node = node.parent.parent;
9697 }
9698 else if (ts.isClassElement(node.parent)) {
9699 // If the decorator's parent is a class element, we resolve the 'this' container
9700 // from the parent class declaration.
9701 node = node.parent;
9702 }
9703 break;
9704 }
9705 }
9706 }
9707 ts.getSuperContainer = getSuperContainer;
9708 function getImmediatelyInvokedFunctionExpression(func) {
9709 if (func.kind === 196 /* FunctionExpression */ || func.kind === 197 /* ArrowFunction */) {
9710 var prev = func;
9711 var parent = func.parent;
9712 while (parent.kind === 195 /* ParenthesizedExpression */) {
9713 prev = parent;
9714 parent = parent.parent;
9715 }
9716 if (parent.kind === 191 /* CallExpression */ && parent.expression === prev) {
9717 return parent;
9718 }
9719 }
9720 }
9721 ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
9722 function isSuperOrSuperProperty(node) {
9723 return node.kind === 98 /* SuperKeyword */
9724 || isSuperProperty(node);
9725 }
9726 ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
9727 /**
9728 * Determines whether a node is a property or element access expression for `super`.
9729 */
9730 function isSuperProperty(node) {
9731 var kind = node.kind;
9732 return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */)
9733 && node.expression.kind === 98 /* SuperKeyword */;
9734 }
9735 ts.isSuperProperty = isSuperProperty;
9736 /**
9737 * Determines whether a node is a property or element access expression for `this`.
9738 */
9739 function isThisProperty(node) {
9740 var kind = node.kind;
9741 return (kind === 189 /* PropertyAccessExpression */ || kind === 190 /* ElementAccessExpression */)
9742 && node.expression.kind === 100 /* ThisKeyword */;
9743 }
9744 ts.isThisProperty = isThisProperty;
9745 function getEntityNameFromTypeNode(node) {
9746 switch (node.kind) {
9747 case 164 /* TypeReference */:
9748 return node.typeName;
9749 case 211 /* ExpressionWithTypeArguments */:
9750 return isEntityNameExpression(node.expression)
9751 ? node.expression
9752 : undefined;
9753 case 72 /* Identifier */:
9754 case 148 /* QualifiedName */:
9755 return node;
9756 }
9757 return undefined;
9758 }
9759 ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
9760 function getInvokedExpression(node) {
9761 switch (node.kind) {
9762 case 193 /* TaggedTemplateExpression */:
9763 return node.tag;
9764 case 262 /* JsxOpeningElement */:
9765 case 261 /* JsxSelfClosingElement */:
9766 return node.tagName;
9767 default:
9768 return node.expression;
9769 }
9770 }
9771 ts.getInvokedExpression = getInvokedExpression;
9772 function nodeCanBeDecorated(node, parent, grandparent) {
9773 switch (node.kind) {
9774 case 240 /* ClassDeclaration */:
9775 // classes are valid targets
9776 return true;
9777 case 154 /* PropertyDeclaration */:
9778 // property declarations are valid if their parent is a class declaration.
9779 return parent.kind === 240 /* ClassDeclaration */;
9780 case 158 /* GetAccessor */:
9781 case 159 /* SetAccessor */:
9782 case 156 /* MethodDeclaration */:
9783 // if this method has a body and its parent is a class declaration, this is a valid target.
9784 return node.body !== undefined
9785 && parent.kind === 240 /* ClassDeclaration */;
9786 case 151 /* Parameter */:
9787 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
9788 return parent.body !== undefined
9789 && (parent.kind === 157 /* Constructor */
9790 || parent.kind === 156 /* MethodDeclaration */
9791 || parent.kind === 159 /* SetAccessor */)
9792 && grandparent.kind === 240 /* ClassDeclaration */;
9793 }
9794 return false;
9795 }
9796 ts.nodeCanBeDecorated = nodeCanBeDecorated;
9797 function nodeIsDecorated(node, parent, grandparent) {
9798 return node.decorators !== undefined
9799 && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
9800 }
9801 ts.nodeIsDecorated = nodeIsDecorated;
9802 function nodeOrChildIsDecorated(node, parent, grandparent) {
9803 return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
9804 }
9805 ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
9806 function childIsDecorated(node, parent) {
9807 switch (node.kind) {
9808 case 240 /* ClassDeclaration */:
9809 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
9810 case 156 /* MethodDeclaration */:
9811 case 159 /* SetAccessor */:
9812 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
9813 default:
9814 return false;
9815 }
9816 }
9817 ts.childIsDecorated = childIsDecorated;
9818 function isJSXTagName(node) {
9819 var parent = node.parent;
9820 if (parent.kind === 262 /* JsxOpeningElement */ ||
9821 parent.kind === 261 /* JsxSelfClosingElement */ ||
9822 parent.kind === 263 /* JsxClosingElement */) {
9823 return parent.tagName === node;
9824 }
9825 return false;
9826 }
9827 ts.isJSXTagName = isJSXTagName;
9828 function isExpressionNode(node) {
9829 switch (node.kind) {
9830 case 98 /* SuperKeyword */:
9831 case 96 /* NullKeyword */:
9832 case 102 /* TrueKeyword */:
9833 case 87 /* FalseKeyword */:
9834 case 13 /* RegularExpressionLiteral */:
9835 case 187 /* ArrayLiteralExpression */:
9836 case 188 /* ObjectLiteralExpression */:
9837 case 189 /* PropertyAccessExpression */:
9838 case 190 /* ElementAccessExpression */:
9839 case 191 /* CallExpression */:
9840 case 192 /* NewExpression */:
9841 case 193 /* TaggedTemplateExpression */:
9842 case 212 /* AsExpression */:
9843 case 194 /* TypeAssertionExpression */:
9844 case 213 /* NonNullExpression */:
9845 case 195 /* ParenthesizedExpression */:
9846 case 196 /* FunctionExpression */:
9847 case 209 /* ClassExpression */:
9848 case 197 /* ArrowFunction */:
9849 case 200 /* VoidExpression */:
9850 case 198 /* DeleteExpression */:
9851 case 199 /* TypeOfExpression */:
9852 case 202 /* PrefixUnaryExpression */:
9853 case 203 /* PostfixUnaryExpression */:
9854 case 204 /* BinaryExpression */:
9855 case 205 /* ConditionalExpression */:
9856 case 208 /* SpreadElement */:
9857 case 206 /* TemplateExpression */:
9858 case 14 /* NoSubstitutionTemplateLiteral */:
9859 case 210 /* OmittedExpression */:
9860 case 260 /* JsxElement */:
9861 case 261 /* JsxSelfClosingElement */:
9862 case 264 /* JsxFragment */:
9863 case 207 /* YieldExpression */:
9864 case 201 /* AwaitExpression */:
9865 case 214 /* MetaProperty */:
9866 return true;
9867 case 148 /* QualifiedName */:
9868 while (node.parent.kind === 148 /* QualifiedName */) {
9869 node = node.parent;
9870 }
9871 return node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node);
9872 case 72 /* Identifier */:
9873 if (node.parent.kind === 167 /* TypeQuery */ || isJSXTagName(node)) {
9874 return true;
9875 }
9876 // falls through
9877 case 8 /* NumericLiteral */:
9878 case 9 /* BigIntLiteral */:
9879 case 10 /* StringLiteral */:
9880 case 100 /* ThisKeyword */:
9881 return isInExpressionContext(node);
9882 default:
9883 return false;
9884 }
9885 }
9886 ts.isExpressionNode = isExpressionNode;
9887 function isInExpressionContext(node) {
9888 var parent = node.parent;
9889 switch (parent.kind) {
9890 case 237 /* VariableDeclaration */:
9891 case 151 /* Parameter */:
9892 case 154 /* PropertyDeclaration */:
9893 case 153 /* PropertySignature */:
9894 case 278 /* EnumMember */:
9895 case 275 /* PropertyAssignment */:
9896 case 186 /* BindingElement */:
9897 return parent.initializer === node;
9898 case 221 /* ExpressionStatement */:
9899 case 222 /* IfStatement */:
9900 case 223 /* DoStatement */:
9901 case 224 /* WhileStatement */:
9902 case 230 /* ReturnStatement */:
9903 case 231 /* WithStatement */:
9904 case 232 /* SwitchStatement */:
9905 case 271 /* CaseClause */:
9906 case 234 /* ThrowStatement */:
9907 return parent.expression === node;
9908 case 225 /* ForStatement */:
9909 var forStatement = parent;
9910 return (forStatement.initializer === node && forStatement.initializer.kind !== 238 /* VariableDeclarationList */) ||
9911 forStatement.condition === node ||
9912 forStatement.incrementor === node;
9913 case 226 /* ForInStatement */:
9914 case 227 /* ForOfStatement */:
9915 var forInStatement = parent;
9916 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 238 /* VariableDeclarationList */) ||
9917 forInStatement.expression === node;
9918 case 194 /* TypeAssertionExpression */:
9919 case 212 /* AsExpression */:
9920 return node === parent.expression;
9921 case 216 /* TemplateSpan */:
9922 return node === parent.expression;
9923 case 149 /* ComputedPropertyName */:
9924 return node === parent.expression;
9925 case 152 /* Decorator */:
9926 case 270 /* JsxExpression */:
9927 case 269 /* JsxSpreadAttribute */:
9928 case 277 /* SpreadAssignment */:
9929 return true;
9930 case 211 /* ExpressionWithTypeArguments */:
9931 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
9932 case 276 /* ShorthandPropertyAssignment */:
9933 return parent.objectAssignmentInitializer === node;
9934 default:
9935 return isExpressionNode(parent);
9936 }
9937 }
9938 ts.isInExpressionContext = isInExpressionContext;
9939 function isExternalModuleImportEqualsDeclaration(node) {
9940 return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */;
9941 }
9942 ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
9943 function getExternalModuleImportEqualsDeclarationExpression(node) {
9944 ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
9945 return node.moduleReference.expression;
9946 }
9947 ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
9948 function isInternalModuleImportEqualsDeclaration(node) {
9949 return node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 259 /* ExternalModuleReference */;
9950 }
9951 ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
9952 function isSourceFileJS(file) {
9953 return isInJSFile(file);
9954 }
9955 ts.isSourceFileJS = isSourceFileJS;
9956 function isSourceFileNotJS(file) {
9957 return !isInJSFile(file);
9958 }
9959 ts.isSourceFileNotJS = isSourceFileNotJS;
9960 function isInJSFile(node) {
9961 return !!node && !!(node.flags & 65536 /* JavaScriptFile */);
9962 }
9963 ts.isInJSFile = isInJSFile;
9964 function isInJsonFile(node) {
9965 return !!node && !!(node.flags & 16777216 /* JsonFile */);
9966 }
9967 ts.isInJsonFile = isInJsonFile;
9968 function isInJSDoc(node) {
9969 return !!node && !!(node.flags & 2097152 /* JSDoc */);
9970 }
9971 ts.isInJSDoc = isInJSDoc;
9972 function isJSDocIndexSignature(node) {
9973 return ts.isTypeReferenceNode(node) &&
9974 ts.isIdentifier(node.typeName) &&
9975 node.typeName.escapedText === "Object" &&
9976 node.typeArguments && node.typeArguments.length === 2 &&
9977 (node.typeArguments[0].kind === 138 /* StringKeyword */ || node.typeArguments[0].kind === 135 /* NumberKeyword */);
9978 }
9979 ts.isJSDocIndexSignature = isJSDocIndexSignature;
9980 function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) {
9981 if (callExpression.kind !== 191 /* CallExpression */) {
9982 return false;
9983 }
9984 var _a = callExpression, expression = _a.expression, args = _a.arguments;
9985 if (expression.kind !== 72 /* Identifier */ || expression.escapedText !== "require") {
9986 return false;
9987 }
9988 if (args.length !== 1) {
9989 return false;
9990 }
9991 var arg = args[0];
9992 return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg);
9993 }
9994 ts.isRequireCall = isRequireCall;
9995 function isSingleOrDoubleQuote(charCode) {
9996 return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
9997 }
9998 ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
9999 function isStringDoubleQuoted(str, sourceFile) {
10000 return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
10001 }
10002 ts.isStringDoubleQuoted = isStringDoubleQuoted;
10003 function getDeclarationOfExpando(node) {
10004 if (!node.parent) {
10005 return undefined;
10006 }
10007 var name;
10008 var decl;
10009 if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
10010 if (!isInJSFile(node) && !isVarConst(node.parent)) {
10011 return undefined;
10012 }
10013 name = node.parent.name;
10014 decl = node.parent;
10015 }
10016 else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.right === node) {
10017 name = node.parent.left;
10018 decl = name;
10019 }
10020 else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 55 /* BarBarToken */) {
10021 if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) {
10022 name = node.parent.parent.name;
10023 decl = node.parent.parent;
10024 }
10025 else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 59 /* EqualsToken */ && node.parent.parent.right === node.parent) {
10026 name = node.parent.parent.left;
10027 decl = name;
10028 }
10029 if (!name || !isEntityNameExpression(name) || !isSameEntityName(name, node.parent.left)) {
10030 return undefined;
10031 }
10032 }
10033 if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
10034 return undefined;
10035 }
10036 return decl;
10037 }
10038 ts.getDeclarationOfExpando = getDeclarationOfExpando;
10039 function isAssignmentDeclaration(decl) {
10040 return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
10041 }
10042 ts.isAssignmentDeclaration = isAssignmentDeclaration;
10043 /** Get the initializer, taking into account defaulted Javascript initializers */
10044 function getEffectiveInitializer(node) {
10045 if (isInJSFile(node) && node.initializer &&
10046 ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 55 /* BarBarToken */ &&
10047 node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
10048 return node.initializer.right;
10049 }
10050 return node.initializer;
10051 }
10052 ts.getEffectiveInitializer = getEffectiveInitializer;
10053 /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
10054 function getDeclaredExpandoInitializer(node) {
10055 var init = getEffectiveInitializer(node);
10056 return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
10057 }
10058 ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
10059 function hasExpandoValueProperty(node, isPrototypeAssignment) {
10060 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); });
10061 }
10062 /**
10063 * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
10064 * We treat the right hand side of assignments with container-like initalizers as declarations.
10065 */
10066 function getAssignedExpandoInitializer(node) {
10067 if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */) {
10068 var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
10069 return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
10070 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
10071 }
10072 if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
10073 var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
10074 if (result) {
10075 return result;
10076 }
10077 }
10078 }
10079 ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
10080 /**
10081 * Recognized expando initializers are:
10082 * 1. (function() {})() -- IIFEs
10083 * 2. function() { } -- Function expressions
10084 * 3. class { } -- Class expressions
10085 * 4. {} -- Empty object literals
10086 * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
10087 *
10088 * This function returns the provided initializer, or undefined if it is not valid.
10089 */
10090 function getExpandoInitializer(initializer, isPrototypeAssignment) {
10091 if (ts.isCallExpression(initializer)) {
10092 var e = skipParentheses(initializer.expression);
10093 return e.kind === 196 /* FunctionExpression */ || e.kind === 197 /* ArrowFunction */ ? initializer : undefined;
10094 }
10095 if (initializer.kind === 196 /* FunctionExpression */ ||
10096 initializer.kind === 209 /* ClassExpression */ ||
10097 initializer.kind === 197 /* ArrowFunction */) {
10098 return initializer;
10099 }
10100 if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
10101 return initializer;
10102 }
10103 }
10104 ts.getExpandoInitializer = getExpandoInitializer;
10105 /**
10106 * A defaulted expando initializer matches the pattern
10107 * `Lhs = Lhs || ExpandoInitializer`
10108 * or `var Lhs = Lhs || ExpandoInitializer`
10109 *
10110 * The second Lhs is required to be the same as the first except that it may be prefixed with
10111 * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
10112 */
10113 function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
10114 var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 55 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment);
10115 if (e && isSameEntityName(name, initializer.left)) {
10116 return e;
10117 }
10118 }
10119 function isDefaultedExpandoInitializer(node) {
10120 var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
10121 ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 59 /* EqualsToken */ ? node.parent.left :
10122 undefined;
10123 return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
10124 }
10125 ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
10126 /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
10127 function getNameOfExpando(node) {
10128 if (ts.isBinaryExpression(node.parent)) {
10129 var parent = (node.parent.operatorToken.kind === 55 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
10130 if (parent.operatorToken.kind === 59 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
10131 return parent.left;
10132 }
10133 }
10134 else if (ts.isVariableDeclaration(node.parent)) {
10135 return node.parent.name;
10136 }
10137 }
10138 ts.getNameOfExpando = getNameOfExpando;
10139 /**
10140 * Is the 'declared' name the same as the one in the initializer?
10141 * @return true for identical entity names, as well as ones where the initializer is prefixed with
10142 * 'window', 'self' or 'global'. For example:
10143 *
10144 * var my = my || {}
10145 * var min = window.min || {}
10146 * my.app = self.my.app || class { }
10147 */
10148 function isSameEntityName(name, initializer) {
10149 if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) {
10150 return name.escapedText === initializer.escapedText;
10151 }
10152 if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) {
10153 return (initializer.expression.kind === 100 /* ThisKeyword */ ||
10154 ts.isIdentifier(initializer.expression) &&
10155 (initializer.expression.escapedText === "window" ||
10156 initializer.expression.escapedText === "self" ||
10157 initializer.expression.escapedText === "global")) &&
10158 isSameEntityName(name, initializer.name);
10159 }
10160 if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) {
10161 return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression);
10162 }
10163 return false;
10164 }
10165 function getRightMostAssignedExpression(node) {
10166 while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
10167 node = node.right;
10168 }
10169 return node;
10170 }
10171 ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
10172 function isExportsIdentifier(node) {
10173 return ts.isIdentifier(node) && node.escapedText === "exports";
10174 }
10175 ts.isExportsIdentifier = isExportsIdentifier;
10176 function isModuleExportsPropertyAccessExpression(node) {
10177 return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports";
10178 }
10179 ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression;
10180 /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
10181 /// assignments we treat as special in the binder
10182 function getAssignmentDeclarationKind(expr) {
10183 var special = getAssignmentDeclarationKindWorker(expr);
10184 return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
10185 }
10186 ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
10187 function isBindableObjectDefinePropertyCall(expr) {
10188 return ts.length(expr.arguments) === 3 &&
10189 ts.isPropertyAccessExpression(expr.expression) &&
10190 ts.isIdentifier(expr.expression.expression) &&
10191 ts.idText(expr.expression.expression) === "Object" &&
10192 ts.idText(expr.expression.name) === "defineProperty" &&
10193 isStringOrNumericLiteralLike(expr.arguments[1]) &&
10194 isEntityNameExpression(expr.arguments[0]);
10195 }
10196 ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
10197 function getAssignmentDeclarationKindWorker(expr) {
10198 if (ts.isCallExpression(expr)) {
10199 if (!isBindableObjectDefinePropertyCall(expr)) {
10200 return 0 /* None */;
10201 }
10202 var entityName = expr.arguments[0];
10203 if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) {
10204 return 8 /* ObjectDefinePropertyExports */;
10205 }
10206 if (ts.isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) {
10207 return 9 /* ObjectDefinePrototypeProperty */;
10208 }
10209 return 7 /* ObjectDefinePropertyValue */;
10210 }
10211 if (expr.operatorToken.kind !== 59 /* EqualsToken */ ||
10212 !ts.isPropertyAccessExpression(expr.left)) {
10213 return 0 /* None */;
10214 }
10215 var lhs = expr.left;
10216 if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
10217 // F.prototype = { ... }
10218 return 6 /* Prototype */;
10219 }
10220 return getAssignmentDeclarationPropertyAccessKind(lhs);
10221 }
10222 function getAssignmentDeclarationPropertyAccessKind(lhs) {
10223 if (lhs.expression.kind === 100 /* ThisKeyword */) {
10224 return 4 /* ThisProperty */;
10225 }
10226 else if (isModuleExportsPropertyAccessExpression(lhs)) {
10227 // module.exports = expr
10228 return 2 /* ModuleExports */;
10229 }
10230 else if (isEntityNameExpression(lhs.expression)) {
10231 if (isPrototypeAccess(lhs.expression)) {
10232 // F.G....prototype.x = expr
10233 return 3 /* PrototypeProperty */;
10234 }
10235 var nextToLast = lhs;
10236 while (ts.isPropertyAccessExpression(nextToLast.expression)) {
10237 nextToLast = nextToLast.expression;
10238 }
10239 ts.Debug.assert(ts.isIdentifier(nextToLast.expression));
10240 var id = nextToLast.expression;
10241 if (id.escapedText === "exports" ||
10242 id.escapedText === "module" && nextToLast.name.escapedText === "exports") {
10243 // exports.name = expr OR module.exports.name = expr
10244 return 1 /* ExportsProperty */;
10245 }
10246 // F.G...x = expr
10247 return 5 /* Property */;
10248 }
10249 return 0 /* None */;
10250 }
10251 ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
10252 function getInitializerOfBinaryExpression(expr) {
10253 while (ts.isBinaryExpression(expr.right)) {
10254 expr = expr.right;
10255 }
10256 return expr.right;
10257 }
10258 ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
10259 function isPrototypePropertyAssignment(node) {
10260 return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
10261 }
10262 ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
10263 function isSpecialPropertyDeclaration(expr) {
10264 return isInJSFile(expr) &&
10265 expr.parent && expr.parent.kind === 221 /* ExpressionStatement */ &&
10266 !!ts.getJSDocTypeTag(expr.parent);
10267 }
10268 ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
10269 function isFunctionSymbol(symbol) {
10270 if (!symbol || !symbol.valueDeclaration) {
10271 return false;
10272 }
10273 var decl = symbol.valueDeclaration;
10274 return decl.kind === 239 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
10275 }
10276 ts.isFunctionSymbol = isFunctionSymbol;
10277 function importFromModuleSpecifier(node) {
10278 return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent));
10279 }
10280 ts.importFromModuleSpecifier = importFromModuleSpecifier;
10281 function tryGetImportFromModuleSpecifier(node) {
10282 switch (node.parent.kind) {
10283 case 249 /* ImportDeclaration */:
10284 case 255 /* ExportDeclaration */:
10285 return node.parent;
10286 case 259 /* ExternalModuleReference */:
10287 return node.parent.parent;
10288 case 191 /* CallExpression */:
10289 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
10290 case 182 /* LiteralType */:
10291 ts.Debug.assert(ts.isStringLiteral(node));
10292 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
10293 default:
10294 return undefined;
10295 }
10296 }
10297 ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
10298 function getExternalModuleName(node) {
10299 switch (node.kind) {
10300 case 249 /* ImportDeclaration */:
10301 case 255 /* ExportDeclaration */:
10302 return node.moduleSpecifier;
10303 case 248 /* ImportEqualsDeclaration */:
10304 return node.moduleReference.kind === 259 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
10305 case 183 /* ImportType */:
10306 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
10307 default:
10308 return ts.Debug.assertNever(node);
10309 }
10310 }
10311 ts.getExternalModuleName = getExternalModuleName;
10312 function getNamespaceDeclarationNode(node) {
10313 switch (node.kind) {
10314 case 249 /* ImportDeclaration */:
10315 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
10316 case 248 /* ImportEqualsDeclaration */:
10317 return node;
10318 case 255 /* ExportDeclaration */:
10319 return undefined;
10320 default:
10321 return ts.Debug.assertNever(node);
10322 }
10323 }
10324 ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
10325 function isDefaultImport(node) {
10326 return node.kind === 249 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
10327 }
10328 ts.isDefaultImport = isDefaultImport;
10329 function hasQuestionToken(node) {
10330 if (node) {
10331 switch (node.kind) {
10332 case 151 /* Parameter */:
10333 case 156 /* MethodDeclaration */:
10334 case 155 /* MethodSignature */:
10335 case 276 /* ShorthandPropertyAssignment */:
10336 case 275 /* PropertyAssignment */:
10337 case 154 /* PropertyDeclaration */:
10338 case 153 /* PropertySignature */:
10339 return node.questionToken !== undefined;
10340 }
10341 }
10342 return false;
10343 }
10344 ts.hasQuestionToken = hasQuestionToken;
10345 function isJSDocConstructSignature(node) {
10346 var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
10347 var name = ts.tryCast(param && param.name, ts.isIdentifier);
10348 return !!name && name.escapedText === "new";
10349 }
10350 ts.isJSDocConstructSignature = isJSDocConstructSignature;
10351 function isJSDocTypeAlias(node) {
10352 return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
10353 }
10354 ts.isJSDocTypeAlias = isJSDocTypeAlias;
10355 function isTypeAlias(node) {
10356 return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
10357 }
10358 ts.isTypeAlias = isTypeAlias;
10359 function getSourceOfAssignment(node) {
10360 return ts.isExpressionStatement(node) &&
10361 node.expression && ts.isBinaryExpression(node.expression) &&
10362 node.expression.operatorToken.kind === 59 /* EqualsToken */
10363 ? node.expression.right
10364 : undefined;
10365 }
10366 function getSourceOfDefaultedAssignment(node) {
10367 return ts.isExpressionStatement(node) &&
10368 ts.isBinaryExpression(node.expression) &&
10369 getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
10370 ts.isBinaryExpression(node.expression.right) &&
10371 node.expression.right.operatorToken.kind === 55 /* BarBarToken */
10372 ? node.expression.right.right
10373 : undefined;
10374 }
10375 function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
10376 switch (node.kind) {
10377 case 219 /* VariableStatement */:
10378 var v = getSingleVariableOfVariableStatement(node);
10379 return v && v.initializer;
10380 case 154 /* PropertyDeclaration */:
10381 return node.initializer;
10382 case 275 /* PropertyAssignment */:
10383 return node.initializer;
10384 }
10385 }
10386 ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
10387 function getSingleVariableOfVariableStatement(node) {
10388 return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
10389 }
10390 function getNestedModuleDeclaration(node) {
10391 return ts.isModuleDeclaration(node) &&
10392 node.body &&
10393 node.body.kind === 244 /* ModuleDeclaration */
10394 ? node.body
10395 : undefined;
10396 }
10397 function getJSDocCommentsAndTags(hostNode) {
10398 var result;
10399 // Pull parameter comments from declaring function as well
10400 if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
10401 result = ts.addRange(result, hostNode.initializer.jsDoc);
10402 }
10403 var node = hostNode;
10404 while (node && node.parent) {
10405 if (ts.hasJSDocNodes(node)) {
10406 result = ts.addRange(result, node.jsDoc);
10407 }
10408 if (node.kind === 151 /* Parameter */) {
10409 result = ts.addRange(result, ts.getJSDocParameterTags(node));
10410 break;
10411 }
10412 if (node.kind === 150 /* TypeParameter */) {
10413 result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
10414 break;
10415 }
10416 node = getNextJSDocCommentLocation(node);
10417 }
10418 return result || ts.emptyArray;
10419 }
10420 ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
10421 function getNextJSDocCommentLocation(node) {
10422 var parent = node.parent;
10423 if (parent.kind === 275 /* PropertyAssignment */ ||
10424 parent.kind === 154 /* PropertyDeclaration */ ||
10425 parent.kind === 221 /* ExpressionStatement */ && node.kind === 189 /* PropertyAccessExpression */ ||
10426 getNestedModuleDeclaration(parent) ||
10427 ts.isBinaryExpression(node) && node.operatorToken.kind === 59 /* EqualsToken */) {
10428 return parent;
10429 }
10430 // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
10431 // /**
10432 // * @param {number} name
10433 // * @returns {number}
10434 // */
10435 // var x = function(name) { return name.length; }
10436 else if (parent.parent &&
10437 (getSingleVariableOfVariableStatement(parent.parent) === node ||
10438 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 59 /* EqualsToken */)) {
10439 return parent.parent;
10440 }
10441 else if (parent.parent && parent.parent.parent &&
10442 (getSingleVariableOfVariableStatement(parent.parent.parent) ||
10443 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
10444 getSourceOfDefaultedAssignment(parent.parent.parent))) {
10445 return parent.parent.parent;
10446 }
10447 }
10448 /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
10449 function getParameterSymbolFromJSDoc(node) {
10450 if (node.symbol) {
10451 return node.symbol;
10452 }
10453 if (!ts.isIdentifier(node.name)) {
10454 return undefined;
10455 }
10456 var name = node.name.escapedText;
10457 var decl = getHostSignatureFromJSDoc(node);
10458 if (!decl) {
10459 return undefined;
10460 }
10461 var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 72 /* Identifier */ && p.name.escapedText === name; });
10462 return parameter && parameter.symbol;
10463 }
10464 ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
10465 function getHostSignatureFromJSDoc(node) {
10466 return getHostSignatureFromJSDocHost(getJSDocHost(node));
10467 }
10468 ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
10469 function getHostSignatureFromJSDocHost(host) {
10470 var decl = getSourceOfDefaultedAssignment(host) ||
10471 getSourceOfAssignment(host) ||
10472 getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
10473 getSingleVariableOfVariableStatement(host) ||
10474 getNestedModuleDeclaration(host) ||
10475 host;
10476 return decl && ts.isFunctionLike(decl) ? decl : undefined;
10477 }
10478 ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
10479 function getJSDocHost(node) {
10480 return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
10481 }
10482 ts.getJSDocHost = getJSDocHost;
10483 function getTypeParameterFromJsDoc(node) {
10484 var name = node.name.escapedText;
10485 var typeParameters = node.parent.parent.parent.typeParameters;
10486 return ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
10487 }
10488 ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
10489 function hasRestParameter(s) {
10490 var last = ts.lastOrUndefined(s.parameters);
10491 return !!last && isRestParameter(last);
10492 }
10493 ts.hasRestParameter = hasRestParameter;
10494 function isRestParameter(node) {
10495 var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
10496 return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
10497 }
10498 ts.isRestParameter = isRestParameter;
10499 var AssignmentKind;
10500 (function (AssignmentKind) {
10501 AssignmentKind[AssignmentKind["None"] = 0] = "None";
10502 AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
10503 AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
10504 })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
10505 function getAssignmentTargetKind(node) {
10506 var parent = node.parent;
10507 while (true) {
10508 switch (parent.kind) {
10509 case 204 /* BinaryExpression */:
10510 var binaryOperator = parent.operatorToken.kind;
10511 return isAssignmentOperator(binaryOperator) && parent.left === node ?
10512 binaryOperator === 59 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
10513 0 /* None */;
10514 case 202 /* PrefixUnaryExpression */:
10515 case 203 /* PostfixUnaryExpression */:
10516 var unaryOperator = parent.operator;
10517 return unaryOperator === 44 /* PlusPlusToken */ || unaryOperator === 45 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
10518 case 226 /* ForInStatement */:
10519 case 227 /* ForOfStatement */:
10520 return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
10521 case 195 /* ParenthesizedExpression */:
10522 case 187 /* ArrayLiteralExpression */:
10523 case 208 /* SpreadElement */:
10524 case 213 /* NonNullExpression */:
10525 node = parent;
10526 break;
10527 case 276 /* ShorthandPropertyAssignment */:
10528 if (parent.name !== node) {
10529 return 0 /* None */;
10530 }
10531 node = parent.parent;
10532 break;
10533 case 275 /* PropertyAssignment */:
10534 if (parent.name === node) {
10535 return 0 /* None */;
10536 }
10537 node = parent.parent;
10538 break;
10539 default:
10540 return 0 /* None */;
10541 }
10542 parent = node.parent;
10543 }
10544 }
10545 ts.getAssignmentTargetKind = getAssignmentTargetKind;
10546 // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
10547 // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
10548 // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
10549 // (Note that `p` is not a target in the above examples, only `a`.)
10550 function isAssignmentTarget(node) {
10551 return getAssignmentTargetKind(node) !== 0 /* None */;
10552 }
10553 ts.isAssignmentTarget = isAssignmentTarget;
10554 /**
10555 * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
10556 * the same `var` declaration scope as the node's parent.
10557 */
10558 function isNodeWithPossibleHoistedDeclaration(node) {
10559 switch (node.kind) {
10560 case 218 /* Block */:
10561 case 219 /* VariableStatement */:
10562 case 231 /* WithStatement */:
10563 case 222 /* IfStatement */:
10564 case 232 /* SwitchStatement */:
10565 case 246 /* CaseBlock */:
10566 case 271 /* CaseClause */:
10567 case 272 /* DefaultClause */:
10568 case 233 /* LabeledStatement */:
10569 case 225 /* ForStatement */:
10570 case 226 /* ForInStatement */:
10571 case 227 /* ForOfStatement */:
10572 case 223 /* DoStatement */:
10573 case 224 /* WhileStatement */:
10574 case 235 /* TryStatement */:
10575 case 274 /* CatchClause */:
10576 return true;
10577 }
10578 return false;
10579 }
10580 ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
10581 function isValueSignatureDeclaration(node) {
10582 return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
10583 }
10584 ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
10585 function walkUp(node, kind) {
10586 while (node && node.kind === kind) {
10587 node = node.parent;
10588 }
10589 return node;
10590 }
10591 function walkUpParenthesizedTypes(node) {
10592 return walkUp(node, 177 /* ParenthesizedType */);
10593 }
10594 ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
10595 function walkUpParenthesizedExpressions(node) {
10596 return walkUp(node, 195 /* ParenthesizedExpression */);
10597 }
10598 ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
10599 function skipParentheses(node) {
10600 while (node.kind === 195 /* ParenthesizedExpression */) {
10601 node = node.expression;
10602 }
10603 return node;
10604 }
10605 ts.skipParentheses = skipParentheses;
10606 function skipParenthesesUp(node) {
10607 while (node.kind === 195 /* ParenthesizedExpression */) {
10608 node = node.parent;
10609 }
10610 return node;
10611 }
10612 // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
10613 function isDeleteTarget(node) {
10614 if (node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) {
10615 return false;
10616 }
10617 node = walkUpParenthesizedExpressions(node.parent);
10618 return node && node.kind === 198 /* DeleteExpression */;
10619 }
10620 ts.isDeleteTarget = isDeleteTarget;
10621 function isNodeDescendantOf(node, ancestor) {
10622 while (node) {
10623 if (node === ancestor)
10624 return true;
10625 node = node.parent;
10626 }
10627 return false;
10628 }
10629 ts.isNodeDescendantOf = isNodeDescendantOf;
10630 // True if `name` is the name of a declaration node
10631 function isDeclarationName(name) {
10632 return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
10633 }
10634 ts.isDeclarationName = isDeclarationName;
10635 // See GH#16030
10636 function getDeclarationFromName(name) {
10637 var parent = name.parent;
10638 switch (name.kind) {
10639 case 10 /* StringLiteral */:
10640 case 8 /* NumericLiteral */:
10641 if (ts.isComputedPropertyName(parent))
10642 return parent.parent;
10643 // falls through
10644 case 72 /* Identifier */:
10645 if (ts.isDeclaration(parent)) {
10646 return parent.name === name ? parent : undefined;
10647 }
10648 else if (ts.isQualifiedName(parent)) {
10649 var tag = parent.parent;
10650 return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
10651 }
10652 else {
10653 var binExp = parent.parent;
10654 return ts.isBinaryExpression(binExp) &&
10655 getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
10656 (binExp.left.symbol || binExp.symbol) &&
10657 ts.getNameOfDeclaration(binExp) === name
10658 ? binExp
10659 : undefined;
10660 }
10661 default:
10662 return undefined;
10663 }
10664 }
10665 ts.getDeclarationFromName = getDeclarationFromName;
10666 function isLiteralComputedPropertyDeclarationName(node) {
10667 return (node.kind === 10 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) &&
10668 node.parent.kind === 149 /* ComputedPropertyName */ &&
10669 ts.isDeclaration(node.parent.parent);
10670 }
10671 ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
10672 // Return true if the given identifier is classified as an IdentifierName
10673 function isIdentifierName(node) {
10674 var parent = node.parent;
10675 switch (parent.kind) {
10676 case 154 /* PropertyDeclaration */:
10677 case 153 /* PropertySignature */:
10678 case 156 /* MethodDeclaration */:
10679 case 155 /* MethodSignature */:
10680 case 158 /* GetAccessor */:
10681 case 159 /* SetAccessor */:
10682 case 278 /* EnumMember */:
10683 case 275 /* PropertyAssignment */:
10684 case 189 /* PropertyAccessExpression */:
10685 // Name in member declaration or property name in property access
10686 return parent.name === node;
10687 case 148 /* QualifiedName */:
10688 // Name on right hand side of dot in a type query or type reference
10689 if (parent.right === node) {
10690 while (parent.kind === 148 /* QualifiedName */) {
10691 parent = parent.parent;
10692 }
10693 return parent.kind === 167 /* TypeQuery */ || parent.kind === 164 /* TypeReference */;
10694 }
10695 return false;
10696 case 186 /* BindingElement */:
10697 case 253 /* ImportSpecifier */:
10698 // Property name in binding element or import specifier
10699 return parent.propertyName === node;
10700 case 257 /* ExportSpecifier */:
10701 case 267 /* JsxAttribute */:
10702 // Any name in an export specifier or JSX Attribute
10703 return true;
10704 }
10705 return false;
10706 }
10707 ts.isIdentifierName = isIdentifierName;
10708 // An alias symbol is created by one of the following declarations:
10709 // import <symbol> = ...
10710 // import <symbol> from ...
10711 // import * as <symbol> from ...
10712 // import { x as <symbol> } from ...
10713 // export { x as <symbol> } from ...
10714 // export = <EntityNameExpression>
10715 // export default <EntityNameExpression>
10716 // module.exports = <EntityNameExpression>
10717 function isAliasSymbolDeclaration(node) {
10718 return node.kind === 248 /* ImportEqualsDeclaration */ ||
10719 node.kind === 247 /* NamespaceExportDeclaration */ ||
10720 node.kind === 250 /* ImportClause */ && !!node.name ||
10721 node.kind === 251 /* NamespaceImport */ ||
10722 node.kind === 253 /* ImportSpecifier */ ||
10723 node.kind === 257 /* ExportSpecifier */ ||
10724 node.kind === 254 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
10725 ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node);
10726 }
10727 ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
10728 function exportAssignmentIsAlias(node) {
10729 var e = ts.isExportAssignment(node) ? node.expression : node.right;
10730 return isEntityNameExpression(e) || ts.isClassExpression(e);
10731 }
10732 ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
10733 function getEffectiveBaseTypeNode(node) {
10734 var baseType = getClassExtendsHeritageElement(node);
10735 if (baseType && isInJSFile(node)) {
10736 // Prefer an @augments tag because it may have type parameters.
10737 var tag = ts.getJSDocAugmentsTag(node);
10738 if (tag) {
10739 return tag.class;
10740 }
10741 }
10742 return baseType;
10743 }
10744 ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
10745 function getClassExtendsHeritageElement(node) {
10746 var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */);
10747 return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
10748 }
10749 ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
10750 function getClassImplementsHeritageClauseElements(node) {
10751 var heritageClause = getHeritageClause(node.heritageClauses, 109 /* ImplementsKeyword */);
10752 return heritageClause ? heritageClause.types : undefined;
10753 }
10754 ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements;
10755 /** Returns the node in an `extends` or `implements` clause of a class or interface. */
10756 function getAllSuperTypeNodes(node) {
10757 return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray
10758 : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray
10759 : ts.emptyArray;
10760 }
10761 ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
10762 function getInterfaceBaseTypeNodes(node) {
10763 var heritageClause = getHeritageClause(node.heritageClauses, 86 /* ExtendsKeyword */);
10764 return heritageClause ? heritageClause.types : undefined;
10765 }
10766 ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
10767 function getHeritageClause(clauses, kind) {
10768 if (clauses) {
10769 for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
10770 var clause = clauses_1[_i];
10771 if (clause.token === kind) {
10772 return clause;
10773 }
10774 }
10775 }
10776 return undefined;
10777 }
10778 ts.getHeritageClause = getHeritageClause;
10779 function tryResolveScriptReference(host, sourceFile, reference) {
10780 if (!host.getCompilerOptions().noResolve) {
10781 var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName);
10782 return host.getSourceFile(referenceFileName);
10783 }
10784 }
10785 ts.tryResolveScriptReference = tryResolveScriptReference;
10786 function getAncestor(node, kind) {
10787 while (node) {
10788 if (node.kind === kind) {
10789 return node;
10790 }
10791 node = node.parent;
10792 }
10793 return undefined;
10794 }
10795 ts.getAncestor = getAncestor;
10796 function isKeyword(token) {
10797 return 73 /* FirstKeyword */ <= token && token <= 147 /* LastKeyword */;
10798 }
10799 ts.isKeyword = isKeyword;
10800 function isContextualKeyword(token) {
10801 return 118 /* FirstContextualKeyword */ <= token && token <= 147 /* LastContextualKeyword */;
10802 }
10803 ts.isContextualKeyword = isContextualKeyword;
10804 function isNonContextualKeyword(token) {
10805 return isKeyword(token) && !isContextualKeyword(token);
10806 }
10807 ts.isNonContextualKeyword = isNonContextualKeyword;
10808 function isStringANonContextualKeyword(name) {
10809 var token = ts.stringToToken(name);
10810 return token !== undefined && isNonContextualKeyword(token);
10811 }
10812 ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
10813 function isIdentifierANonContextualKeyword(_a) {
10814 var originalKeywordKind = _a.originalKeywordKind;
10815 return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
10816 }
10817 ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
10818 function isTrivia(token) {
10819 return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
10820 }
10821 ts.isTrivia = isTrivia;
10822 var FunctionFlags;
10823 (function (FunctionFlags) {
10824 FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
10825 FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
10826 FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
10827 FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
10828 FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
10829 })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
10830 function getFunctionFlags(node) {
10831 if (!node) {
10832 return 4 /* Invalid */;
10833 }
10834 var flags = 0 /* Normal */;
10835 switch (node.kind) {
10836 case 239 /* FunctionDeclaration */:
10837 case 196 /* FunctionExpression */:
10838 case 156 /* MethodDeclaration */:
10839 if (node.asteriskToken) {
10840 flags |= 1 /* Generator */;
10841 }
10842 // falls through
10843 case 197 /* ArrowFunction */:
10844 if (hasModifier(node, 256 /* Async */)) {
10845 flags |= 2 /* Async */;
10846 }
10847 break;
10848 }
10849 if (!node.body) {
10850 flags |= 4 /* Invalid */;
10851 }
10852 return flags;
10853 }
10854 ts.getFunctionFlags = getFunctionFlags;
10855 function isAsyncFunction(node) {
10856 switch (node.kind) {
10857 case 239 /* FunctionDeclaration */:
10858 case 196 /* FunctionExpression */:
10859 case 197 /* ArrowFunction */:
10860 case 156 /* MethodDeclaration */:
10861 return node.body !== undefined
10862 && node.asteriskToken === undefined
10863 && hasModifier(node, 256 /* Async */);
10864 }
10865 return false;
10866 }
10867 ts.isAsyncFunction = isAsyncFunction;
10868 function isStringOrNumericLiteralLike(node) {
10869 return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
10870 }
10871 ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
10872 /**
10873 * A declaration has a dynamic name if both of the following are true:
10874 * 1. The declaration has a computed property name
10875 * 2. The computed name is *not* expressed as Symbol.<name>, where name
10876 * is a property of the Symbol constructor that denotes a built in
10877 * Symbol.
10878 */
10879 function hasDynamicName(declaration) {
10880 var name = ts.getNameOfDeclaration(declaration);
10881 return !!name && isDynamicName(name);
10882 }
10883 ts.hasDynamicName = hasDynamicName;
10884 function isDynamicName(name) {
10885 return name.kind === 149 /* ComputedPropertyName */ &&
10886 !isStringOrNumericLiteralLike(name.expression) &&
10887 !isWellKnownSymbolSyntactically(name.expression);
10888 }
10889 ts.isDynamicName = isDynamicName;
10890 /**
10891 * Checks if the expression is of the form:
10892 * Symbol.name
10893 * where Symbol is literally the word "Symbol", and name is any identifierName
10894 */
10895 function isWellKnownSymbolSyntactically(node) {
10896 return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
10897 }
10898 ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
10899 function getPropertyNameForPropertyNameNode(name) {
10900 switch (name.kind) {
10901 case 72 /* Identifier */:
10902 return name.escapedText;
10903 case 10 /* StringLiteral */:
10904 case 8 /* NumericLiteral */:
10905 return ts.escapeLeadingUnderscores(name.text);
10906 case 149 /* ComputedPropertyName */:
10907 var nameExpression = name.expression;
10908 if (isWellKnownSymbolSyntactically(nameExpression)) {
10909 return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
10910 }
10911 else if (isStringOrNumericLiteralLike(nameExpression)) {
10912 return ts.escapeLeadingUnderscores(nameExpression.text);
10913 }
10914 return undefined;
10915 default:
10916 return ts.Debug.assertNever(name);
10917 }
10918 }
10919 ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
10920 function isPropertyNameLiteral(node) {
10921 switch (node.kind) {
10922 case 72 /* Identifier */:
10923 case 10 /* StringLiteral */:
10924 case 14 /* NoSubstitutionTemplateLiteral */:
10925 case 8 /* NumericLiteral */:
10926 return true;
10927 default:
10928 return false;
10929 }
10930 }
10931 ts.isPropertyNameLiteral = isPropertyNameLiteral;
10932 function getTextOfIdentifierOrLiteral(node) {
10933 return node.kind === 72 /* Identifier */ ? ts.idText(node) : node.text;
10934 }
10935 ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
10936 function getEscapedTextOfIdentifierOrLiteral(node) {
10937 return node.kind === 72 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
10938 }
10939 ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
10940 function getPropertyNameForKnownSymbolName(symbolName) {
10941 return "__@" + symbolName;
10942 }
10943 ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
10944 function isKnownSymbol(symbol) {
10945 return ts.startsWith(symbol.escapedName, "__@");
10946 }
10947 ts.isKnownSymbol = isKnownSymbol;
10948 /**
10949 * Includes the word "Symbol" with unicode escapes
10950 */
10951 function isESSymbolIdentifier(node) {
10952 return node.kind === 72 /* Identifier */ && node.escapedText === "Symbol";
10953 }
10954 ts.isESSymbolIdentifier = isESSymbolIdentifier;
10955 function isPushOrUnshiftIdentifier(node) {
10956 return node.escapedText === "push" || node.escapedText === "unshift";
10957 }
10958 ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
10959 function isParameterDeclaration(node) {
10960 var root = getRootDeclaration(node);
10961 return root.kind === 151 /* Parameter */;
10962 }
10963 ts.isParameterDeclaration = isParameterDeclaration;
10964 function getRootDeclaration(node) {
10965 while (node.kind === 186 /* BindingElement */) {
10966 node = node.parent.parent;
10967 }
10968 return node;
10969 }
10970 ts.getRootDeclaration = getRootDeclaration;
10971 function nodeStartsNewLexicalEnvironment(node) {
10972 var kind = node.kind;
10973 return kind === 157 /* Constructor */
10974 || kind === 196 /* FunctionExpression */
10975 || kind === 239 /* FunctionDeclaration */
10976 || kind === 197 /* ArrowFunction */
10977 || kind === 156 /* MethodDeclaration */
10978 || kind === 158 /* GetAccessor */
10979 || kind === 159 /* SetAccessor */
10980 || kind === 244 /* ModuleDeclaration */
10981 || kind === 284 /* SourceFile */;
10982 }
10983 ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
10984 function nodeIsSynthesized(range) {
10985 return ts.positionIsSynthesized(range.pos)
10986 || ts.positionIsSynthesized(range.end);
10987 }
10988 ts.nodeIsSynthesized = nodeIsSynthesized;
10989 function getOriginalSourceFile(sourceFile) {
10990 return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
10991 }
10992 ts.getOriginalSourceFile = getOriginalSourceFile;
10993 var Associativity;
10994 (function (Associativity) {
10995 Associativity[Associativity["Left"] = 0] = "Left";
10996 Associativity[Associativity["Right"] = 1] = "Right";
10997 })(Associativity = ts.Associativity || (ts.Associativity = {}));
10998 function getExpressionAssociativity(expression) {
10999 var operator = getOperator(expression);
11000 var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined;
11001 return getOperatorAssociativity(expression.kind, operator, hasArguments);
11002 }
11003 ts.getExpressionAssociativity = getExpressionAssociativity;
11004 function getOperatorAssociativity(kind, operator, hasArguments) {
11005 switch (kind) {
11006 case 192 /* NewExpression */:
11007 return hasArguments ? 0 /* Left */ : 1 /* Right */;
11008 case 202 /* PrefixUnaryExpression */:
11009 case 199 /* TypeOfExpression */:
11010 case 200 /* VoidExpression */:
11011 case 198 /* DeleteExpression */:
11012 case 201 /* AwaitExpression */:
11013 case 205 /* ConditionalExpression */:
11014 case 207 /* YieldExpression */:
11015 return 1 /* Right */;
11016 case 204 /* BinaryExpression */:
11017 switch (operator) {
11018 case 41 /* AsteriskAsteriskToken */:
11019 case 59 /* EqualsToken */:
11020 case 60 /* PlusEqualsToken */:
11021 case 61 /* MinusEqualsToken */:
11022 case 63 /* AsteriskAsteriskEqualsToken */:
11023 case 62 /* AsteriskEqualsToken */:
11024 case 64 /* SlashEqualsToken */:
11025 case 65 /* PercentEqualsToken */:
11026 case 66 /* LessThanLessThanEqualsToken */:
11027 case 67 /* GreaterThanGreaterThanEqualsToken */:
11028 case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
11029 case 69 /* AmpersandEqualsToken */:
11030 case 71 /* CaretEqualsToken */:
11031 case 70 /* BarEqualsToken */:
11032 return 1 /* Right */;
11033 }
11034 }
11035 return 0 /* Left */;
11036 }
11037 ts.getOperatorAssociativity = getOperatorAssociativity;
11038 function getExpressionPrecedence(expression) {
11039 var operator = getOperator(expression);
11040 var hasArguments = expression.kind === 192 /* NewExpression */ && expression.arguments !== undefined;
11041 return getOperatorPrecedence(expression.kind, operator, hasArguments);
11042 }
11043 ts.getExpressionPrecedence = getExpressionPrecedence;
11044 function getOperator(expression) {
11045 if (expression.kind === 204 /* BinaryExpression */) {
11046 return expression.operatorToken.kind;
11047 }
11048 else if (expression.kind === 202 /* PrefixUnaryExpression */ || expression.kind === 203 /* PostfixUnaryExpression */) {
11049 return expression.operator;
11050 }
11051 else {
11052 return expression.kind;
11053 }
11054 }
11055 ts.getOperator = getOperator;
11056 function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
11057 switch (nodeKind) {
11058 case 314 /* CommaListExpression */:
11059 return 0;
11060 case 208 /* SpreadElement */:
11061 return 1;
11062 case 207 /* YieldExpression */:
11063 return 2;
11064 case 205 /* ConditionalExpression */:
11065 return 4;
11066 case 204 /* BinaryExpression */:
11067 switch (operatorKind) {
11068 case 27 /* CommaToken */:
11069 return 0;
11070 case 59 /* EqualsToken */:
11071 case 60 /* PlusEqualsToken */:
11072 case 61 /* MinusEqualsToken */:
11073 case 63 /* AsteriskAsteriskEqualsToken */:
11074 case 62 /* AsteriskEqualsToken */:
11075 case 64 /* SlashEqualsToken */:
11076 case 65 /* PercentEqualsToken */:
11077 case 66 /* LessThanLessThanEqualsToken */:
11078 case 67 /* GreaterThanGreaterThanEqualsToken */:
11079 case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
11080 case 69 /* AmpersandEqualsToken */:
11081 case 71 /* CaretEqualsToken */:
11082 case 70 /* BarEqualsToken */:
11083 return 3;
11084 default:
11085 return getBinaryOperatorPrecedence(operatorKind);
11086 }
11087 case 202 /* PrefixUnaryExpression */:
11088 case 199 /* TypeOfExpression */:
11089 case 200 /* VoidExpression */:
11090 case 198 /* DeleteExpression */:
11091 case 201 /* AwaitExpression */:
11092 return 16;
11093 case 203 /* PostfixUnaryExpression */:
11094 return 17;
11095 case 191 /* CallExpression */:
11096 return 18;
11097 case 192 /* NewExpression */:
11098 return hasArguments ? 19 : 18;
11099 case 193 /* TaggedTemplateExpression */:
11100 case 189 /* PropertyAccessExpression */:
11101 case 190 /* ElementAccessExpression */:
11102 return 19;
11103 case 100 /* ThisKeyword */:
11104 case 98 /* SuperKeyword */:
11105 case 72 /* Identifier */:
11106 case 96 /* NullKeyword */:
11107 case 102 /* TrueKeyword */:
11108 case 87 /* FalseKeyword */:
11109 case 8 /* NumericLiteral */:
11110 case 9 /* BigIntLiteral */:
11111 case 10 /* StringLiteral */:
11112 case 187 /* ArrayLiteralExpression */:
11113 case 188 /* ObjectLiteralExpression */:
11114 case 196 /* FunctionExpression */:
11115 case 197 /* ArrowFunction */:
11116 case 209 /* ClassExpression */:
11117 case 260 /* JsxElement */:
11118 case 261 /* JsxSelfClosingElement */:
11119 case 264 /* JsxFragment */:
11120 case 13 /* RegularExpressionLiteral */:
11121 case 14 /* NoSubstitutionTemplateLiteral */:
11122 case 206 /* TemplateExpression */:
11123 case 195 /* ParenthesizedExpression */:
11124 case 210 /* OmittedExpression */:
11125 return 20;
11126 default:
11127 return -1;
11128 }
11129 }
11130 ts.getOperatorPrecedence = getOperatorPrecedence;
11131 function getBinaryOperatorPrecedence(kind) {
11132 switch (kind) {
11133 case 55 /* BarBarToken */:
11134 return 5;
11135 case 54 /* AmpersandAmpersandToken */:
11136 return 6;
11137 case 50 /* BarToken */:
11138 return 7;
11139 case 51 /* CaretToken */:
11140 return 8;
11141 case 49 /* AmpersandToken */:
11142 return 9;
11143 case 33 /* EqualsEqualsToken */:
11144 case 34 /* ExclamationEqualsToken */:
11145 case 35 /* EqualsEqualsEqualsToken */:
11146 case 36 /* ExclamationEqualsEqualsToken */:
11147 return 10;
11148 case 28 /* LessThanToken */:
11149 case 30 /* GreaterThanToken */:
11150 case 31 /* LessThanEqualsToken */:
11151 case 32 /* GreaterThanEqualsToken */:
11152 case 94 /* InstanceOfKeyword */:
11153 case 93 /* InKeyword */:
11154 case 119 /* AsKeyword */:
11155 return 11;
11156 case 46 /* LessThanLessThanToken */:
11157 case 47 /* GreaterThanGreaterThanToken */:
11158 case 48 /* GreaterThanGreaterThanGreaterThanToken */:
11159 return 12;
11160 case 38 /* PlusToken */:
11161 case 39 /* MinusToken */:
11162 return 13;
11163 case 40 /* AsteriskToken */:
11164 case 42 /* SlashToken */:
11165 case 43 /* PercentToken */:
11166 return 14;
11167 case 41 /* AsteriskAsteriskToken */:
11168 return 15;
11169 }
11170 // -1 is lower than all other precedences. Returning it will cause binary expression
11171 // parsing to stop.
11172 return -1;
11173 }
11174 ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
11175 function createDiagnosticCollection() {
11176 var nonFileDiagnostics = []; // See GH#19873
11177 var filesWithDiagnostics = [];
11178 var fileDiagnostics = ts.createMap();
11179 var hasReadNonFileDiagnostics = false;
11180 return {
11181 add: add,
11182 lookup: lookup,
11183 getGlobalDiagnostics: getGlobalDiagnostics,
11184 getDiagnostics: getDiagnostics,
11185 reattachFileDiagnostics: reattachFileDiagnostics
11186 };
11187 function reattachFileDiagnostics(newFile) {
11188 ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
11189 }
11190 function lookup(diagnostic) {
11191 var diagnostics;
11192 if (diagnostic.file) {
11193 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
11194 }
11195 else {
11196 diagnostics = nonFileDiagnostics;
11197 }
11198 if (!diagnostics) {
11199 return undefined;
11200 }
11201 var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation);
11202 if (result >= 0) {
11203 return diagnostics[result];
11204 }
11205 return undefined;
11206 }
11207 function add(diagnostic) {
11208 var diagnostics;
11209 if (diagnostic.file) {
11210 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
11211 if (!diagnostics) {
11212 diagnostics = []; // See GH#19873
11213 fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
11214 ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
11215 }
11216 }
11217 else {
11218 // If we've already read the non-file diagnostics, do not modify the existing array.
11219 if (hasReadNonFileDiagnostics) {
11220 hasReadNonFileDiagnostics = false;
11221 nonFileDiagnostics = nonFileDiagnostics.slice();
11222 }
11223 diagnostics = nonFileDiagnostics;
11224 }
11225 ts.insertSorted(diagnostics, diagnostic, ts.compareDiagnostics);
11226 }
11227 function getGlobalDiagnostics() {
11228 hasReadNonFileDiagnostics = true;
11229 return nonFileDiagnostics;
11230 }
11231 function getDiagnostics(fileName) {
11232 if (fileName) {
11233 return fileDiagnostics.get(fileName) || [];
11234 }
11235 var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
11236 if (!nonFileDiagnostics.length) {
11237 return fileDiags;
11238 }
11239 fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
11240 return fileDiags;
11241 }
11242 }
11243 ts.createDiagnosticCollection = createDiagnosticCollection;
11244 // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
11245 // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
11246 // the language service. These characters should be escaped when printing, and if any characters are added,
11247 // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
11248 // There is no reason for this other than that JSON.stringify does not handle it either.
11249 var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
11250 var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
11251 var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
11252 var escapedCharsMap = ts.createMapFromTemplate({
11253 "\t": "\\t",
11254 "\v": "\\v",
11255 "\f": "\\f",
11256 "\b": "\\b",
11257 "\r": "\\r",
11258 "\n": "\\n",
11259 "\\": "\\\\",
11260 "\"": "\\\"",
11261 "\'": "\\\'",
11262 "\`": "\\\`",
11263 "\u2028": "\\u2028",
11264 "\u2029": "\\u2029",
11265 "\u0085": "\\u0085" // nextLine
11266 });
11267 /**
11268 * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
11269 * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
11270 * Note that this doesn't actually wrap the input in double quotes.
11271 */
11272 function escapeString(s, quoteChar) {
11273 var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
11274 quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
11275 doubleQuoteEscapedCharsRegExp;
11276 return s.replace(escapedCharsRegExp, getReplacement);
11277 }
11278 ts.escapeString = escapeString;
11279 function getReplacement(c, offset, input) {
11280 if (c.charCodeAt(0) === 0 /* nullCharacter */) {
11281 var lookAhead = input.charCodeAt(offset + c.length);
11282 if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
11283 // 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)
11284 return "\\x00";
11285 }
11286 // Otherwise, keep printing a literal \0 for the null character
11287 return "\\0";
11288 }
11289 return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0));
11290 }
11291 function isIntrinsicJsxName(name) {
11292 var ch = name.charCodeAt(0);
11293 return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
11294 }
11295 ts.isIntrinsicJsxName = isIntrinsicJsxName;
11296 function get16BitUnicodeEscapeSequence(charCode) {
11297 var hexCharCode = charCode.toString(16).toUpperCase();
11298 var paddedHexCode = ("0000" + hexCharCode).slice(-4);
11299 return "\\u" + paddedHexCode;
11300 }
11301 var nonAsciiCharacters = /[^\u0000-\u007F]/g;
11302 function escapeNonAsciiString(s, quoteChar) {
11303 s = escapeString(s, quoteChar);
11304 // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
11305 // Otherwise just return the original string.
11306 return nonAsciiCharacters.test(s) ?
11307 s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) :
11308 s;
11309 }
11310 ts.escapeNonAsciiString = escapeNonAsciiString;
11311 var indentStrings = ["", " "];
11312 function getIndentString(level) {
11313 if (indentStrings[level] === undefined) {
11314 indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
11315 }
11316 return indentStrings[level];
11317 }
11318 ts.getIndentString = getIndentString;
11319 function getIndentSize() {
11320 return indentStrings[1].length;
11321 }
11322 ts.getIndentSize = getIndentSize;
11323 function createTextWriter(newLine) {
11324 var output;
11325 var indent;
11326 var lineStart;
11327 var lineCount;
11328 var linePos;
11329 function updateLineCountAndPosFor(s) {
11330 var lineStartsOfS = ts.computeLineStarts(s);
11331 if (lineStartsOfS.length > 1) {
11332 lineCount = lineCount + lineStartsOfS.length - 1;
11333 linePos = output.length - s.length + ts.last(lineStartsOfS);
11334 lineStart = (linePos - output.length) === 0;
11335 }
11336 else {
11337 lineStart = false;
11338 }
11339 }
11340 function write(s) {
11341 if (s && s.length) {
11342 if (lineStart) {
11343 s = getIndentString(indent) + s;
11344 lineStart = false;
11345 }
11346 output += s;
11347 updateLineCountAndPosFor(s);
11348 }
11349 }
11350 function reset() {
11351 output = "";
11352 indent = 0;
11353 lineStart = true;
11354 lineCount = 0;
11355 linePos = 0;
11356 }
11357 function rawWrite(s) {
11358 if (s !== undefined) {
11359 output += s;
11360 updateLineCountAndPosFor(s);
11361 }
11362 }
11363 function writeLiteral(s) {
11364 if (s && s.length) {
11365 write(s);
11366 }
11367 }
11368 function writeLine() {
11369 if (!lineStart) {
11370 output += newLine;
11371 lineCount++;
11372 linePos = output.length;
11373 lineStart = true;
11374 }
11375 }
11376 function getTextPosWithWriteLine() {
11377 return lineStart ? output.length : (output.length + newLine.length);
11378 }
11379 reset();
11380 return {
11381 write: write,
11382 rawWrite: rawWrite,
11383 writeLiteral: writeLiteral,
11384 writeLine: writeLine,
11385 increaseIndent: function () { indent++; },
11386 decreaseIndent: function () { indent--; },
11387 getIndent: function () { return indent; },
11388 getTextPos: function () { return output.length; },
11389 getLine: function () { return lineCount; },
11390 getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
11391 getText: function () { return output; },
11392 isAtStartOfLine: function () { return lineStart; },
11393 clear: reset,
11394 reportInaccessibleThisError: ts.noop,
11395 reportPrivateInBaseOfClassExpression: ts.noop,
11396 reportInaccessibleUniqueSymbolError: ts.noop,
11397 trackSymbol: ts.noop,
11398 writeKeyword: write,
11399 writeOperator: write,
11400 writeParameter: write,
11401 writeProperty: write,
11402 writePunctuation: write,
11403 writeSpace: write,
11404 writeStringLiteral: write,
11405 writeSymbol: function (s, _) { return write(s); },
11406 writeTrailingSemicolon: write,
11407 writeComment: write,
11408 getTextPosWithWriteLine: getTextPosWithWriteLine
11409 };
11410 }
11411 ts.createTextWriter = createTextWriter;
11412 function getTrailingSemicolonOmittingWriter(writer) {
11413 var pendingTrailingSemicolon = false;
11414 function commitPendingTrailingSemicolon() {
11415 if (pendingTrailingSemicolon) {
11416 writer.writeTrailingSemicolon(";");
11417 pendingTrailingSemicolon = false;
11418 }
11419 }
11420 return __assign({}, writer, { writeTrailingSemicolon: function () {
11421 pendingTrailingSemicolon = true;
11422 },
11423 writeLiteral: function (s) {
11424 commitPendingTrailingSemicolon();
11425 writer.writeLiteral(s);
11426 },
11427 writeStringLiteral: function (s) {
11428 commitPendingTrailingSemicolon();
11429 writer.writeStringLiteral(s);
11430 },
11431 writeSymbol: function (s, sym) {
11432 commitPendingTrailingSemicolon();
11433 writer.writeSymbol(s, sym);
11434 },
11435 writePunctuation: function (s) {
11436 commitPendingTrailingSemicolon();
11437 writer.writePunctuation(s);
11438 },
11439 writeKeyword: function (s) {
11440 commitPendingTrailingSemicolon();
11441 writer.writeKeyword(s);
11442 },
11443 writeOperator: function (s) {
11444 commitPendingTrailingSemicolon();
11445 writer.writeOperator(s);
11446 },
11447 writeParameter: function (s) {
11448 commitPendingTrailingSemicolon();
11449 writer.writeParameter(s);
11450 },
11451 writeSpace: function (s) {
11452 commitPendingTrailingSemicolon();
11453 writer.writeSpace(s);
11454 },
11455 writeProperty: function (s) {
11456 commitPendingTrailingSemicolon();
11457 writer.writeProperty(s);
11458 },
11459 writeComment: function (s) {
11460 commitPendingTrailingSemicolon();
11461 writer.writeComment(s);
11462 },
11463 writeLine: function () {
11464 commitPendingTrailingSemicolon();
11465 writer.writeLine();
11466 },
11467 increaseIndent: function () {
11468 commitPendingTrailingSemicolon();
11469 writer.increaseIndent();
11470 },
11471 decreaseIndent: function () {
11472 commitPendingTrailingSemicolon();
11473 writer.decreaseIndent();
11474 } });
11475 }
11476 ts.getTrailingSemicolonOmittingWriter = getTrailingSemicolonOmittingWriter;
11477 function getResolvedExternalModuleName(host, file, referenceFile) {
11478 return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
11479 }
11480 ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
11481 function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
11482 var file = resolver.getExternalModuleFileFromDeclaration(declaration);
11483 if (!file || file.isDeclarationFile) {
11484 return undefined;
11485 }
11486 return getResolvedExternalModuleName(host, file);
11487 }
11488 ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
11489 /**
11490 * Resolves a local path to a path which is absolute to the base of the emit
11491 */
11492 function getExternalModuleNameFromPath(host, fileName, referencePath) {
11493 var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
11494 var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
11495 var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
11496 var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
11497 var extensionless = ts.removeFileExtension(relativePath);
11498 return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
11499 }
11500 ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
11501 function getOwnEmitOutputFilePath(fileName, host, extension) {
11502 var compilerOptions = host.getCompilerOptions();
11503 var emitOutputFilePathWithoutExtension;
11504 if (compilerOptions.outDir) {
11505 emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
11506 }
11507 else {
11508 emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName);
11509 }
11510 return emitOutputFilePathWithoutExtension + extension;
11511 }
11512 ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
11513 function getDeclarationEmitOutputFilePath(fileName, host) {
11514 return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
11515 }
11516 ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
11517 function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
11518 var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
11519 var path = outputDir
11520 ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
11521 : fileName;
11522 return ts.removeFileExtension(path) + ".d.ts" /* Dts */;
11523 }
11524 ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
11525 /**
11526 * Gets the source files that are expected to have an emit output.
11527 *
11528 * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
11529 * transformations.
11530 *
11531 * @param host An EmitHost.
11532 * @param targetSourceFile An optional target source file to emit.
11533 */
11534 function getSourceFilesToEmit(host, targetSourceFile) {
11535 var options = host.getCompilerOptions();
11536 var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
11537 var getResolvedProjectReferenceToRedirect = function (fileName) { return host.getResolvedProjectReferenceToRedirect(fileName); };
11538 if (options.outFile || options.out) {
11539 var moduleKind = ts.getEmitModuleKind(options);
11540 var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
11541 // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
11542 return ts.filter(host.getSourceFiles(), function (sourceFile) {
11543 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect);
11544 });
11545 }
11546 else {
11547 var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
11548 return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
11549 }
11550 }
11551 ts.getSourceFilesToEmit = getSourceFilesToEmit;
11552 /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
11553 function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect) {
11554 return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
11555 !sourceFile.isDeclarationFile &&
11556 !isSourceFileFromExternalLibrary(sourceFile) &&
11557 !(isJsonSourceFile(sourceFile) && getResolvedProjectReferenceToRedirect(sourceFile.fileName));
11558 }
11559 ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
11560 function getSourceFilePathInNewDir(fileName, host, newDirPath) {
11561 return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
11562 }
11563 ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
11564 function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
11565 var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
11566 var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
11567 sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
11568 return ts.combinePaths(newDirPath, sourceFilePath);
11569 }
11570 ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
11571 function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
11572 host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
11573 diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
11574 }, sourceFiles);
11575 }
11576 ts.writeFile = writeFile;
11577 function getLineOfLocalPosition(currentSourceFile, pos) {
11578 return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line;
11579 }
11580 ts.getLineOfLocalPosition = getLineOfLocalPosition;
11581 function getLineOfLocalPositionFromLineMap(lineMap, pos) {
11582 return ts.computeLineAndCharacterOfPosition(lineMap, pos).line;
11583 }
11584 ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
11585 function getFirstConstructorWithBody(node) {
11586 return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
11587 }
11588 ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
11589 function getSetAccessorValueParameter(accessor) {
11590 if (accessor && accessor.parameters.length > 0) {
11591 var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
11592 return accessor.parameters[hasThis ? 1 : 0];
11593 }
11594 }
11595 /** Get the type annotation for the value parameter. */
11596 function getSetAccessorTypeAnnotationNode(accessor) {
11597 var parameter = getSetAccessorValueParameter(accessor);
11598 return parameter && parameter.type;
11599 }
11600 ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
11601 function getThisParameter(signature) {
11602 // callback tags do not currently support this parameters
11603 if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
11604 var thisParameter = signature.parameters[0];
11605 if (parameterIsThisKeyword(thisParameter)) {
11606 return thisParameter;
11607 }
11608 }
11609 }
11610 ts.getThisParameter = getThisParameter;
11611 function parameterIsThisKeyword(parameter) {
11612 return isThisIdentifier(parameter.name);
11613 }
11614 ts.parameterIsThisKeyword = parameterIsThisKeyword;
11615 function isThisIdentifier(node) {
11616 return !!node && node.kind === 72 /* Identifier */ && identifierIsThisKeyword(node);
11617 }
11618 ts.isThisIdentifier = isThisIdentifier;
11619 function identifierIsThisKeyword(id) {
11620 return id.originalKeywordKind === 100 /* ThisKeyword */;
11621 }
11622 ts.identifierIsThisKeyword = identifierIsThisKeyword;
11623 function getAllAccessorDeclarations(declarations, accessor) {
11624 // TODO: GH#18217
11625 var firstAccessor;
11626 var secondAccessor;
11627 var getAccessor;
11628 var setAccessor;
11629 if (hasDynamicName(accessor)) {
11630 firstAccessor = accessor;
11631 if (accessor.kind === 158 /* GetAccessor */) {
11632 getAccessor = accessor;
11633 }
11634 else if (accessor.kind === 159 /* SetAccessor */) {
11635 setAccessor = accessor;
11636 }
11637 else {
11638 ts.Debug.fail("Accessor has wrong kind");
11639 }
11640 }
11641 else {
11642 ts.forEach(declarations, function (member) {
11643 if (ts.isAccessor(member)
11644 && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
11645 var memberName = getPropertyNameForPropertyNameNode(member.name);
11646 var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
11647 if (memberName === accessorName) {
11648 if (!firstAccessor) {
11649 firstAccessor = member;
11650 }
11651 else if (!secondAccessor) {
11652 secondAccessor = member;
11653 }
11654 if (member.kind === 158 /* GetAccessor */ && !getAccessor) {
11655 getAccessor = member;
11656 }
11657 if (member.kind === 159 /* SetAccessor */ && !setAccessor) {
11658 setAccessor = member;
11659 }
11660 }
11661 }
11662 });
11663 }
11664 return {
11665 firstAccessor: firstAccessor,
11666 secondAccessor: secondAccessor,
11667 getAccessor: getAccessor,
11668 setAccessor: setAccessor
11669 };
11670 }
11671 ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
11672 /**
11673 * Gets the effective type annotation of a variable, parameter, or property. If the node was
11674 * parsed in a JavaScript file, gets the type annotation from JSDoc.
11675 */
11676 function getEffectiveTypeAnnotationNode(node) {
11677 var type = node.type;
11678 if (type || !isInJSFile(node))
11679 return type;
11680 return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
11681 }
11682 ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
11683 function getTypeAnnotationNode(node) {
11684 return node.type;
11685 }
11686 ts.getTypeAnnotationNode = getTypeAnnotationNode;
11687 /**
11688 * Gets the effective return type annotation of a signature. If the node was parsed in a
11689 * JavaScript file, gets the return type annotation from JSDoc.
11690 */
11691 function getEffectiveReturnTypeNode(node) {
11692 return ts.isJSDocSignature(node) ?
11693 node.type && node.type.typeExpression && node.type.typeExpression.type :
11694 node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
11695 }
11696 ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
11697 function getJSDocTypeParameterDeclarations(node) {
11698 return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
11699 }
11700 ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
11701 /** template tags are only available when a typedef isn't already using them */
11702 function isNonTypeAliasTemplate(tag) {
11703 return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
11704 }
11705 /**
11706 * Gets the effective type annotation of the value parameter of a set accessor. If the node
11707 * was parsed in a JavaScript file, gets the type annotation from JSDoc.
11708 */
11709 function getEffectiveSetAccessorTypeAnnotationNode(node) {
11710 var parameter = getSetAccessorValueParameter(node);
11711 return parameter && getEffectiveTypeAnnotationNode(parameter);
11712 }
11713 ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
11714 function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
11715 emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
11716 }
11717 ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
11718 function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
11719 // If the leading comments start on different line than the start of node, write new line
11720 if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
11721 getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
11722 writer.writeLine();
11723 }
11724 }
11725 ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
11726 function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
11727 // If the leading comments start on different line than the start of node, write new line
11728 if (pos !== commentPos &&
11729 getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
11730 writer.writeLine();
11731 }
11732 }
11733 ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
11734 function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
11735 if (comments && comments.length > 0) {
11736 if (leadingSeparator) {
11737 writer.writeSpace(" ");
11738 }
11739 var emitInterveningSeparator = false;
11740 for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
11741 var comment = comments_1[_i];
11742 if (emitInterveningSeparator) {
11743 writer.writeSpace(" ");
11744 emitInterveningSeparator = false;
11745 }
11746 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
11747 if (comment.hasTrailingNewLine) {
11748 writer.writeLine();
11749 }
11750 else {
11751 emitInterveningSeparator = true;
11752 }
11753 }
11754 if (emitInterveningSeparator && trailingSeparator) {
11755 writer.writeSpace(" ");
11756 }
11757 }
11758 }
11759 ts.emitComments = emitComments;
11760 /**
11761 * Detached comment is a comment at the top of file or function body that is separated from
11762 * the next statement by space.
11763 */
11764 function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
11765 var leadingComments;
11766 var currentDetachedCommentInfo;
11767 if (removeComments) {
11768 // removeComments is true, only reserve pinned comment at the top of file
11769 // For example:
11770 // /*! Pinned Comment */
11771 //
11772 // var x = 10;
11773 if (node.pos === 0) {
11774 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
11775 }
11776 }
11777 else {
11778 // removeComments is false, just get detached as normal and bypass the process to filter comment
11779 leadingComments = ts.getLeadingCommentRanges(text, node.pos);
11780 }
11781 if (leadingComments) {
11782 var detachedComments = [];
11783 var lastComment = void 0;
11784 for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
11785 var comment = leadingComments_1[_i];
11786 if (lastComment) {
11787 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
11788 var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
11789 if (commentLine >= lastCommentLine + 2) {
11790 // There was a blank line between the last comment and this comment. This
11791 // comment is not part of the copyright comments. Return what we have so
11792 // far.
11793 break;
11794 }
11795 }
11796 detachedComments.push(comment);
11797 lastComment = comment;
11798 }
11799 if (detachedComments.length) {
11800 // All comments look like they could have been part of the copyright header. Make
11801 // sure there is at least one blank line between it and the node. If not, it's not
11802 // a copyright header.
11803 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
11804 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
11805 if (nodeLine >= lastCommentLine + 2) {
11806 // Valid detachedComments
11807 emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
11808 emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
11809 currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
11810 }
11811 }
11812 }
11813 return currentDetachedCommentInfo;
11814 function isPinnedCommentLocal(comment) {
11815 return isPinnedComment(text, comment.pos);
11816 }
11817 }
11818 ts.emitDetachedComments = emitDetachedComments;
11819 function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
11820 if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
11821 var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
11822 var lineCount = lineMap.length;
11823 var firstCommentLineIndent = void 0;
11824 for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
11825 var nextLineStart = (currentLine + 1) === lineCount
11826 ? text.length + 1
11827 : lineMap[currentLine + 1];
11828 if (pos !== commentPos) {
11829 // If we are not emitting first line, we need to write the spaces to adjust the alignment
11830 if (firstCommentLineIndent === undefined) {
11831 firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
11832 }
11833 // These are number of spaces writer is going to write at current indent
11834 var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
11835 // Number of spaces we want to be writing
11836 // eg: Assume writer indent
11837 // module m {
11838 // /* starts at character 9 this is line 1
11839 // * starts at character pos 4 line --1 = 8 - 8 + 3
11840 // More left indented comment */ --2 = 8 - 8 + 2
11841 // class c { }
11842 // }
11843 // module m {
11844 // /* this is line 1 -- Assume current writer indent 8
11845 // * line --3 = 8 - 4 + 5
11846 // More right indented comment */ --4 = 8 - 4 + 11
11847 // class c { }
11848 // }
11849 var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
11850 if (spacesToEmit > 0) {
11851 var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
11852 var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
11853 // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
11854 writer.rawWrite(indentSizeSpaceString);
11855 // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
11856 while (numberOfSingleSpacesToEmit) {
11857 writer.rawWrite(" ");
11858 numberOfSingleSpacesToEmit--;
11859 }
11860 }
11861 else {
11862 // No spaces to emit write empty string
11863 writer.rawWrite("");
11864 }
11865 }
11866 // Write the comment line text
11867 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
11868 pos = nextLineStart;
11869 }
11870 }
11871 else {
11872 // Single line comment of style //....
11873 writer.writeComment(text.substring(commentPos, commentEnd));
11874 }
11875 }
11876 ts.writeCommentRange = writeCommentRange;
11877 function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
11878 var end = Math.min(commentEnd, nextLineStart - 1);
11879 var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
11880 if (currentLineText) {
11881 // trimmed forward and ending spaces text
11882 writer.writeComment(currentLineText);
11883 if (end !== commentEnd) {
11884 writer.writeLine();
11885 }
11886 }
11887 else {
11888 // Empty string - make sure we write empty line
11889 writer.rawWrite(newLine);
11890 }
11891 }
11892 function calculateIndent(text, pos, end) {
11893 var currentLineIndent = 0;
11894 for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
11895 if (text.charCodeAt(pos) === 9 /* tab */) {
11896 // Tabs = TabSize = indent size and go to next tabStop
11897 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
11898 }
11899 else {
11900 // Single space
11901 currentLineIndent++;
11902 }
11903 }
11904 return currentLineIndent;
11905 }
11906 function hasModifiers(node) {
11907 return getModifierFlags(node) !== 0 /* None */;
11908 }
11909 ts.hasModifiers = hasModifiers;
11910 function hasModifier(node, flags) {
11911 return !!getSelectedModifierFlags(node, flags);
11912 }
11913 ts.hasModifier = hasModifier;
11914 function hasStaticModifier(node) {
11915 return hasModifier(node, 32 /* Static */);
11916 }
11917 ts.hasStaticModifier = hasStaticModifier;
11918 function hasReadonlyModifier(node) {
11919 return hasModifier(node, 64 /* Readonly */);
11920 }
11921 ts.hasReadonlyModifier = hasReadonlyModifier;
11922 function getSelectedModifierFlags(node, flags) {
11923 return getModifierFlags(node) & flags;
11924 }
11925 ts.getSelectedModifierFlags = getSelectedModifierFlags;
11926 function getModifierFlags(node) {
11927 if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
11928 return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
11929 }
11930 var flags = getModifierFlagsNoCache(node);
11931 node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
11932 return flags;
11933 }
11934 ts.getModifierFlags = getModifierFlags;
11935 function getModifierFlagsNoCache(node) {
11936 var flags = 0 /* None */;
11937 if (node.modifiers) {
11938 for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
11939 var modifier = _a[_i];
11940 flags |= modifierToFlag(modifier.kind);
11941 }
11942 }
11943 if (node.flags & 4 /* NestedNamespace */ || (node.kind === 72 /* Identifier */ && node.isInJSDocNamespace)) {
11944 flags |= 1 /* Export */;
11945 }
11946 return flags;
11947 }
11948 ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
11949 function modifierToFlag(token) {
11950 switch (token) {
11951 case 116 /* StaticKeyword */: return 32 /* Static */;
11952 case 115 /* PublicKeyword */: return 4 /* Public */;
11953 case 114 /* ProtectedKeyword */: return 16 /* Protected */;
11954 case 113 /* PrivateKeyword */: return 8 /* Private */;
11955 case 118 /* AbstractKeyword */: return 128 /* Abstract */;
11956 case 85 /* ExportKeyword */: return 1 /* Export */;
11957 case 125 /* DeclareKeyword */: return 2 /* Ambient */;
11958 case 77 /* ConstKeyword */: return 2048 /* Const */;
11959 case 80 /* DefaultKeyword */: return 512 /* Default */;
11960 case 121 /* AsyncKeyword */: return 256 /* Async */;
11961 case 133 /* ReadonlyKeyword */: return 64 /* Readonly */;
11962 }
11963 return 0 /* None */;
11964 }
11965 ts.modifierToFlag = modifierToFlag;
11966 function isLogicalOperator(token) {
11967 return token === 55 /* BarBarToken */
11968 || token === 54 /* AmpersandAmpersandToken */
11969 || token === 52 /* ExclamationToken */;
11970 }
11971 ts.isLogicalOperator = isLogicalOperator;
11972 function isAssignmentOperator(token) {
11973 return token >= 59 /* FirstAssignment */ && token <= 71 /* LastAssignment */;
11974 }
11975 ts.isAssignmentOperator = isAssignmentOperator;
11976 /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
11977 function tryGetClassExtendingExpressionWithTypeArguments(node) {
11978 var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
11979 return cls && !cls.isImplements ? cls.class : undefined;
11980 }
11981 ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
11982 function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
11983 return ts.isExpressionWithTypeArguments(node)
11984 && ts.isHeritageClause(node.parent)
11985 && ts.isClassLike(node.parent.parent)
11986 ? { class: node.parent.parent, isImplements: node.parent.token === 109 /* ImplementsKeyword */ }
11987 : undefined;
11988 }
11989 ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
11990 function isAssignmentExpression(node, excludeCompoundAssignment) {
11991 return ts.isBinaryExpression(node)
11992 && (excludeCompoundAssignment
11993 ? node.operatorToken.kind === 59 /* EqualsToken */
11994 : isAssignmentOperator(node.operatorToken.kind))
11995 && ts.isLeftHandSideExpression(node.left);
11996 }
11997 ts.isAssignmentExpression = isAssignmentExpression;
11998 function isDestructuringAssignment(node) {
11999 if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
12000 var kind = node.left.kind;
12001 return kind === 188 /* ObjectLiteralExpression */
12002 || kind === 187 /* ArrayLiteralExpression */;
12003 }
12004 return false;
12005 }
12006 ts.isDestructuringAssignment = isDestructuringAssignment;
12007 function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
12008 return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
12009 }
12010 ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
12011 function isEntityNameExpression(node) {
12012 return node.kind === 72 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
12013 }
12014 ts.isEntityNameExpression = isEntityNameExpression;
12015 function isPropertyAccessEntityNameExpression(node) {
12016 return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression);
12017 }
12018 ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
12019 function isPrototypeAccess(node) {
12020 return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype";
12021 }
12022 ts.isPrototypeAccess = isPrototypeAccess;
12023 function isRightSideOfQualifiedNameOrPropertyAccess(node) {
12024 return (node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node) ||
12025 (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node);
12026 }
12027 ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
12028 function isEmptyObjectLiteral(expression) {
12029 return expression.kind === 188 /* ObjectLiteralExpression */ &&
12030 expression.properties.length === 0;
12031 }
12032 ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
12033 function isEmptyArrayLiteral(expression) {
12034 return expression.kind === 187 /* ArrayLiteralExpression */ &&
12035 expression.elements.length === 0;
12036 }
12037 ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
12038 function getLocalSymbolForExportDefault(symbol) {
12039 return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
12040 }
12041 ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
12042 function isExportDefaultSymbol(symbol) {
12043 return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */);
12044 }
12045 /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
12046 function tryExtractTSExtension(fileName) {
12047 return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
12048 }
12049 ts.tryExtractTSExtension = tryExtractTSExtension;
12050 /**
12051 * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
12052 * representing the UTF-8 encoding of the character, and return the expanded char code list.
12053 */
12054 function getExpandedCharCodes(input) {
12055 var output = [];
12056 var length = input.length;
12057 for (var i = 0; i < length; i++) {
12058 var charCode = input.charCodeAt(i);
12059 // handle utf8
12060 if (charCode < 0x80) {
12061 output.push(charCode);
12062 }
12063 else if (charCode < 0x800) {
12064 output.push((charCode >> 6) | 192);
12065 output.push((charCode & 63) | 128);
12066 }
12067 else if (charCode < 0x10000) {
12068 output.push((charCode >> 12) | 224);
12069 output.push(((charCode >> 6) & 63) | 128);
12070 output.push((charCode & 63) | 128);
12071 }
12072 else if (charCode < 0x20000) {
12073 output.push((charCode >> 18) | 240);
12074 output.push(((charCode >> 12) & 63) | 128);
12075 output.push(((charCode >> 6) & 63) | 128);
12076 output.push((charCode & 63) | 128);
12077 }
12078 else {
12079 ts.Debug.assert(false, "Unexpected code point");
12080 }
12081 }
12082 return output;
12083 }
12084 var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
12085 /**
12086 * Converts a string to a base-64 encoded ASCII string.
12087 */
12088 function convertToBase64(input) {
12089 var result = "";
12090 var charCodes = getExpandedCharCodes(input);
12091 var i = 0;
12092 var length = charCodes.length;
12093 var byte1, byte2, byte3, byte4;
12094 while (i < length) {
12095 // Convert every 6-bits in the input 3 character points
12096 // into a base64 digit
12097 byte1 = charCodes[i] >> 2;
12098 byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
12099 byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
12100 byte4 = charCodes[i + 2] & 63;
12101 // We are out of characters in the input, set the extra
12102 // digits to 64 (padding character).
12103 if (i + 1 >= length) {
12104 byte3 = byte4 = 64;
12105 }
12106 else if (i + 2 >= length) {
12107 byte4 = 64;
12108 }
12109 // Write to the output
12110 result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
12111 i += 3;
12112 }
12113 return result;
12114 }
12115 ts.convertToBase64 = convertToBase64;
12116 function getStringFromExpandedCharCodes(codes) {
12117 var output = "";
12118 var i = 0;
12119 var length = codes.length;
12120 while (i < length) {
12121 var charCode = codes[i];
12122 if (charCode < 0x80) {
12123 output += String.fromCharCode(charCode);
12124 i++;
12125 }
12126 else if ((charCode & 192) === 192) {
12127 var value = charCode & 63;
12128 i++;
12129 var nextCode = codes[i];
12130 while ((nextCode & 192) === 128) {
12131 value = (value << 6) | (nextCode & 63);
12132 i++;
12133 nextCode = codes[i];
12134 }
12135 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
12136 output += String.fromCharCode(value);
12137 }
12138 else {
12139 // We don't want to kill the process when decoding fails (due to a following char byte not
12140 // following a leading char), so we just print the (bad) value
12141 output += String.fromCharCode(charCode);
12142 i++;
12143 }
12144 }
12145 return output;
12146 }
12147 function base64encode(host, input) {
12148 if (host && host.base64encode) {
12149 return host.base64encode(input);
12150 }
12151 return convertToBase64(input);
12152 }
12153 ts.base64encode = base64encode;
12154 function base64decode(host, input) {
12155 if (host && host.base64decode) {
12156 return host.base64decode(input);
12157 }
12158 var length = input.length;
12159 var expandedCharCodes = [];
12160 var i = 0;
12161 while (i < length) {
12162 // Stop decoding once padding characters are present
12163 if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
12164 break;
12165 }
12166 // convert 4 input digits into three characters, ignoring padding characters at the end
12167 var ch1 = base64Digits.indexOf(input[i]);
12168 var ch2 = base64Digits.indexOf(input[i + 1]);
12169 var ch3 = base64Digits.indexOf(input[i + 2]);
12170 var ch4 = base64Digits.indexOf(input[i + 3]);
12171 var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
12172 var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
12173 var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
12174 if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
12175 expandedCharCodes.push(code1);
12176 }
12177 else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
12178 expandedCharCodes.push(code1, code2);
12179 }
12180 else {
12181 expandedCharCodes.push(code1, code2, code3);
12182 }
12183 i += 4;
12184 }
12185 return getStringFromExpandedCharCodes(expandedCharCodes);
12186 }
12187 ts.base64decode = base64decode;
12188 function readJson(path, host) {
12189 try {
12190 var jsonText = host.readFile(path);
12191 if (!jsonText)
12192 return {};
12193 var result = ts.parseConfigFileTextToJson(path, jsonText);
12194 if (result.error) {
12195 return {};
12196 }
12197 return result.config;
12198 }
12199 catch (e) {
12200 // gracefully handle if readFile fails or returns not JSON
12201 return {};
12202 }
12203 }
12204 ts.readJson = readJson;
12205 function directoryProbablyExists(directoryName, host) {
12206 // if host does not support 'directoryExists' assume that directory will exist
12207 return !host.directoryExists || host.directoryExists(directoryName);
12208 }
12209 ts.directoryProbablyExists = directoryProbablyExists;
12210 var carriageReturnLineFeed = "\r\n";
12211 var lineFeed = "\n";
12212 function getNewLineCharacter(options, getNewLine) {
12213 switch (options.newLine) {
12214 case 0 /* CarriageReturnLineFeed */:
12215 return carriageReturnLineFeed;
12216 case 1 /* LineFeed */:
12217 return lineFeed;
12218 }
12219 return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
12220 }
12221 ts.getNewLineCharacter = getNewLineCharacter;
12222 /**
12223 * Formats an enum value as a string for debugging and debug assertions.
12224 */
12225 function formatEnum(value, enumObject, isFlags) {
12226 if (value === void 0) { value = 0; }
12227 var members = getEnumMembers(enumObject);
12228 if (value === 0) {
12229 return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
12230 }
12231 if (isFlags) {
12232 var result = "";
12233 var remainingFlags = value;
12234 for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) {
12235 var _a = members[i], enumValue = _a[0], enumName = _a[1];
12236 if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) {
12237 remainingFlags &= ~enumValue;
12238 result = "" + enumName + (result ? ", " : "") + result;
12239 }
12240 }
12241 if (remainingFlags === 0) {
12242 return result;
12243 }
12244 }
12245 else {
12246 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
12247 var _b = members_1[_i], enumValue = _b[0], enumName = _b[1];
12248 if (enumValue === value) {
12249 return enumName;
12250 }
12251 }
12252 }
12253 return value.toString();
12254 }
12255 function getEnumMembers(enumObject) {
12256 var result = [];
12257 for (var name in enumObject) {
12258 var value = enumObject[name];
12259 if (typeof value === "number") {
12260 result.push([value, name]);
12261 }
12262 }
12263 return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
12264 }
12265 function formatSyntaxKind(kind) {
12266 return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
12267 }
12268 ts.formatSyntaxKind = formatSyntaxKind;
12269 function formatModifierFlags(flags) {
12270 return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
12271 }
12272 ts.formatModifierFlags = formatModifierFlags;
12273 function formatTransformFlags(flags) {
12274 return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
12275 }
12276 ts.formatTransformFlags = formatTransformFlags;
12277 function formatEmitFlags(flags) {
12278 return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
12279 }
12280 ts.formatEmitFlags = formatEmitFlags;
12281 function formatSymbolFlags(flags) {
12282 return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
12283 }
12284 ts.formatSymbolFlags = formatSymbolFlags;
12285 function formatTypeFlags(flags) {
12286 return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
12287 }
12288 ts.formatTypeFlags = formatTypeFlags;
12289 function formatObjectFlags(flags) {
12290 return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
12291 }
12292 ts.formatObjectFlags = formatObjectFlags;
12293 /**
12294 * Creates a new TextRange from the provided pos and end.
12295 *
12296 * @param pos The start position.
12297 * @param end The end position.
12298 */
12299 function createRange(pos, end) {
12300 if (end === void 0) { end = pos; }
12301 ts.Debug.assert(end >= pos || end === -1);
12302 return { pos: pos, end: end };
12303 }
12304 ts.createRange = createRange;
12305 /**
12306 * Creates a new TextRange from a provided range with a new end position.
12307 *
12308 * @param range A TextRange.
12309 * @param end The new end position.
12310 */
12311 function moveRangeEnd(range, end) {
12312 return createRange(range.pos, end);
12313 }
12314 ts.moveRangeEnd = moveRangeEnd;
12315 /**
12316 * Creates a new TextRange from a provided range with a new start position.
12317 *
12318 * @param range A TextRange.
12319 * @param pos The new Start position.
12320 */
12321 function moveRangePos(range, pos) {
12322 return createRange(pos, range.end);
12323 }
12324 ts.moveRangePos = moveRangePos;
12325 /**
12326 * Moves the start position of a range past any decorators.
12327 */
12328 function moveRangePastDecorators(node) {
12329 return node.decorators && node.decorators.length > 0
12330 ? moveRangePos(node, node.decorators.end)
12331 : node;
12332 }
12333 ts.moveRangePastDecorators = moveRangePastDecorators;
12334 /**
12335 * Moves the start position of a range past any decorators or modifiers.
12336 */
12337 function moveRangePastModifiers(node) {
12338 return node.modifiers && node.modifiers.length > 0
12339 ? moveRangePos(node, node.modifiers.end)
12340 : moveRangePastDecorators(node);
12341 }
12342 ts.moveRangePastModifiers = moveRangePastModifiers;
12343 /**
12344 * Determines whether a TextRange has the same start and end positions.
12345 *
12346 * @param range A TextRange.
12347 */
12348 function isCollapsedRange(range) {
12349 return range.pos === range.end;
12350 }
12351 ts.isCollapsedRange = isCollapsedRange;
12352 /**
12353 * Creates a new TextRange for a token at the provides start position.
12354 *
12355 * @param pos The start position.
12356 * @param token The token.
12357 */
12358 function createTokenRange(pos, token) {
12359 return createRange(pos, pos + ts.tokenToString(token).length);
12360 }
12361 ts.createTokenRange = createTokenRange;
12362 function rangeIsOnSingleLine(range, sourceFile) {
12363 return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
12364 }
12365 ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
12366 function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
12367 return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile);
12368 }
12369 ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
12370 function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
12371 return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
12372 }
12373 ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
12374 function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
12375 return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile);
12376 }
12377 ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
12378 function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
12379 return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile);
12380 }
12381 ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
12382 function positionsAreOnSameLine(pos1, pos2, sourceFile) {
12383 return pos1 === pos2 ||
12384 getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2);
12385 }
12386 ts.positionsAreOnSameLine = positionsAreOnSameLine;
12387 function getStartPositionOfRange(range, sourceFile) {
12388 return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
12389 }
12390 ts.getStartPositionOfRange = getStartPositionOfRange;
12391 /**
12392 * Determines whether a name was originally the declaration name of an enum or namespace
12393 * declaration.
12394 */
12395 function isDeclarationNameOfEnumOrNamespace(node) {
12396 var parseNode = ts.getParseTreeNode(node);
12397 if (parseNode) {
12398 switch (parseNode.parent.kind) {
12399 case 243 /* EnumDeclaration */:
12400 case 244 /* ModuleDeclaration */:
12401 return parseNode === parseNode.parent.name;
12402 }
12403 }
12404 return false;
12405 }
12406 ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
12407 function getInitializedVariables(node) {
12408 return ts.filter(node.declarations, isInitializedVariable);
12409 }
12410 ts.getInitializedVariables = getInitializedVariables;
12411 function isInitializedVariable(node) {
12412 return node.initializer !== undefined;
12413 }
12414 function isWatchSet(options) {
12415 // Firefox has Object.prototype.watch
12416 return options.watch && options.hasOwnProperty("watch");
12417 }
12418 ts.isWatchSet = isWatchSet;
12419 function closeFileWatcher(watcher) {
12420 watcher.close();
12421 }
12422 ts.closeFileWatcher = closeFileWatcher;
12423 function getCheckFlags(symbol) {
12424 return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
12425 }
12426 ts.getCheckFlags = getCheckFlags;
12427 function getDeclarationModifierFlagsFromSymbol(s) {
12428 if (s.valueDeclaration) {
12429 var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
12430 return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
12431 }
12432 if (getCheckFlags(s) & 6 /* Synthetic */) {
12433 var checkFlags = s.checkFlags;
12434 var accessModifier = checkFlags & 512 /* ContainsPrivate */ ? 8 /* Private */ :
12435 checkFlags & 128 /* ContainsPublic */ ? 4 /* Public */ :
12436 16 /* Protected */;
12437 var staticModifier = checkFlags & 1024 /* ContainsStatic */ ? 32 /* Static */ : 0;
12438 return accessModifier | staticModifier;
12439 }
12440 if (s.flags & 4194304 /* Prototype */) {
12441 return 4 /* Public */ | 32 /* Static */;
12442 }
12443 return 0;
12444 }
12445 ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
12446 function skipAlias(symbol, checker) {
12447 return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
12448 }
12449 ts.skipAlias = skipAlias;
12450 /** See comment on `declareModuleMember` in `binder.ts`. */
12451 function getCombinedLocalAndExportSymbolFlags(symbol) {
12452 return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
12453 }
12454 ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
12455 function isWriteOnlyAccess(node) {
12456 return accessKind(node) === 1 /* Write */;
12457 }
12458 ts.isWriteOnlyAccess = isWriteOnlyAccess;
12459 function isWriteAccess(node) {
12460 return accessKind(node) !== 0 /* Read */;
12461 }
12462 ts.isWriteAccess = isWriteAccess;
12463 var AccessKind;
12464 (function (AccessKind) {
12465 /** Only reads from a variable. */
12466 AccessKind[AccessKind["Read"] = 0] = "Read";
12467 /** Only writes to a variable without using the result. E.g.: `x++;`. */
12468 AccessKind[AccessKind["Write"] = 1] = "Write";
12469 /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
12470 AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
12471 })(AccessKind || (AccessKind = {}));
12472 function accessKind(node) {
12473 var parent = node.parent;
12474 if (!parent)
12475 return 0 /* Read */;
12476 switch (parent.kind) {
12477 case 195 /* ParenthesizedExpression */:
12478 return accessKind(parent);
12479 case 203 /* PostfixUnaryExpression */:
12480 case 202 /* PrefixUnaryExpression */:
12481 var operator = parent.operator;
12482 return operator === 44 /* PlusPlusToken */ || operator === 45 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
12483 case 204 /* BinaryExpression */:
12484 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
12485 return left === node && isAssignmentOperator(operatorToken.kind) ?
12486 operatorToken.kind === 59 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
12487 : 0 /* Read */;
12488 case 189 /* PropertyAccessExpression */:
12489 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
12490 case 275 /* PropertyAssignment */: {
12491 var parentAccess = accessKind(parent.parent);
12492 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
12493 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
12494 }
12495 case 276 /* ShorthandPropertyAssignment */:
12496 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
12497 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
12498 case 187 /* ArrayLiteralExpression */:
12499 return accessKind(parent);
12500 default:
12501 return 0 /* Read */;
12502 }
12503 function writeOrReadWrite() {
12504 // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
12505 return parent.parent && skipParenthesesUp(parent.parent).kind === 221 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
12506 }
12507 }
12508 function reverseAccessKind(a) {
12509 switch (a) {
12510 case 0 /* Read */:
12511 return 1 /* Write */;
12512 case 1 /* Write */:
12513 return 0 /* Read */;
12514 case 2 /* ReadWrite */:
12515 return 2 /* ReadWrite */;
12516 default:
12517 return ts.Debug.assertNever(a);
12518 }
12519 }
12520 function compareDataObjects(dst, src) {
12521 if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
12522 return false;
12523 }
12524 for (var e in dst) {
12525 if (typeof dst[e] === "object") {
12526 if (!compareDataObjects(dst[e], src[e])) {
12527 return false;
12528 }
12529 }
12530 else if (typeof dst[e] !== "function") {
12531 if (dst[e] !== src[e]) {
12532 return false;
12533 }
12534 }
12535 }
12536 return true;
12537 }
12538 ts.compareDataObjects = compareDataObjects;
12539 /**
12540 * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
12541 */
12542 function clearMap(map, onDeleteValue) {
12543 // Remove all
12544 map.forEach(onDeleteValue);
12545 map.clear();
12546 }
12547 ts.clearMap = clearMap;
12548 /**
12549 * Mutates the map with newMap such that keys in map will be same as newMap.
12550 */
12551 function mutateMap(map, newMap, options) {
12552 var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
12553 // Needs update
12554 map.forEach(function (existingValue, key) {
12555 var valueInNewMap = newMap.get(key);
12556 // Not present any more in new map, remove it
12557 if (valueInNewMap === undefined) {
12558 map.delete(key);
12559 onDeleteValue(existingValue, key);
12560 }
12561 // If present notify about existing values
12562 else if (onExistingValue) {
12563 onExistingValue(existingValue, valueInNewMap, key);
12564 }
12565 });
12566 // Add new values that are not already present
12567 newMap.forEach(function (valueInNewMap, key) {
12568 if (!map.has(key)) {
12569 // New values
12570 map.set(key, createNewValue(key, valueInNewMap));
12571 }
12572 });
12573 }
12574 ts.mutateMap = mutateMap;
12575 /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */
12576 function forEachAncestorDirectory(directory, callback) {
12577 while (true) {
12578 var result = callback(directory);
12579 if (result !== undefined) {
12580 return result;
12581 }
12582 var parentPath = ts.getDirectoryPath(directory);
12583 if (parentPath === directory) {
12584 return undefined;
12585 }
12586 directory = parentPath;
12587 }
12588 }
12589 ts.forEachAncestorDirectory = forEachAncestorDirectory;
12590 // Return true if the given type is the constructor type for an abstract class
12591 function isAbstractConstructorType(type) {
12592 return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
12593 }
12594 ts.isAbstractConstructorType = isAbstractConstructorType;
12595 function isAbstractConstructorSymbol(symbol) {
12596 if (symbol.flags & 32 /* Class */) {
12597 var declaration = getClassLikeDeclarationOfSymbol(symbol);
12598 return !!declaration && hasModifier(declaration, 128 /* Abstract */);
12599 }
12600 return false;
12601 }
12602 ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
12603 function getClassLikeDeclarationOfSymbol(symbol) {
12604 return ts.find(symbol.declarations, ts.isClassLike);
12605 }
12606 ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
12607 function getObjectFlags(type) {
12608 return type.flags & 3899392 /* ObjectFlagsType */ ? type.objectFlags : 0;
12609 }
12610 ts.getObjectFlags = getObjectFlags;
12611 function typeHasCallOrConstructSignatures(type, checker) {
12612 return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
12613 }
12614 ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
12615 function forSomeAncestorDirectory(directory, callback) {
12616 return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
12617 }
12618 ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
12619 function isUMDExportSymbol(symbol) {
12620 return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
12621 }
12622 ts.isUMDExportSymbol = isUMDExportSymbol;
12623 function showModuleSpecifier(_a) {
12624 var moduleSpecifier = _a.moduleSpecifier;
12625 return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
12626 }
12627 ts.showModuleSpecifier = showModuleSpecifier;
12628 function getLastChild(node) {
12629 var lastChild;
12630 ts.forEachChild(node, function (child) {
12631 if (nodeIsPresent(child))
12632 lastChild = child;
12633 }, function (children) {
12634 // As an optimization, jump straight to the end of the list.
12635 for (var i = children.length - 1; i >= 0; i--) {
12636 if (nodeIsPresent(children[i])) {
12637 lastChild = children[i];
12638 break;
12639 }
12640 }
12641 });
12642 return lastChild;
12643 }
12644 ts.getLastChild = getLastChild;
12645 function addToSeen(seen, key, value) {
12646 if (value === void 0) { value = true; }
12647 key = String(key);
12648 if (seen.has(key)) {
12649 return false;
12650 }
12651 seen.set(key, value);
12652 return true;
12653 }
12654 ts.addToSeen = addToSeen;
12655 function isObjectTypeDeclaration(node) {
12656 return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
12657 }
12658 ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
12659 function isTypeNodeKind(kind) {
12660 return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
12661 || kind === 120 /* AnyKeyword */
12662 || kind === 143 /* UnknownKeyword */
12663 || kind === 135 /* NumberKeyword */
12664 || kind === 146 /* BigIntKeyword */
12665 || kind === 136 /* ObjectKeyword */
12666 || kind === 123 /* BooleanKeyword */
12667 || kind === 138 /* StringKeyword */
12668 || kind === 139 /* SymbolKeyword */
12669 || kind === 100 /* ThisKeyword */
12670 || kind === 106 /* VoidKeyword */
12671 || kind === 141 /* UndefinedKeyword */
12672 || kind === 96 /* NullKeyword */
12673 || kind === 132 /* NeverKeyword */
12674 || kind === 211 /* ExpressionWithTypeArguments */
12675 || kind === 289 /* JSDocAllType */
12676 || kind === 290 /* JSDocUnknownType */
12677 || kind === 291 /* JSDocNullableType */
12678 || kind === 292 /* JSDocNonNullableType */
12679 || kind === 293 /* JSDocOptionalType */
12680 || kind === 294 /* JSDocFunctionType */
12681 || kind === 295 /* JSDocVariadicType */;
12682 }
12683 ts.isTypeNodeKind = isTypeNodeKind;
12684 function isAccessExpression(node) {
12685 return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
12686 }
12687 ts.isAccessExpression = isAccessExpression;
12688 function isBundleFileTextLike(section) {
12689 switch (section.kind) {
12690 case "text" /* Text */:
12691 case "internal" /* Internal */:
12692 return true;
12693 default:
12694 return false;
12695 }
12696 }
12697 ts.isBundleFileTextLike = isBundleFileTextLike;
12698})(ts || (ts = {}));
12699(function (ts) {
12700 function getDefaultLibFileName(options) {
12701 switch (options.target) {
12702 case 7 /* ESNext */:
12703 return "lib.esnext.full.d.ts";
12704 case 6 /* ES2019 */:
12705 return "lib.es2019.full.d.ts";
12706 case 5 /* ES2018 */:
12707 return "lib.es2018.full.d.ts";
12708 case 4 /* ES2017 */:
12709 return "lib.es2017.full.d.ts";
12710 case 3 /* ES2016 */:
12711 return "lib.es2016.full.d.ts";
12712 case 2 /* ES2015 */:
12713 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
12714 default:
12715 return "lib.d.ts";
12716 }
12717 }
12718 ts.getDefaultLibFileName = getDefaultLibFileName;
12719 function textSpanEnd(span) {
12720 return span.start + span.length;
12721 }
12722 ts.textSpanEnd = textSpanEnd;
12723 function textSpanIsEmpty(span) {
12724 return span.length === 0;
12725 }
12726 ts.textSpanIsEmpty = textSpanIsEmpty;
12727 function textSpanContainsPosition(span, position) {
12728 return position >= span.start && position < textSpanEnd(span);
12729 }
12730 ts.textSpanContainsPosition = textSpanContainsPosition;
12731 /* @internal */
12732 function textRangeContainsPositionInclusive(span, position) {
12733 return position >= span.pos && position <= span.end;
12734 }
12735 ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
12736 // Returns true if 'span' contains 'other'.
12737 function textSpanContainsTextSpan(span, other) {
12738 return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
12739 }
12740 ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
12741 function textSpanOverlapsWith(span, other) {
12742 return textSpanOverlap(span, other) !== undefined;
12743 }
12744 ts.textSpanOverlapsWith = textSpanOverlapsWith;
12745 function textSpanOverlap(span1, span2) {
12746 var overlap = textSpanIntersection(span1, span2);
12747 return overlap && overlap.length === 0 ? undefined : overlap;
12748 }
12749 ts.textSpanOverlap = textSpanOverlap;
12750 function textSpanIntersectsWithTextSpan(span, other) {
12751 return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
12752 }
12753 ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
12754 function textSpanIntersectsWith(span, start, length) {
12755 return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
12756 }
12757 ts.textSpanIntersectsWith = textSpanIntersectsWith;
12758 function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
12759 var end1 = start1 + length1;
12760 var end2 = start2 + length2;
12761 return start2 <= end1 && end2 >= start1;
12762 }
12763 ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
12764 function textSpanIntersectsWithPosition(span, position) {
12765 return position <= textSpanEnd(span) && position >= span.start;
12766 }
12767 ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
12768 function textSpanIntersection(span1, span2) {
12769 var start = Math.max(span1.start, span2.start);
12770 var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
12771 return start <= end ? createTextSpanFromBounds(start, end) : undefined;
12772 }
12773 ts.textSpanIntersection = textSpanIntersection;
12774 function createTextSpan(start, length) {
12775 if (start < 0) {
12776 throw new Error("start < 0");
12777 }
12778 if (length < 0) {
12779 throw new Error("length < 0");
12780 }
12781 return { start: start, length: length };
12782 }
12783 ts.createTextSpan = createTextSpan;
12784 function createTextSpanFromBounds(start, end) {
12785 return createTextSpan(start, end - start);
12786 }
12787 ts.createTextSpanFromBounds = createTextSpanFromBounds;
12788 function textChangeRangeNewSpan(range) {
12789 return createTextSpan(range.span.start, range.newLength);
12790 }
12791 ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
12792 function textChangeRangeIsUnchanged(range) {
12793 return textSpanIsEmpty(range.span) && range.newLength === 0;
12794 }
12795 ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
12796 function createTextChangeRange(span, newLength) {
12797 if (newLength < 0) {
12798 throw new Error("newLength < 0");
12799 }
12800 return { span: span, newLength: newLength };
12801 }
12802 ts.createTextChangeRange = createTextChangeRange;
12803 ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0);
12804 /**
12805 * Called to merge all the changes that occurred across several versions of a script snapshot
12806 * into a single change. i.e. if a user keeps making successive edits to a script we will
12807 * have a text change from V1 to V2, V2 to V3, ..., Vn.
12808 *
12809 * This function will then merge those changes into a single change range valid between V1 and
12810 * Vn.
12811 */
12812 function collapseTextChangeRangesAcrossMultipleVersions(changes) {
12813 if (changes.length === 0) {
12814 return ts.unchangedTextChangeRange;
12815 }
12816 if (changes.length === 1) {
12817 return changes[0];
12818 }
12819 // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
12820 // as it makes things much easier to reason about.
12821 var change0 = changes[0];
12822 var oldStartN = change0.span.start;
12823 var oldEndN = textSpanEnd(change0.span);
12824 var newEndN = oldStartN + change0.newLength;
12825 for (var i = 1; i < changes.length; i++) {
12826 var nextChange = changes[i];
12827 // Consider the following case:
12828 // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting
12829 // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }.
12830 // i.e. the span starting at 30 with length 30 is increased to length 40.
12831 //
12832 // 0 10 20 30 40 50 60 70 80 90 100
12833 // -------------------------------------------------------------------------------------------------------
12834 // | /
12835 // | /----
12836 // T1 | /----
12837 // | /----
12838 // | /----
12839 // -------------------------------------------------------------------------------------------------------
12840 // | \
12841 // | \
12842 // T2 | \
12843 // | \
12844 // | \
12845 // -------------------------------------------------------------------------------------------------------
12846 //
12847 // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial
12848 // it's just the min of the old and new starts. i.e.:
12849 //
12850 // 0 10 20 30 40 50 60 70 80 90 100
12851 // ------------------------------------------------------------*------------------------------------------
12852 // | /
12853 // | /----
12854 // T1 | /----
12855 // | /----
12856 // | /----
12857 // ----------------------------------------$-------------------$------------------------------------------
12858 // . | \
12859 // . | \
12860 // T2 . | \
12861 // . | \
12862 // . | \
12863 // ----------------------------------------------------------------------*--------------------------------
12864 //
12865 // (Note the dots represent the newly inferred start.
12866 // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the
12867 // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
12868 // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that
12869 // means:
12870 //
12871 // 0 10 20 30 40 50 60 70 80 90 100
12872 // --------------------------------------------------------------------------------*----------------------
12873 // | /
12874 // | /----
12875 // T1 | /----
12876 // | /----
12877 // | /----
12878 // ------------------------------------------------------------$------------------------------------------
12879 // . | \
12880 // . | \
12881 // T2 . | \
12882 // . | \
12883 // . | \
12884 // ----------------------------------------------------------------------*--------------------------------
12885 //
12886 // In other words (in this case), we're recognizing that the second edit happened after where the first edit
12887 // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started
12888 // that's the same as if we started at char 80 instead of 60.
12889 //
12890 // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather
12891 // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
12892 // first.
12893 //
12894 // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
12895 // semantics: { { start: 10, length: 70 }, newLength: 60 }
12896 //
12897 // The math then works out as follows.
12898 // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
12899 // final result like so:
12900 //
12901 // {
12902 // oldStart3: Min(oldStart1, oldStart2),
12903 // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
12904 // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
12905 // }
12906 var oldStart1 = oldStartN;
12907 var oldEnd1 = oldEndN;
12908 var newEnd1 = newEndN;
12909 var oldStart2 = nextChange.span.start;
12910 var oldEnd2 = textSpanEnd(nextChange.span);
12911 var newEnd2 = oldStart2 + nextChange.newLength;
12912 oldStartN = Math.min(oldStart1, oldStart2);
12913 oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
12914 newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
12915 }
12916 return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
12917 }
12918 ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
12919 function getTypeParameterOwner(d) {
12920 if (d && d.kind === 150 /* TypeParameter */) {
12921 for (var current = d; current; current = current.parent) {
12922 if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 241 /* InterfaceDeclaration */) {
12923 return current;
12924 }
12925 }
12926 }
12927 }
12928 ts.getTypeParameterOwner = getTypeParameterOwner;
12929 function isParameterPropertyDeclaration(node) {
12930 return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 157 /* Constructor */;
12931 }
12932 ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
12933 function isEmptyBindingPattern(node) {
12934 if (ts.isBindingPattern(node)) {
12935 return ts.every(node.elements, isEmptyBindingElement);
12936 }
12937 return false;
12938 }
12939 ts.isEmptyBindingPattern = isEmptyBindingPattern;
12940 function isEmptyBindingElement(node) {
12941 if (ts.isOmittedExpression(node)) {
12942 return true;
12943 }
12944 return isEmptyBindingPattern(node.name);
12945 }
12946 ts.isEmptyBindingElement = isEmptyBindingElement;
12947 function walkUpBindingElementsAndPatterns(binding) {
12948 var node = binding.parent;
12949 while (ts.isBindingElement(node.parent)) {
12950 node = node.parent.parent;
12951 }
12952 return node.parent;
12953 }
12954 ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
12955 function getCombinedFlags(node, getFlags) {
12956 if (ts.isBindingElement(node)) {
12957 node = walkUpBindingElementsAndPatterns(node);
12958 }
12959 var flags = getFlags(node);
12960 if (node.kind === 237 /* VariableDeclaration */) {
12961 node = node.parent;
12962 }
12963 if (node && node.kind === 238 /* VariableDeclarationList */) {
12964 flags |= getFlags(node);
12965 node = node.parent;
12966 }
12967 if (node && node.kind === 219 /* VariableStatement */) {
12968 flags |= getFlags(node);
12969 }
12970 return flags;
12971 }
12972 function getCombinedModifierFlags(node) {
12973 return getCombinedFlags(node, ts.getModifierFlags);
12974 }
12975 ts.getCombinedModifierFlags = getCombinedModifierFlags;
12976 // Returns the node flags for this node and all relevant parent nodes. This is done so that
12977 // nodes like variable declarations and binding elements can returned a view of their flags
12978 // that includes the modifiers from their container. i.e. flags like export/declare aren't
12979 // stored on the variable declaration directly, but on the containing variable statement
12980 // (if it has one). Similarly, flags for let/const are store on the variable declaration
12981 // list. By calling this function, all those flags are combined so that the client can treat
12982 // the node as if it actually had those flags.
12983 function getCombinedNodeFlags(node) {
12984 return getCombinedFlags(node, function (n) { return n.flags; });
12985 }
12986 ts.getCombinedNodeFlags = getCombinedNodeFlags;
12987 /**
12988 * Checks to see if the locale is in the appropriate format,
12989 * and if it is, attempts to set the appropriate language.
12990 */
12991 function validateLocaleAndSetLanguage(locale, sys, errors) {
12992 var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
12993 if (!matchResult) {
12994 if (errors) {
12995 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
12996 }
12997 return;
12998 }
12999 var language = matchResult[1];
13000 var territory = matchResult[3];
13001 // First try the entire locale, then fall back to just language if that's all we have.
13002 // Either ways do not fail, and fallback to the English diagnostic strings.
13003 if (!trySetLanguageAndTerritory(language, territory, errors)) {
13004 trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
13005 }
13006 // Set the UI locale for string collation
13007 ts.setUILocale(locale);
13008 function trySetLanguageAndTerritory(language, territory, errors) {
13009 var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
13010 var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
13011 var filePath = ts.combinePaths(containingDirectoryPath, language);
13012 if (territory) {
13013 filePath = filePath + "-" + territory;
13014 }
13015 filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
13016 if (!sys.fileExists(filePath)) {
13017 return false;
13018 }
13019 // TODO: Add codePage support for readFile?
13020 var fileContents = "";
13021 try {
13022 fileContents = sys.readFile(filePath);
13023 }
13024 catch (e) {
13025 if (errors) {
13026 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
13027 }
13028 return false;
13029 }
13030 try {
13031 // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!)
13032 ts.localizedDiagnosticMessages = JSON.parse(fileContents);
13033 }
13034 catch (_a) {
13035 if (errors) {
13036 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
13037 }
13038 return false;
13039 }
13040 return true;
13041 }
13042 }
13043 ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
13044 function getOriginalNode(node, nodeTest) {
13045 if (node) {
13046 while (node.original !== undefined) {
13047 node = node.original;
13048 }
13049 }
13050 return !nodeTest || nodeTest(node) ? node : undefined;
13051 }
13052 ts.getOriginalNode = getOriginalNode;
13053 /**
13054 * Gets a value indicating whether a node originated in the parse tree.
13055 *
13056 * @param node The node to test.
13057 */
13058 function isParseTreeNode(node) {
13059 return (node.flags & 8 /* Synthesized */) === 0;
13060 }
13061 ts.isParseTreeNode = isParseTreeNode;
13062 function getParseTreeNode(node, nodeTest) {
13063 if (node === undefined || isParseTreeNode(node)) {
13064 return node;
13065 }
13066 node = getOriginalNode(node);
13067 if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
13068 return node;
13069 }
13070 return undefined;
13071 }
13072 ts.getParseTreeNode = getParseTreeNode;
13073 /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
13074 function escapeLeadingUnderscores(identifier) {
13075 return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
13076 }
13077 ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
13078 /**
13079 * Remove extra underscore from escaped identifier text content.
13080 *
13081 * @param identifier The escaped identifier text.
13082 * @returns The unescaped identifier text.
13083 */
13084 function unescapeLeadingUnderscores(identifier) {
13085 var id = identifier;
13086 return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
13087 }
13088 ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
13089 function idText(identifier) {
13090 return unescapeLeadingUnderscores(identifier.escapedText);
13091 }
13092 ts.idText = idText;
13093 function symbolName(symbol) {
13094 return unescapeLeadingUnderscores(symbol.escapedName);
13095 }
13096 ts.symbolName = symbolName;
13097 /**
13098 * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
13099 * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
13100 * will be merged with)
13101 */
13102 function nameForNamelessJSDocTypedef(declaration) {
13103 var hostNode = declaration.parent.parent;
13104 if (!hostNode) {
13105 return undefined;
13106 }
13107 // Covers classes, functions - any named declaration host node
13108 if (ts.isDeclaration(hostNode)) {
13109 return getDeclarationIdentifier(hostNode);
13110 }
13111 // Covers remaining cases (returning undefined if none match).
13112 switch (hostNode.kind) {
13113 case 219 /* VariableStatement */:
13114 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
13115 return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
13116 }
13117 break;
13118 case 221 /* ExpressionStatement */:
13119 var expr = hostNode.expression;
13120 switch (expr.kind) {
13121 case 189 /* PropertyAccessExpression */:
13122 return expr.name;
13123 case 190 /* ElementAccessExpression */:
13124 var arg = expr.argumentExpression;
13125 if (ts.isIdentifier(arg)) {
13126 return arg;
13127 }
13128 }
13129 break;
13130 case 195 /* ParenthesizedExpression */: {
13131 return getDeclarationIdentifier(hostNode.expression);
13132 }
13133 case 233 /* LabeledStatement */: {
13134 if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) {
13135 return getDeclarationIdentifier(hostNode.statement);
13136 }
13137 break;
13138 }
13139 }
13140 }
13141 function getDeclarationIdentifier(node) {
13142 var name = getNameOfDeclaration(node);
13143 return name && ts.isIdentifier(name) ? name : undefined;
13144 }
13145 function getNameOfJSDocTypedef(declaration) {
13146 return declaration.name || nameForNamelessJSDocTypedef(declaration);
13147 }
13148 ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
13149 /** @internal */
13150 function isNamedDeclaration(node) {
13151 return !!node.name; // A 'name' property should always be a DeclarationName.
13152 }
13153 ts.isNamedDeclaration = isNamedDeclaration;
13154 /** @internal */
13155 function getNonAssignedNameOfDeclaration(declaration) {
13156 switch (declaration.kind) {
13157 case 72 /* Identifier */:
13158 return declaration;
13159 case 310 /* JSDocPropertyTag */:
13160 case 304 /* JSDocParameterTag */: {
13161 var name = declaration.name;
13162 if (name.kind === 148 /* QualifiedName */) {
13163 return name.right;
13164 }
13165 break;
13166 }
13167 case 191 /* CallExpression */:
13168 case 204 /* BinaryExpression */: {
13169 var expr = declaration;
13170 switch (ts.getAssignmentDeclarationKind(expr)) {
13171 case 1 /* ExportsProperty */:
13172 case 4 /* ThisProperty */:
13173 case 5 /* Property */:
13174 case 3 /* PrototypeProperty */:
13175 return expr.left.name;
13176 case 7 /* ObjectDefinePropertyValue */:
13177 case 8 /* ObjectDefinePropertyExports */:
13178 case 9 /* ObjectDefinePrototypeProperty */:
13179 return expr.arguments[1];
13180 default:
13181 return undefined;
13182 }
13183 }
13184 case 309 /* JSDocTypedefTag */:
13185 return getNameOfJSDocTypedef(declaration);
13186 case 254 /* ExportAssignment */: {
13187 var expression = declaration.expression;
13188 return ts.isIdentifier(expression) ? expression : undefined;
13189 }
13190 }
13191 return declaration.name;
13192 }
13193 ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
13194 function getNameOfDeclaration(declaration) {
13195 if (declaration === undefined)
13196 return undefined;
13197 return getNonAssignedNameOfDeclaration(declaration) ||
13198 (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
13199 }
13200 ts.getNameOfDeclaration = getNameOfDeclaration;
13201 function getAssignedName(node) {
13202 if (!node.parent) {
13203 return undefined;
13204 }
13205 else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) {
13206 return node.parent.name;
13207 }
13208 else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) {
13209 if (ts.isIdentifier(node.parent.left)) {
13210 return node.parent.left;
13211 }
13212 else if (ts.isPropertyAccessExpression(node.parent.left)) {
13213 return node.parent.left.name;
13214 }
13215 }
13216 }
13217 /**
13218 * Gets the JSDoc parameter tags for the node if present.
13219 *
13220 * @remarks Returns any JSDoc param tag whose name matches the provided
13221 * parameter, whether a param tag on a containing function
13222 * expression, or a param tag on a variable declaration whose
13223 * initializer is the containing function. The tags closest to the
13224 * node are returned first, so in the previous example, the param
13225 * tag on the containing function expression would be first.
13226 *
13227 * For binding patterns, parameter tags are matched by position.
13228 */
13229 function getJSDocParameterTags(param) {
13230 if (param.name) {
13231 if (ts.isIdentifier(param.name)) {
13232 var name_1 = param.name.escapedText;
13233 return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; });
13234 }
13235 else {
13236 var i = param.parent.parameters.indexOf(param);
13237 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
13238 var paramTags = getJSDocTags(param.parent).filter(ts.isJSDocParameterTag);
13239 if (i < paramTags.length) {
13240 return [paramTags[i]];
13241 }
13242 }
13243 }
13244 // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
13245 return ts.emptyArray;
13246 }
13247 ts.getJSDocParameterTags = getJSDocParameterTags;
13248 /**
13249 * Gets the JSDoc type parameter tags for the node if present.
13250 *
13251 * @remarks Returns any JSDoc template tag whose names match the provided
13252 * parameter, whether a template tag on a containing function
13253 * expression, or a template tag on a variable declaration whose
13254 * initializer is the containing function. The tags closest to the
13255 * node are returned first, so in the previous example, the template
13256 * tag on the containing function expression would be first.
13257 */
13258 function getJSDocTypeParameterTags(param) {
13259 var name = param.name.escapedText;
13260 return getJSDocTags(param.parent).filter(function (tag) {
13261 return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
13262 });
13263 }
13264 ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
13265 /**
13266 * Return true if the node has JSDoc parameter tags.
13267 *
13268 * @remarks Includes parameter tags that are not directly on the node,
13269 * for example on a variable declaration whose initializer is a function expression.
13270 */
13271 function hasJSDocParameterTags(node) {
13272 return !!getFirstJSDocTag(node, ts.isJSDocParameterTag);
13273 }
13274 ts.hasJSDocParameterTags = hasJSDocParameterTags;
13275 /** Gets the JSDoc augments tag for the node if present */
13276 function getJSDocAugmentsTag(node) {
13277 return getFirstJSDocTag(node, ts.isJSDocAugmentsTag);
13278 }
13279 ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
13280 /** Gets the JSDoc class tag for the node if present */
13281 function getJSDocClassTag(node) {
13282 return getFirstJSDocTag(node, ts.isJSDocClassTag);
13283 }
13284 ts.getJSDocClassTag = getJSDocClassTag;
13285 /** Gets the JSDoc enum tag for the node if present */
13286 function getJSDocEnumTag(node) {
13287 return getFirstJSDocTag(node, ts.isJSDocEnumTag);
13288 }
13289 ts.getJSDocEnumTag = getJSDocEnumTag;
13290 /** Gets the JSDoc this tag for the node if present */
13291 function getJSDocThisTag(node) {
13292 return getFirstJSDocTag(node, ts.isJSDocThisTag);
13293 }
13294 ts.getJSDocThisTag = getJSDocThisTag;
13295 /** Gets the JSDoc return tag for the node if present */
13296 function getJSDocReturnTag(node) {
13297 return getFirstJSDocTag(node, ts.isJSDocReturnTag);
13298 }
13299 ts.getJSDocReturnTag = getJSDocReturnTag;
13300 /** Gets the JSDoc template tag for the node if present */
13301 function getJSDocTemplateTag(node) {
13302 return getFirstJSDocTag(node, ts.isJSDocTemplateTag);
13303 }
13304 ts.getJSDocTemplateTag = getJSDocTemplateTag;
13305 /** Gets the JSDoc type tag for the node if present and valid */
13306 function getJSDocTypeTag(node) {
13307 // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
13308 var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
13309 if (tag && tag.typeExpression && tag.typeExpression.type) {
13310 return tag;
13311 }
13312 return undefined;
13313 }
13314 ts.getJSDocTypeTag = getJSDocTypeTag;
13315 /**
13316 * Gets the type node for the node if provided via JSDoc.
13317 *
13318 * @remarks The search includes any JSDoc param tag that relates
13319 * to the provided parameter, for example a type tag on the
13320 * parameter itself, or a param tag on a containing function
13321 * expression, or a param tag on a variable declaration whose
13322 * initializer is the containing function. The tags closest to the
13323 * node are examined first, so in the previous example, the type
13324 * tag directly on the node would be returned.
13325 */
13326 function getJSDocType(node) {
13327 var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
13328 if (!tag && ts.isParameter(node)) {
13329 tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
13330 }
13331 return tag && tag.typeExpression && tag.typeExpression.type;
13332 }
13333 ts.getJSDocType = getJSDocType;
13334 /**
13335 * Gets the return type node for the node if provided via JSDoc return tag or type tag.
13336 *
13337 * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
13338 * gets the type from inside the braces, after the fat arrow, etc.
13339 */
13340 function getJSDocReturnType(node) {
13341 var returnTag = getJSDocReturnTag(node);
13342 if (returnTag && returnTag.typeExpression) {
13343 return returnTag.typeExpression.type;
13344 }
13345 var typeTag = getJSDocTypeTag(node);
13346 if (typeTag && typeTag.typeExpression) {
13347 var type = typeTag.typeExpression.type;
13348 if (ts.isTypeLiteralNode(type)) {
13349 var sig = ts.find(type.members, ts.isCallSignatureDeclaration);
13350 return sig && sig.type;
13351 }
13352 if (ts.isFunctionTypeNode(type)) {
13353 return type.type;
13354 }
13355 }
13356 }
13357 ts.getJSDocReturnType = getJSDocReturnType;
13358 /** Get all JSDoc tags related to a node, including those on parent nodes. */
13359 function getJSDocTags(node) {
13360 var tags = node.jsDocCache;
13361 // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
13362 if (tags === undefined) {
13363 var comments = ts.getJSDocCommentsAndTags(node);
13364 ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
13365 node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
13366 }
13367 return tags;
13368 }
13369 ts.getJSDocTags = getJSDocTags;
13370 /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
13371 function getFirstJSDocTag(node, predicate) {
13372 return ts.find(getJSDocTags(node), predicate);
13373 }
13374 /** Gets all JSDoc tags of a specified kind, or undefined if not present. */
13375 function getAllJSDocTagsOfKind(node, kind) {
13376 return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
13377 }
13378 ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
13379 /**
13380 * Gets the effective type parameters. If the node was parsed in a
13381 * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
13382 */
13383 function getEffectiveTypeParameterDeclarations(node) {
13384 if (ts.isJSDocSignature(node)) {
13385 return ts.emptyArray;
13386 }
13387 if (ts.isJSDocTypeAlias(node)) {
13388 ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
13389 return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
13390 }
13391 if (node.typeParameters) {
13392 return node.typeParameters;
13393 }
13394 if (ts.isInJSFile(node)) {
13395 var decls = ts.getJSDocTypeParameterDeclarations(node);
13396 if (decls.length) {
13397 return decls;
13398 }
13399 var typeTag = getJSDocType(node);
13400 if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
13401 return typeTag.typeParameters;
13402 }
13403 }
13404 return ts.emptyArray;
13405 }
13406 ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
13407 function getEffectiveConstraintOfTypeParameter(node) {
13408 return node.constraint ? node.constraint
13409 : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0]
13410 ? node.parent.constraint
13411 : undefined;
13412 }
13413 ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
13414})(ts || (ts = {}));
13415// Simple node tests of the form `node.kind === SyntaxKind.Foo`.
13416(function (ts) {
13417 // Literals
13418 function isNumericLiteral(node) {
13419 return node.kind === 8 /* NumericLiteral */;
13420 }
13421 ts.isNumericLiteral = isNumericLiteral;
13422 function isBigIntLiteral(node) {
13423 return node.kind === 9 /* BigIntLiteral */;
13424 }
13425 ts.isBigIntLiteral = isBigIntLiteral;
13426 function isStringLiteral(node) {
13427 return node.kind === 10 /* StringLiteral */;
13428 }
13429 ts.isStringLiteral = isStringLiteral;
13430 function isJsxText(node) {
13431 return node.kind === 11 /* JsxText */;
13432 }
13433 ts.isJsxText = isJsxText;
13434 function isRegularExpressionLiteral(node) {
13435 return node.kind === 13 /* RegularExpressionLiteral */;
13436 }
13437 ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
13438 function isNoSubstitutionTemplateLiteral(node) {
13439 return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
13440 }
13441 ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
13442 // Pseudo-literals
13443 function isTemplateHead(node) {
13444 return node.kind === 15 /* TemplateHead */;
13445 }
13446 ts.isTemplateHead = isTemplateHead;
13447 function isTemplateMiddle(node) {
13448 return node.kind === 16 /* TemplateMiddle */;
13449 }
13450 ts.isTemplateMiddle = isTemplateMiddle;
13451 function isTemplateTail(node) {
13452 return node.kind === 17 /* TemplateTail */;
13453 }
13454 ts.isTemplateTail = isTemplateTail;
13455 function isIdentifier(node) {
13456 return node.kind === 72 /* Identifier */;
13457 }
13458 ts.isIdentifier = isIdentifier;
13459 // Names
13460 function isQualifiedName(node) {
13461 return node.kind === 148 /* QualifiedName */;
13462 }
13463 ts.isQualifiedName = isQualifiedName;
13464 function isComputedPropertyName(node) {
13465 return node.kind === 149 /* ComputedPropertyName */;
13466 }
13467 ts.isComputedPropertyName = isComputedPropertyName;
13468 // Signature elements
13469 function isTypeParameterDeclaration(node) {
13470 return node.kind === 150 /* TypeParameter */;
13471 }
13472 ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
13473 function isParameter(node) {
13474 return node.kind === 151 /* Parameter */;
13475 }
13476 ts.isParameter = isParameter;
13477 function isDecorator(node) {
13478 return node.kind === 152 /* Decorator */;
13479 }
13480 ts.isDecorator = isDecorator;
13481 // TypeMember
13482 function isPropertySignature(node) {
13483 return node.kind === 153 /* PropertySignature */;
13484 }
13485 ts.isPropertySignature = isPropertySignature;
13486 function isPropertyDeclaration(node) {
13487 return node.kind === 154 /* PropertyDeclaration */;
13488 }
13489 ts.isPropertyDeclaration = isPropertyDeclaration;
13490 function isMethodSignature(node) {
13491 return node.kind === 155 /* MethodSignature */;
13492 }
13493 ts.isMethodSignature = isMethodSignature;
13494 function isMethodDeclaration(node) {
13495 return node.kind === 156 /* MethodDeclaration */;
13496 }
13497 ts.isMethodDeclaration = isMethodDeclaration;
13498 function isConstructorDeclaration(node) {
13499 return node.kind === 157 /* Constructor */;
13500 }
13501 ts.isConstructorDeclaration = isConstructorDeclaration;
13502 function isGetAccessorDeclaration(node) {
13503 return node.kind === 158 /* GetAccessor */;
13504 }
13505 ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
13506 function isSetAccessorDeclaration(node) {
13507 return node.kind === 159 /* SetAccessor */;
13508 }
13509 ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
13510 function isCallSignatureDeclaration(node) {
13511 return node.kind === 160 /* CallSignature */;
13512 }
13513 ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
13514 function isConstructSignatureDeclaration(node) {
13515 return node.kind === 161 /* ConstructSignature */;
13516 }
13517 ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
13518 function isIndexSignatureDeclaration(node) {
13519 return node.kind === 162 /* IndexSignature */;
13520 }
13521 ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
13522 /* @internal */
13523 function isGetOrSetAccessorDeclaration(node) {
13524 return node.kind === 159 /* SetAccessor */ || node.kind === 158 /* GetAccessor */;
13525 }
13526 ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
13527 // Type
13528 function isTypePredicateNode(node) {
13529 return node.kind === 163 /* TypePredicate */;
13530 }
13531 ts.isTypePredicateNode = isTypePredicateNode;
13532 function isTypeReferenceNode(node) {
13533 return node.kind === 164 /* TypeReference */;
13534 }
13535 ts.isTypeReferenceNode = isTypeReferenceNode;
13536 function isFunctionTypeNode(node) {
13537 return node.kind === 165 /* FunctionType */;
13538 }
13539 ts.isFunctionTypeNode = isFunctionTypeNode;
13540 function isConstructorTypeNode(node) {
13541 return node.kind === 166 /* ConstructorType */;
13542 }
13543 ts.isConstructorTypeNode = isConstructorTypeNode;
13544 function isTypeQueryNode(node) {
13545 return node.kind === 167 /* TypeQuery */;
13546 }
13547 ts.isTypeQueryNode = isTypeQueryNode;
13548 function isTypeLiteralNode(node) {
13549 return node.kind === 168 /* TypeLiteral */;
13550 }
13551 ts.isTypeLiteralNode = isTypeLiteralNode;
13552 function isArrayTypeNode(node) {
13553 return node.kind === 169 /* ArrayType */;
13554 }
13555 ts.isArrayTypeNode = isArrayTypeNode;
13556 function isTupleTypeNode(node) {
13557 return node.kind === 170 /* TupleType */;
13558 }
13559 ts.isTupleTypeNode = isTupleTypeNode;
13560 function isUnionTypeNode(node) {
13561 return node.kind === 173 /* UnionType */;
13562 }
13563 ts.isUnionTypeNode = isUnionTypeNode;
13564 function isIntersectionTypeNode(node) {
13565 return node.kind === 174 /* IntersectionType */;
13566 }
13567 ts.isIntersectionTypeNode = isIntersectionTypeNode;
13568 function isConditionalTypeNode(node) {
13569 return node.kind === 175 /* ConditionalType */;
13570 }
13571 ts.isConditionalTypeNode = isConditionalTypeNode;
13572 function isInferTypeNode(node) {
13573 return node.kind === 176 /* InferType */;
13574 }
13575 ts.isInferTypeNode = isInferTypeNode;
13576 function isParenthesizedTypeNode(node) {
13577 return node.kind === 177 /* ParenthesizedType */;
13578 }
13579 ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
13580 function isThisTypeNode(node) {
13581 return node.kind === 178 /* ThisType */;
13582 }
13583 ts.isThisTypeNode = isThisTypeNode;
13584 function isTypeOperatorNode(node) {
13585 return node.kind === 179 /* TypeOperator */;
13586 }
13587 ts.isTypeOperatorNode = isTypeOperatorNode;
13588 function isIndexedAccessTypeNode(node) {
13589 return node.kind === 180 /* IndexedAccessType */;
13590 }
13591 ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
13592 function isMappedTypeNode(node) {
13593 return node.kind === 181 /* MappedType */;
13594 }
13595 ts.isMappedTypeNode = isMappedTypeNode;
13596 function isLiteralTypeNode(node) {
13597 return node.kind === 182 /* LiteralType */;
13598 }
13599 ts.isLiteralTypeNode = isLiteralTypeNode;
13600 function isImportTypeNode(node) {
13601 return node.kind === 183 /* ImportType */;
13602 }
13603 ts.isImportTypeNode = isImportTypeNode;
13604 // Binding patterns
13605 function isObjectBindingPattern(node) {
13606 return node.kind === 184 /* ObjectBindingPattern */;
13607 }
13608 ts.isObjectBindingPattern = isObjectBindingPattern;
13609 function isArrayBindingPattern(node) {
13610 return node.kind === 185 /* ArrayBindingPattern */;
13611 }
13612 ts.isArrayBindingPattern = isArrayBindingPattern;
13613 function isBindingElement(node) {
13614 return node.kind === 186 /* BindingElement */;
13615 }
13616 ts.isBindingElement = isBindingElement;
13617 // Expression
13618 function isArrayLiteralExpression(node) {
13619 return node.kind === 187 /* ArrayLiteralExpression */;
13620 }
13621 ts.isArrayLiteralExpression = isArrayLiteralExpression;
13622 function isObjectLiteralExpression(node) {
13623 return node.kind === 188 /* ObjectLiteralExpression */;
13624 }
13625 ts.isObjectLiteralExpression = isObjectLiteralExpression;
13626 function isPropertyAccessExpression(node) {
13627 return node.kind === 189 /* PropertyAccessExpression */;
13628 }
13629 ts.isPropertyAccessExpression = isPropertyAccessExpression;
13630 function isElementAccessExpression(node) {
13631 return node.kind === 190 /* ElementAccessExpression */;
13632 }
13633 ts.isElementAccessExpression = isElementAccessExpression;
13634 function isCallExpression(node) {
13635 return node.kind === 191 /* CallExpression */;
13636 }
13637 ts.isCallExpression = isCallExpression;
13638 function isNewExpression(node) {
13639 return node.kind === 192 /* NewExpression */;
13640 }
13641 ts.isNewExpression = isNewExpression;
13642 function isTaggedTemplateExpression(node) {
13643 return node.kind === 193 /* TaggedTemplateExpression */;
13644 }
13645 ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
13646 function isTypeAssertion(node) {
13647 return node.kind === 194 /* TypeAssertionExpression */;
13648 }
13649 ts.isTypeAssertion = isTypeAssertion;
13650 function isConstTypeReference(node) {
13651 return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
13652 node.typeName.escapedText === "const" && !node.typeArguments;
13653 }
13654 ts.isConstTypeReference = isConstTypeReference;
13655 function isParenthesizedExpression(node) {
13656 return node.kind === 195 /* ParenthesizedExpression */;
13657 }
13658 ts.isParenthesizedExpression = isParenthesizedExpression;
13659 function skipPartiallyEmittedExpressions(node) {
13660 while (node.kind === 313 /* PartiallyEmittedExpression */) {
13661 node = node.expression;
13662 }
13663 return node;
13664 }
13665 ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
13666 function isFunctionExpression(node) {
13667 return node.kind === 196 /* FunctionExpression */;
13668 }
13669 ts.isFunctionExpression = isFunctionExpression;
13670 function isArrowFunction(node) {
13671 return node.kind === 197 /* ArrowFunction */;
13672 }
13673 ts.isArrowFunction = isArrowFunction;
13674 function isDeleteExpression(node) {
13675 return node.kind === 198 /* DeleteExpression */;
13676 }
13677 ts.isDeleteExpression = isDeleteExpression;
13678 function isTypeOfExpression(node) {
13679 return node.kind === 199 /* TypeOfExpression */;
13680 }
13681 ts.isTypeOfExpression = isTypeOfExpression;
13682 function isVoidExpression(node) {
13683 return node.kind === 200 /* VoidExpression */;
13684 }
13685 ts.isVoidExpression = isVoidExpression;
13686 function isAwaitExpression(node) {
13687 return node.kind === 201 /* AwaitExpression */;
13688 }
13689 ts.isAwaitExpression = isAwaitExpression;
13690 function isPrefixUnaryExpression(node) {
13691 return node.kind === 202 /* PrefixUnaryExpression */;
13692 }
13693 ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
13694 function isPostfixUnaryExpression(node) {
13695 return node.kind === 203 /* PostfixUnaryExpression */;
13696 }
13697 ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
13698 function isBinaryExpression(node) {
13699 return node.kind === 204 /* BinaryExpression */;
13700 }
13701 ts.isBinaryExpression = isBinaryExpression;
13702 function isConditionalExpression(node) {
13703 return node.kind === 205 /* ConditionalExpression */;
13704 }
13705 ts.isConditionalExpression = isConditionalExpression;
13706 function isTemplateExpression(node) {
13707 return node.kind === 206 /* TemplateExpression */;
13708 }
13709 ts.isTemplateExpression = isTemplateExpression;
13710 function isYieldExpression(node) {
13711 return node.kind === 207 /* YieldExpression */;
13712 }
13713 ts.isYieldExpression = isYieldExpression;
13714 function isSpreadElement(node) {
13715 return node.kind === 208 /* SpreadElement */;
13716 }
13717 ts.isSpreadElement = isSpreadElement;
13718 function isClassExpression(node) {
13719 return node.kind === 209 /* ClassExpression */;
13720 }
13721 ts.isClassExpression = isClassExpression;
13722 function isOmittedExpression(node) {
13723 return node.kind === 210 /* OmittedExpression */;
13724 }
13725 ts.isOmittedExpression = isOmittedExpression;
13726 function isExpressionWithTypeArguments(node) {
13727 return node.kind === 211 /* ExpressionWithTypeArguments */;
13728 }
13729 ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
13730 function isAsExpression(node) {
13731 return node.kind === 212 /* AsExpression */;
13732 }
13733 ts.isAsExpression = isAsExpression;
13734 function isNonNullExpression(node) {
13735 return node.kind === 213 /* NonNullExpression */;
13736 }
13737 ts.isNonNullExpression = isNonNullExpression;
13738 function isMetaProperty(node) {
13739 return node.kind === 214 /* MetaProperty */;
13740 }
13741 ts.isMetaProperty = isMetaProperty;
13742 // Misc
13743 function isTemplateSpan(node) {
13744 return node.kind === 216 /* TemplateSpan */;
13745 }
13746 ts.isTemplateSpan = isTemplateSpan;
13747 function isSemicolonClassElement(node) {
13748 return node.kind === 217 /* SemicolonClassElement */;
13749 }
13750 ts.isSemicolonClassElement = isSemicolonClassElement;
13751 // Block
13752 function isBlock(node) {
13753 return node.kind === 218 /* Block */;
13754 }
13755 ts.isBlock = isBlock;
13756 function isVariableStatement(node) {
13757 return node.kind === 219 /* VariableStatement */;
13758 }
13759 ts.isVariableStatement = isVariableStatement;
13760 function isEmptyStatement(node) {
13761 return node.kind === 220 /* EmptyStatement */;
13762 }
13763 ts.isEmptyStatement = isEmptyStatement;
13764 function isExpressionStatement(node) {
13765 return node.kind === 221 /* ExpressionStatement */;
13766 }
13767 ts.isExpressionStatement = isExpressionStatement;
13768 function isIfStatement(node) {
13769 return node.kind === 222 /* IfStatement */;
13770 }
13771 ts.isIfStatement = isIfStatement;
13772 function isDoStatement(node) {
13773 return node.kind === 223 /* DoStatement */;
13774 }
13775 ts.isDoStatement = isDoStatement;
13776 function isWhileStatement(node) {
13777 return node.kind === 224 /* WhileStatement */;
13778 }
13779 ts.isWhileStatement = isWhileStatement;
13780 function isForStatement(node) {
13781 return node.kind === 225 /* ForStatement */;
13782 }
13783 ts.isForStatement = isForStatement;
13784 function isForInStatement(node) {
13785 return node.kind === 226 /* ForInStatement */;
13786 }
13787 ts.isForInStatement = isForInStatement;
13788 function isForOfStatement(node) {
13789 return node.kind === 227 /* ForOfStatement */;
13790 }
13791 ts.isForOfStatement = isForOfStatement;
13792 function isContinueStatement(node) {
13793 return node.kind === 228 /* ContinueStatement */;
13794 }
13795 ts.isContinueStatement = isContinueStatement;
13796 function isBreakStatement(node) {
13797 return node.kind === 229 /* BreakStatement */;
13798 }
13799 ts.isBreakStatement = isBreakStatement;
13800 function isBreakOrContinueStatement(node) {
13801 return node.kind === 229 /* BreakStatement */ || node.kind === 228 /* ContinueStatement */;
13802 }
13803 ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
13804 function isReturnStatement(node) {
13805 return node.kind === 230 /* ReturnStatement */;
13806 }
13807 ts.isReturnStatement = isReturnStatement;
13808 function isWithStatement(node) {
13809 return node.kind === 231 /* WithStatement */;
13810 }
13811 ts.isWithStatement = isWithStatement;
13812 function isSwitchStatement(node) {
13813 return node.kind === 232 /* SwitchStatement */;
13814 }
13815 ts.isSwitchStatement = isSwitchStatement;
13816 function isLabeledStatement(node) {
13817 return node.kind === 233 /* LabeledStatement */;
13818 }
13819 ts.isLabeledStatement = isLabeledStatement;
13820 function isThrowStatement(node) {
13821 return node.kind === 234 /* ThrowStatement */;
13822 }
13823 ts.isThrowStatement = isThrowStatement;
13824 function isTryStatement(node) {
13825 return node.kind === 235 /* TryStatement */;
13826 }
13827 ts.isTryStatement = isTryStatement;
13828 function isDebuggerStatement(node) {
13829 return node.kind === 236 /* DebuggerStatement */;
13830 }
13831 ts.isDebuggerStatement = isDebuggerStatement;
13832 function isVariableDeclaration(node) {
13833 return node.kind === 237 /* VariableDeclaration */;
13834 }
13835 ts.isVariableDeclaration = isVariableDeclaration;
13836 function isVariableDeclarationList(node) {
13837 return node.kind === 238 /* VariableDeclarationList */;
13838 }
13839 ts.isVariableDeclarationList = isVariableDeclarationList;
13840 function isFunctionDeclaration(node) {
13841 return node.kind === 239 /* FunctionDeclaration */;
13842 }
13843 ts.isFunctionDeclaration = isFunctionDeclaration;
13844 function isClassDeclaration(node) {
13845 return node.kind === 240 /* ClassDeclaration */;
13846 }
13847 ts.isClassDeclaration = isClassDeclaration;
13848 function isInterfaceDeclaration(node) {
13849 return node.kind === 241 /* InterfaceDeclaration */;
13850 }
13851 ts.isInterfaceDeclaration = isInterfaceDeclaration;
13852 function isTypeAliasDeclaration(node) {
13853 return node.kind === 242 /* TypeAliasDeclaration */;
13854 }
13855 ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
13856 function isEnumDeclaration(node) {
13857 return node.kind === 243 /* EnumDeclaration */;
13858 }
13859 ts.isEnumDeclaration = isEnumDeclaration;
13860 function isModuleDeclaration(node) {
13861 return node.kind === 244 /* ModuleDeclaration */;
13862 }
13863 ts.isModuleDeclaration = isModuleDeclaration;
13864 function isModuleBlock(node) {
13865 return node.kind === 245 /* ModuleBlock */;
13866 }
13867 ts.isModuleBlock = isModuleBlock;
13868 function isCaseBlock(node) {
13869 return node.kind === 246 /* CaseBlock */;
13870 }
13871 ts.isCaseBlock = isCaseBlock;
13872 function isNamespaceExportDeclaration(node) {
13873 return node.kind === 247 /* NamespaceExportDeclaration */;
13874 }
13875 ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
13876 function isImportEqualsDeclaration(node) {
13877 return node.kind === 248 /* ImportEqualsDeclaration */;
13878 }
13879 ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
13880 function isImportDeclaration(node) {
13881 return node.kind === 249 /* ImportDeclaration */;
13882 }
13883 ts.isImportDeclaration = isImportDeclaration;
13884 function isImportClause(node) {
13885 return node.kind === 250 /* ImportClause */;
13886 }
13887 ts.isImportClause = isImportClause;
13888 function isNamespaceImport(node) {
13889 return node.kind === 251 /* NamespaceImport */;
13890 }
13891 ts.isNamespaceImport = isNamespaceImport;
13892 function isNamedImports(node) {
13893 return node.kind === 252 /* NamedImports */;
13894 }
13895 ts.isNamedImports = isNamedImports;
13896 function isImportSpecifier(node) {
13897 return node.kind === 253 /* ImportSpecifier */;
13898 }
13899 ts.isImportSpecifier = isImportSpecifier;
13900 function isExportAssignment(node) {
13901 return node.kind === 254 /* ExportAssignment */;
13902 }
13903 ts.isExportAssignment = isExportAssignment;
13904 function isExportDeclaration(node) {
13905 return node.kind === 255 /* ExportDeclaration */;
13906 }
13907 ts.isExportDeclaration = isExportDeclaration;
13908 function isNamedExports(node) {
13909 return node.kind === 256 /* NamedExports */;
13910 }
13911 ts.isNamedExports = isNamedExports;
13912 function isExportSpecifier(node) {
13913 return node.kind === 257 /* ExportSpecifier */;
13914 }
13915 ts.isExportSpecifier = isExportSpecifier;
13916 function isMissingDeclaration(node) {
13917 return node.kind === 258 /* MissingDeclaration */;
13918 }
13919 ts.isMissingDeclaration = isMissingDeclaration;
13920 // Module References
13921 function isExternalModuleReference(node) {
13922 return node.kind === 259 /* ExternalModuleReference */;
13923 }
13924 ts.isExternalModuleReference = isExternalModuleReference;
13925 // JSX
13926 function isJsxElement(node) {
13927 return node.kind === 260 /* JsxElement */;
13928 }
13929 ts.isJsxElement = isJsxElement;
13930 function isJsxSelfClosingElement(node) {
13931 return node.kind === 261 /* JsxSelfClosingElement */;
13932 }
13933 ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
13934 function isJsxOpeningElement(node) {
13935 return node.kind === 262 /* JsxOpeningElement */;
13936 }
13937 ts.isJsxOpeningElement = isJsxOpeningElement;
13938 function isJsxClosingElement(node) {
13939 return node.kind === 263 /* JsxClosingElement */;
13940 }
13941 ts.isJsxClosingElement = isJsxClosingElement;
13942 function isJsxFragment(node) {
13943 return node.kind === 264 /* JsxFragment */;
13944 }
13945 ts.isJsxFragment = isJsxFragment;
13946 function isJsxOpeningFragment(node) {
13947 return node.kind === 265 /* JsxOpeningFragment */;
13948 }
13949 ts.isJsxOpeningFragment = isJsxOpeningFragment;
13950 function isJsxClosingFragment(node) {
13951 return node.kind === 266 /* JsxClosingFragment */;
13952 }
13953 ts.isJsxClosingFragment = isJsxClosingFragment;
13954 function isJsxAttribute(node) {
13955 return node.kind === 267 /* JsxAttribute */;
13956 }
13957 ts.isJsxAttribute = isJsxAttribute;
13958 function isJsxAttributes(node) {
13959 return node.kind === 268 /* JsxAttributes */;
13960 }
13961 ts.isJsxAttributes = isJsxAttributes;
13962 function isJsxSpreadAttribute(node) {
13963 return node.kind === 269 /* JsxSpreadAttribute */;
13964 }
13965 ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
13966 function isJsxExpression(node) {
13967 return node.kind === 270 /* JsxExpression */;
13968 }
13969 ts.isJsxExpression = isJsxExpression;
13970 // Clauses
13971 function isCaseClause(node) {
13972 return node.kind === 271 /* CaseClause */;
13973 }
13974 ts.isCaseClause = isCaseClause;
13975 function isDefaultClause(node) {
13976 return node.kind === 272 /* DefaultClause */;
13977 }
13978 ts.isDefaultClause = isDefaultClause;
13979 function isHeritageClause(node) {
13980 return node.kind === 273 /* HeritageClause */;
13981 }
13982 ts.isHeritageClause = isHeritageClause;
13983 function isCatchClause(node) {
13984 return node.kind === 274 /* CatchClause */;
13985 }
13986 ts.isCatchClause = isCatchClause;
13987 // Property assignments
13988 function isPropertyAssignment(node) {
13989 return node.kind === 275 /* PropertyAssignment */;
13990 }
13991 ts.isPropertyAssignment = isPropertyAssignment;
13992 function isShorthandPropertyAssignment(node) {
13993 return node.kind === 276 /* ShorthandPropertyAssignment */;
13994 }
13995 ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
13996 function isSpreadAssignment(node) {
13997 return node.kind === 277 /* SpreadAssignment */;
13998 }
13999 ts.isSpreadAssignment = isSpreadAssignment;
14000 // Enum
14001 function isEnumMember(node) {
14002 return node.kind === 278 /* EnumMember */;
14003 }
14004 ts.isEnumMember = isEnumMember;
14005 // Top-level nodes
14006 function isSourceFile(node) {
14007 return node.kind === 284 /* SourceFile */;
14008 }
14009 ts.isSourceFile = isSourceFile;
14010 function isBundle(node) {
14011 return node.kind === 285 /* Bundle */;
14012 }
14013 ts.isBundle = isBundle;
14014 function isUnparsedSource(node) {
14015 return node.kind === 286 /* UnparsedSource */;
14016 }
14017 ts.isUnparsedSource = isUnparsedSource;
14018 function isUnparsedPrepend(node) {
14019 return node.kind === 280 /* UnparsedPrepend */;
14020 }
14021 ts.isUnparsedPrepend = isUnparsedPrepend;
14022 function isUnparsedTextLike(node) {
14023 switch (node.kind) {
14024 case 281 /* UnparsedText */:
14025 case 282 /* UnparsedInternalText */:
14026 return true;
14027 default:
14028 return false;
14029 }
14030 }
14031 ts.isUnparsedTextLike = isUnparsedTextLike;
14032 function isUnparsedNode(node) {
14033 return isUnparsedTextLike(node) ||
14034 node.kind === 279 /* UnparsedPrologue */ ||
14035 node.kind === 283 /* UnparsedSyntheticReference */;
14036 }
14037 ts.isUnparsedNode = isUnparsedNode;
14038 // JSDoc
14039 function isJSDocTypeExpression(node) {
14040 return node.kind === 288 /* JSDocTypeExpression */;
14041 }
14042 ts.isJSDocTypeExpression = isJSDocTypeExpression;
14043 function isJSDocAllType(node) {
14044 return node.kind === 289 /* JSDocAllType */;
14045 }
14046 ts.isJSDocAllType = isJSDocAllType;
14047 function isJSDocUnknownType(node) {
14048 return node.kind === 290 /* JSDocUnknownType */;
14049 }
14050 ts.isJSDocUnknownType = isJSDocUnknownType;
14051 function isJSDocNullableType(node) {
14052 return node.kind === 291 /* JSDocNullableType */;
14053 }
14054 ts.isJSDocNullableType = isJSDocNullableType;
14055 function isJSDocNonNullableType(node) {
14056 return node.kind === 292 /* JSDocNonNullableType */;
14057 }
14058 ts.isJSDocNonNullableType = isJSDocNonNullableType;
14059 function isJSDocOptionalType(node) {
14060 return node.kind === 293 /* JSDocOptionalType */;
14061 }
14062 ts.isJSDocOptionalType = isJSDocOptionalType;
14063 function isJSDocFunctionType(node) {
14064 return node.kind === 294 /* JSDocFunctionType */;
14065 }
14066 ts.isJSDocFunctionType = isJSDocFunctionType;
14067 function isJSDocVariadicType(node) {
14068 return node.kind === 295 /* JSDocVariadicType */;
14069 }
14070 ts.isJSDocVariadicType = isJSDocVariadicType;
14071 function isJSDoc(node) {
14072 return node.kind === 296 /* JSDocComment */;
14073 }
14074 ts.isJSDoc = isJSDoc;
14075 function isJSDocAugmentsTag(node) {
14076 return node.kind === 300 /* JSDocAugmentsTag */;
14077 }
14078 ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
14079 function isJSDocClassTag(node) {
14080 return node.kind === 301 /* JSDocClassTag */;
14081 }
14082 ts.isJSDocClassTag = isJSDocClassTag;
14083 function isJSDocEnumTag(node) {
14084 return node.kind === 303 /* JSDocEnumTag */;
14085 }
14086 ts.isJSDocEnumTag = isJSDocEnumTag;
14087 function isJSDocThisTag(node) {
14088 return node.kind === 306 /* JSDocThisTag */;
14089 }
14090 ts.isJSDocThisTag = isJSDocThisTag;
14091 function isJSDocParameterTag(node) {
14092 return node.kind === 304 /* JSDocParameterTag */;
14093 }
14094 ts.isJSDocParameterTag = isJSDocParameterTag;
14095 function isJSDocReturnTag(node) {
14096 return node.kind === 305 /* JSDocReturnTag */;
14097 }
14098 ts.isJSDocReturnTag = isJSDocReturnTag;
14099 function isJSDocTypeTag(node) {
14100 return node.kind === 307 /* JSDocTypeTag */;
14101 }
14102 ts.isJSDocTypeTag = isJSDocTypeTag;
14103 function isJSDocTemplateTag(node) {
14104 return node.kind === 308 /* JSDocTemplateTag */;
14105 }
14106 ts.isJSDocTemplateTag = isJSDocTemplateTag;
14107 function isJSDocTypedefTag(node) {
14108 return node.kind === 309 /* JSDocTypedefTag */;
14109 }
14110 ts.isJSDocTypedefTag = isJSDocTypedefTag;
14111 function isJSDocPropertyTag(node) {
14112 return node.kind === 310 /* JSDocPropertyTag */;
14113 }
14114 ts.isJSDocPropertyTag = isJSDocPropertyTag;
14115 function isJSDocPropertyLikeTag(node) {
14116 return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
14117 }
14118 ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
14119 function isJSDocTypeLiteral(node) {
14120 return node.kind === 297 /* JSDocTypeLiteral */;
14121 }
14122 ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
14123 function isJSDocCallbackTag(node) {
14124 return node.kind === 302 /* JSDocCallbackTag */;
14125 }
14126 ts.isJSDocCallbackTag = isJSDocCallbackTag;
14127 function isJSDocSignature(node) {
14128 return node.kind === 298 /* JSDocSignature */;
14129 }
14130 ts.isJSDocSignature = isJSDocSignature;
14131})(ts || (ts = {}));
14132// Node tests
14133//
14134// All node tests in the following list should *not* reference parent pointers so that
14135// they may be used with transformations.
14136(function (ts) {
14137 /* @internal */
14138 function isSyntaxList(n) {
14139 return n.kind === 311 /* SyntaxList */;
14140 }
14141 ts.isSyntaxList = isSyntaxList;
14142 /* @internal */
14143 function isNode(node) {
14144 return isNodeKind(node.kind);
14145 }
14146 ts.isNode = isNode;
14147 /* @internal */
14148 function isNodeKind(kind) {
14149 return kind >= 148 /* FirstNode */;
14150 }
14151 ts.isNodeKind = isNodeKind;
14152 /**
14153 * True if node is of some token syntax kind.
14154 * For example, this is true for an IfKeyword but not for an IfStatement.
14155 * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
14156 */
14157 function isToken(n) {
14158 return n.kind >= 0 /* FirstToken */ && n.kind <= 147 /* LastToken */;
14159 }
14160 ts.isToken = isToken;
14161 // Node Arrays
14162 /* @internal */
14163 function isNodeArray(array) {
14164 return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
14165 }
14166 ts.isNodeArray = isNodeArray;
14167 // Literals
14168 /* @internal */
14169 function isLiteralKind(kind) {
14170 return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
14171 }
14172 ts.isLiteralKind = isLiteralKind;
14173 function isLiteralExpression(node) {
14174 return isLiteralKind(node.kind);
14175 }
14176 ts.isLiteralExpression = isLiteralExpression;
14177 // Pseudo-literals
14178 /* @internal */
14179 function isTemplateLiteralKind(kind) {
14180 return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
14181 }
14182 ts.isTemplateLiteralKind = isTemplateLiteralKind;
14183 function isTemplateLiteralToken(node) {
14184 return isTemplateLiteralKind(node.kind);
14185 }
14186 ts.isTemplateLiteralToken = isTemplateLiteralToken;
14187 function isTemplateMiddleOrTemplateTail(node) {
14188 var kind = node.kind;
14189 return kind === 16 /* TemplateMiddle */
14190 || kind === 17 /* TemplateTail */;
14191 }
14192 ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
14193 function isImportOrExportSpecifier(node) {
14194 return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
14195 }
14196 ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
14197 function isStringTextContainingNode(node) {
14198 return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
14199 }
14200 ts.isStringTextContainingNode = isStringTextContainingNode;
14201 // Identifiers
14202 /* @internal */
14203 function isGeneratedIdentifier(node) {
14204 return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
14205 }
14206 ts.isGeneratedIdentifier = isGeneratedIdentifier;
14207 // Keywords
14208 /* @internal */
14209 function isModifierKind(token) {
14210 switch (token) {
14211 case 118 /* AbstractKeyword */:
14212 case 121 /* AsyncKeyword */:
14213 case 77 /* ConstKeyword */:
14214 case 125 /* DeclareKeyword */:
14215 case 80 /* DefaultKeyword */:
14216 case 85 /* ExportKeyword */:
14217 case 115 /* PublicKeyword */:
14218 case 113 /* PrivateKeyword */:
14219 case 114 /* ProtectedKeyword */:
14220 case 133 /* ReadonlyKeyword */:
14221 case 116 /* StaticKeyword */:
14222 return true;
14223 }
14224 return false;
14225 }
14226 ts.isModifierKind = isModifierKind;
14227 /* @internal */
14228 function isParameterPropertyModifier(kind) {
14229 return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
14230 }
14231 ts.isParameterPropertyModifier = isParameterPropertyModifier;
14232 /* @internal */
14233 function isClassMemberModifier(idToken) {
14234 return isParameterPropertyModifier(idToken) || idToken === 116 /* StaticKeyword */;
14235 }
14236 ts.isClassMemberModifier = isClassMemberModifier;
14237 function isModifier(node) {
14238 return isModifierKind(node.kind);
14239 }
14240 ts.isModifier = isModifier;
14241 function isEntityName(node) {
14242 var kind = node.kind;
14243 return kind === 148 /* QualifiedName */
14244 || kind === 72 /* Identifier */;
14245 }
14246 ts.isEntityName = isEntityName;
14247 function isPropertyName(node) {
14248 var kind = node.kind;
14249 return kind === 72 /* Identifier */
14250 || kind === 10 /* StringLiteral */
14251 || kind === 8 /* NumericLiteral */
14252 || kind === 149 /* ComputedPropertyName */;
14253 }
14254 ts.isPropertyName = isPropertyName;
14255 function isBindingName(node) {
14256 var kind = node.kind;
14257 return kind === 72 /* Identifier */
14258 || kind === 184 /* ObjectBindingPattern */
14259 || kind === 185 /* ArrayBindingPattern */;
14260 }
14261 ts.isBindingName = isBindingName;
14262 // Functions
14263 function isFunctionLike(node) {
14264 return node && isFunctionLikeKind(node.kind);
14265 }
14266 ts.isFunctionLike = isFunctionLike;
14267 /* @internal */
14268 function isFunctionLikeDeclaration(node) {
14269 return node && isFunctionLikeDeclarationKind(node.kind);
14270 }
14271 ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
14272 function isFunctionLikeDeclarationKind(kind) {
14273 switch (kind) {
14274 case 239 /* FunctionDeclaration */:
14275 case 156 /* MethodDeclaration */:
14276 case 157 /* Constructor */:
14277 case 158 /* GetAccessor */:
14278 case 159 /* SetAccessor */:
14279 case 196 /* FunctionExpression */:
14280 case 197 /* ArrowFunction */:
14281 return true;
14282 default:
14283 return false;
14284 }
14285 }
14286 /* @internal */
14287 function isFunctionLikeKind(kind) {
14288 switch (kind) {
14289 case 155 /* MethodSignature */:
14290 case 160 /* CallSignature */:
14291 case 298 /* JSDocSignature */:
14292 case 161 /* ConstructSignature */:
14293 case 162 /* IndexSignature */:
14294 case 165 /* FunctionType */:
14295 case 294 /* JSDocFunctionType */:
14296 case 166 /* ConstructorType */:
14297 return true;
14298 default:
14299 return isFunctionLikeDeclarationKind(kind);
14300 }
14301 }
14302 ts.isFunctionLikeKind = isFunctionLikeKind;
14303 /* @internal */
14304 function isFunctionOrModuleBlock(node) {
14305 return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent);
14306 }
14307 ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
14308 // Classes
14309 function isClassElement(node) {
14310 var kind = node.kind;
14311 return kind === 157 /* Constructor */
14312 || kind === 154 /* PropertyDeclaration */
14313 || kind === 156 /* MethodDeclaration */
14314 || kind === 158 /* GetAccessor */
14315 || kind === 159 /* SetAccessor */
14316 || kind === 162 /* IndexSignature */
14317 || kind === 217 /* SemicolonClassElement */;
14318 }
14319 ts.isClassElement = isClassElement;
14320 function isClassLike(node) {
14321 return node && (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */);
14322 }
14323 ts.isClassLike = isClassLike;
14324 function isAccessor(node) {
14325 return node && (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */);
14326 }
14327 ts.isAccessor = isAccessor;
14328 /* @internal */
14329 function isMethodOrAccessor(node) {
14330 switch (node.kind) {
14331 case 156 /* MethodDeclaration */:
14332 case 158 /* GetAccessor */:
14333 case 159 /* SetAccessor */:
14334 return true;
14335 default:
14336 return false;
14337 }
14338 }
14339 ts.isMethodOrAccessor = isMethodOrAccessor;
14340 // Type members
14341 function isTypeElement(node) {
14342 var kind = node.kind;
14343 return kind === 161 /* ConstructSignature */
14344 || kind === 160 /* CallSignature */
14345 || kind === 153 /* PropertySignature */
14346 || kind === 155 /* MethodSignature */
14347 || kind === 162 /* IndexSignature */;
14348 }
14349 ts.isTypeElement = isTypeElement;
14350 function isClassOrTypeElement(node) {
14351 return isTypeElement(node) || isClassElement(node);
14352 }
14353 ts.isClassOrTypeElement = isClassOrTypeElement;
14354 function isObjectLiteralElementLike(node) {
14355 var kind = node.kind;
14356 return kind === 275 /* PropertyAssignment */
14357 || kind === 276 /* ShorthandPropertyAssignment */
14358 || kind === 277 /* SpreadAssignment */
14359 || kind === 156 /* MethodDeclaration */
14360 || kind === 158 /* GetAccessor */
14361 || kind === 159 /* SetAccessor */;
14362 }
14363 ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
14364 // Type
14365 /**
14366 * Node test that determines whether a node is a valid type node.
14367 * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
14368 * of a TypeNode.
14369 */
14370 function isTypeNode(node) {
14371 return ts.isTypeNodeKind(node.kind);
14372 }
14373 ts.isTypeNode = isTypeNode;
14374 function isFunctionOrConstructorTypeNode(node) {
14375 switch (node.kind) {
14376 case 165 /* FunctionType */:
14377 case 166 /* ConstructorType */:
14378 return true;
14379 }
14380 return false;
14381 }
14382 ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
14383 // Binding patterns
14384 /* @internal */
14385 function isBindingPattern(node) {
14386 if (node) {
14387 var kind = node.kind;
14388 return kind === 185 /* ArrayBindingPattern */
14389 || kind === 184 /* ObjectBindingPattern */;
14390 }
14391 return false;
14392 }
14393 ts.isBindingPattern = isBindingPattern;
14394 /* @internal */
14395 function isAssignmentPattern(node) {
14396 var kind = node.kind;
14397 return kind === 187 /* ArrayLiteralExpression */
14398 || kind === 188 /* ObjectLiteralExpression */;
14399 }
14400 ts.isAssignmentPattern = isAssignmentPattern;
14401 /* @internal */
14402 function isArrayBindingElement(node) {
14403 var kind = node.kind;
14404 return kind === 186 /* BindingElement */
14405 || kind === 210 /* OmittedExpression */;
14406 }
14407 ts.isArrayBindingElement = isArrayBindingElement;
14408 /**
14409 * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
14410 */
14411 /* @internal */
14412 function isDeclarationBindingElement(bindingElement) {
14413 switch (bindingElement.kind) {
14414 case 237 /* VariableDeclaration */:
14415 case 151 /* Parameter */:
14416 case 186 /* BindingElement */:
14417 return true;
14418 }
14419 return false;
14420 }
14421 ts.isDeclarationBindingElement = isDeclarationBindingElement;
14422 /**
14423 * Determines whether a node is a BindingOrAssignmentPattern
14424 */
14425 /* @internal */
14426 function isBindingOrAssignmentPattern(node) {
14427 return isObjectBindingOrAssignmentPattern(node)
14428 || isArrayBindingOrAssignmentPattern(node);
14429 }
14430 ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
14431 /**
14432 * Determines whether a node is an ObjectBindingOrAssignmentPattern
14433 */
14434 /* @internal */
14435 function isObjectBindingOrAssignmentPattern(node) {
14436 switch (node.kind) {
14437 case 184 /* ObjectBindingPattern */:
14438 case 188 /* ObjectLiteralExpression */:
14439 return true;
14440 }
14441 return false;
14442 }
14443 ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
14444 /**
14445 * Determines whether a node is an ArrayBindingOrAssignmentPattern
14446 */
14447 /* @internal */
14448 function isArrayBindingOrAssignmentPattern(node) {
14449 switch (node.kind) {
14450 case 185 /* ArrayBindingPattern */:
14451 case 187 /* ArrayLiteralExpression */:
14452 return true;
14453 }
14454 return false;
14455 }
14456 ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
14457 /* @internal */
14458 function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
14459 var kind = node.kind;
14460 return kind === 189 /* PropertyAccessExpression */
14461 || kind === 148 /* QualifiedName */
14462 || kind === 183 /* ImportType */;
14463 }
14464 ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
14465 // Expression
14466 function isPropertyAccessOrQualifiedName(node) {
14467 var kind = node.kind;
14468 return kind === 189 /* PropertyAccessExpression */
14469 || kind === 148 /* QualifiedName */;
14470 }
14471 ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
14472 function isCallLikeExpression(node) {
14473 switch (node.kind) {
14474 case 262 /* JsxOpeningElement */:
14475 case 261 /* JsxSelfClosingElement */:
14476 case 191 /* CallExpression */:
14477 case 192 /* NewExpression */:
14478 case 193 /* TaggedTemplateExpression */:
14479 case 152 /* Decorator */:
14480 return true;
14481 default:
14482 return false;
14483 }
14484 }
14485 ts.isCallLikeExpression = isCallLikeExpression;
14486 function isCallOrNewExpression(node) {
14487 return node.kind === 191 /* CallExpression */ || node.kind === 192 /* NewExpression */;
14488 }
14489 ts.isCallOrNewExpression = isCallOrNewExpression;
14490 function isTemplateLiteral(node) {
14491 var kind = node.kind;
14492 return kind === 206 /* TemplateExpression */
14493 || kind === 14 /* NoSubstitutionTemplateLiteral */;
14494 }
14495 ts.isTemplateLiteral = isTemplateLiteral;
14496 /* @internal */
14497 function isLeftHandSideExpression(node) {
14498 return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
14499 }
14500 ts.isLeftHandSideExpression = isLeftHandSideExpression;
14501 function isLeftHandSideExpressionKind(kind) {
14502 switch (kind) {
14503 case 189 /* PropertyAccessExpression */:
14504 case 190 /* ElementAccessExpression */:
14505 case 192 /* NewExpression */:
14506 case 191 /* CallExpression */:
14507 case 260 /* JsxElement */:
14508 case 261 /* JsxSelfClosingElement */:
14509 case 264 /* JsxFragment */:
14510 case 193 /* TaggedTemplateExpression */:
14511 case 187 /* ArrayLiteralExpression */:
14512 case 195 /* ParenthesizedExpression */:
14513 case 188 /* ObjectLiteralExpression */:
14514 case 209 /* ClassExpression */:
14515 case 196 /* FunctionExpression */:
14516 case 72 /* Identifier */:
14517 case 13 /* RegularExpressionLiteral */:
14518 case 8 /* NumericLiteral */:
14519 case 9 /* BigIntLiteral */:
14520 case 10 /* StringLiteral */:
14521 case 14 /* NoSubstitutionTemplateLiteral */:
14522 case 206 /* TemplateExpression */:
14523 case 87 /* FalseKeyword */:
14524 case 96 /* NullKeyword */:
14525 case 100 /* ThisKeyword */:
14526 case 102 /* TrueKeyword */:
14527 case 98 /* SuperKeyword */:
14528 case 213 /* NonNullExpression */:
14529 case 214 /* MetaProperty */:
14530 case 92 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
14531 return true;
14532 default:
14533 return false;
14534 }
14535 }
14536 /* @internal */
14537 function isUnaryExpression(node) {
14538 return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
14539 }
14540 ts.isUnaryExpression = isUnaryExpression;
14541 function isUnaryExpressionKind(kind) {
14542 switch (kind) {
14543 case 202 /* PrefixUnaryExpression */:
14544 case 203 /* PostfixUnaryExpression */:
14545 case 198 /* DeleteExpression */:
14546 case 199 /* TypeOfExpression */:
14547 case 200 /* VoidExpression */:
14548 case 201 /* AwaitExpression */:
14549 case 194 /* TypeAssertionExpression */:
14550 return true;
14551 default:
14552 return isLeftHandSideExpressionKind(kind);
14553 }
14554 }
14555 /* @internal */
14556 function isUnaryExpressionWithWrite(expr) {
14557 switch (expr.kind) {
14558 case 203 /* PostfixUnaryExpression */:
14559 return true;
14560 case 202 /* PrefixUnaryExpression */:
14561 return expr.operator === 44 /* PlusPlusToken */ ||
14562 expr.operator === 45 /* MinusMinusToken */;
14563 default:
14564 return false;
14565 }
14566 }
14567 ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
14568 /* @internal */
14569 /**
14570 * Determines whether a node is an expression based only on its kind.
14571 * Use `isExpressionNode` if not in transforms.
14572 */
14573 function isExpression(node) {
14574 return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
14575 }
14576 ts.isExpression = isExpression;
14577 function isExpressionKind(kind) {
14578 switch (kind) {
14579 case 205 /* ConditionalExpression */:
14580 case 207 /* YieldExpression */:
14581 case 197 /* ArrowFunction */:
14582 case 204 /* BinaryExpression */:
14583 case 208 /* SpreadElement */:
14584 case 212 /* AsExpression */:
14585 case 210 /* OmittedExpression */:
14586 case 314 /* CommaListExpression */:
14587 case 313 /* PartiallyEmittedExpression */:
14588 return true;
14589 default:
14590 return isUnaryExpressionKind(kind);
14591 }
14592 }
14593 function isAssertionExpression(node) {
14594 var kind = node.kind;
14595 return kind === 194 /* TypeAssertionExpression */
14596 || kind === 212 /* AsExpression */;
14597 }
14598 ts.isAssertionExpression = isAssertionExpression;
14599 /* @internal */
14600 function isPartiallyEmittedExpression(node) {
14601 return node.kind === 313 /* PartiallyEmittedExpression */;
14602 }
14603 ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
14604 /* @internal */
14605 function isNotEmittedStatement(node) {
14606 return node.kind === 312 /* NotEmittedStatement */;
14607 }
14608 ts.isNotEmittedStatement = isNotEmittedStatement;
14609 /* @internal */
14610 function isNotEmittedOrPartiallyEmittedNode(node) {
14611 return isNotEmittedStatement(node)
14612 || isPartiallyEmittedExpression(node);
14613 }
14614 ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
14615 function isIterationStatement(node, lookInLabeledStatements) {
14616 switch (node.kind) {
14617 case 225 /* ForStatement */:
14618 case 226 /* ForInStatement */:
14619 case 227 /* ForOfStatement */:
14620 case 223 /* DoStatement */:
14621 case 224 /* WhileStatement */:
14622 return true;
14623 case 233 /* LabeledStatement */:
14624 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
14625 }
14626 return false;
14627 }
14628 ts.isIterationStatement = isIterationStatement;
14629 /* @internal */
14630 function isForInOrOfStatement(node) {
14631 return node.kind === 226 /* ForInStatement */ || node.kind === 227 /* ForOfStatement */;
14632 }
14633 ts.isForInOrOfStatement = isForInOrOfStatement;
14634 // Element
14635 /* @internal */
14636 function isConciseBody(node) {
14637 return ts.isBlock(node)
14638 || isExpression(node);
14639 }
14640 ts.isConciseBody = isConciseBody;
14641 /* @internal */
14642 function isFunctionBody(node) {
14643 return ts.isBlock(node);
14644 }
14645 ts.isFunctionBody = isFunctionBody;
14646 /* @internal */
14647 function isForInitializer(node) {
14648 return ts.isVariableDeclarationList(node)
14649 || isExpression(node);
14650 }
14651 ts.isForInitializer = isForInitializer;
14652 /* @internal */
14653 function isModuleBody(node) {
14654 var kind = node.kind;
14655 return kind === 245 /* ModuleBlock */
14656 || kind === 244 /* ModuleDeclaration */
14657 || kind === 72 /* Identifier */;
14658 }
14659 ts.isModuleBody = isModuleBody;
14660 /* @internal */
14661 function isNamespaceBody(node) {
14662 var kind = node.kind;
14663 return kind === 245 /* ModuleBlock */
14664 || kind === 244 /* ModuleDeclaration */;
14665 }
14666 ts.isNamespaceBody = isNamespaceBody;
14667 /* @internal */
14668 function isJSDocNamespaceBody(node) {
14669 var kind = node.kind;
14670 return kind === 72 /* Identifier */
14671 || kind === 244 /* ModuleDeclaration */;
14672 }
14673 ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
14674 /* @internal */
14675 function isNamedImportBindings(node) {
14676 var kind = node.kind;
14677 return kind === 252 /* NamedImports */
14678 || kind === 251 /* NamespaceImport */;
14679 }
14680 ts.isNamedImportBindings = isNamedImportBindings;
14681 /* @internal */
14682 function isModuleOrEnumDeclaration(node) {
14683 return node.kind === 244 /* ModuleDeclaration */ || node.kind === 243 /* EnumDeclaration */;
14684 }
14685 ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
14686 function isDeclarationKind(kind) {
14687 return kind === 197 /* ArrowFunction */
14688 || kind === 186 /* BindingElement */
14689 || kind === 240 /* ClassDeclaration */
14690 || kind === 209 /* ClassExpression */
14691 || kind === 157 /* Constructor */
14692 || kind === 243 /* EnumDeclaration */
14693 || kind === 278 /* EnumMember */
14694 || kind === 257 /* ExportSpecifier */
14695 || kind === 239 /* FunctionDeclaration */
14696 || kind === 196 /* FunctionExpression */
14697 || kind === 158 /* GetAccessor */
14698 || kind === 250 /* ImportClause */
14699 || kind === 248 /* ImportEqualsDeclaration */
14700 || kind === 253 /* ImportSpecifier */
14701 || kind === 241 /* InterfaceDeclaration */
14702 || kind === 267 /* JsxAttribute */
14703 || kind === 156 /* MethodDeclaration */
14704 || kind === 155 /* MethodSignature */
14705 || kind === 244 /* ModuleDeclaration */
14706 || kind === 247 /* NamespaceExportDeclaration */
14707 || kind === 251 /* NamespaceImport */
14708 || kind === 151 /* Parameter */
14709 || kind === 275 /* PropertyAssignment */
14710 || kind === 154 /* PropertyDeclaration */
14711 || kind === 153 /* PropertySignature */
14712 || kind === 159 /* SetAccessor */
14713 || kind === 276 /* ShorthandPropertyAssignment */
14714 || kind === 242 /* TypeAliasDeclaration */
14715 || kind === 150 /* TypeParameter */
14716 || kind === 237 /* VariableDeclaration */
14717 || kind === 309 /* JSDocTypedefTag */
14718 || kind === 302 /* JSDocCallbackTag */
14719 || kind === 310 /* JSDocPropertyTag */;
14720 }
14721 function isDeclarationStatementKind(kind) {
14722 return kind === 239 /* FunctionDeclaration */
14723 || kind === 258 /* MissingDeclaration */
14724 || kind === 240 /* ClassDeclaration */
14725 || kind === 241 /* InterfaceDeclaration */
14726 || kind === 242 /* TypeAliasDeclaration */
14727 || kind === 243 /* EnumDeclaration */
14728 || kind === 244 /* ModuleDeclaration */
14729 || kind === 249 /* ImportDeclaration */
14730 || kind === 248 /* ImportEqualsDeclaration */
14731 || kind === 255 /* ExportDeclaration */
14732 || kind === 254 /* ExportAssignment */
14733 || kind === 247 /* NamespaceExportDeclaration */;
14734 }
14735 function isStatementKindButNotDeclarationKind(kind) {
14736 return kind === 229 /* BreakStatement */
14737 || kind === 228 /* ContinueStatement */
14738 || kind === 236 /* DebuggerStatement */
14739 || kind === 223 /* DoStatement */
14740 || kind === 221 /* ExpressionStatement */
14741 || kind === 220 /* EmptyStatement */
14742 || kind === 226 /* ForInStatement */
14743 || kind === 227 /* ForOfStatement */
14744 || kind === 225 /* ForStatement */
14745 || kind === 222 /* IfStatement */
14746 || kind === 233 /* LabeledStatement */
14747 || kind === 230 /* ReturnStatement */
14748 || kind === 232 /* SwitchStatement */
14749 || kind === 234 /* ThrowStatement */
14750 || kind === 235 /* TryStatement */
14751 || kind === 219 /* VariableStatement */
14752 || kind === 224 /* WhileStatement */
14753 || kind === 231 /* WithStatement */
14754 || kind === 312 /* NotEmittedStatement */
14755 || kind === 316 /* EndOfDeclarationMarker */
14756 || kind === 315 /* MergeDeclarationMarker */;
14757 }
14758 /* @internal */
14759 function isDeclaration(node) {
14760 if (node.kind === 150 /* TypeParameter */) {
14761 return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
14762 }
14763 return isDeclarationKind(node.kind);
14764 }
14765 ts.isDeclaration = isDeclaration;
14766 /* @internal */
14767 function isDeclarationStatement(node) {
14768 return isDeclarationStatementKind(node.kind);
14769 }
14770 ts.isDeclarationStatement = isDeclarationStatement;
14771 /**
14772 * Determines whether the node is a statement that is not also a declaration
14773 */
14774 /* @internal */
14775 function isStatementButNotDeclaration(node) {
14776 return isStatementKindButNotDeclarationKind(node.kind);
14777 }
14778 ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
14779 /* @internal */
14780 function isStatement(node) {
14781 var kind = node.kind;
14782 return isStatementKindButNotDeclarationKind(kind)
14783 || isDeclarationStatementKind(kind)
14784 || isBlockStatement(node);
14785 }
14786 ts.isStatement = isStatement;
14787 function isBlockStatement(node) {
14788 if (node.kind !== 218 /* Block */)
14789 return false;
14790 if (node.parent !== undefined) {
14791 if (node.parent.kind === 235 /* TryStatement */ || node.parent.kind === 274 /* CatchClause */) {
14792 return false;
14793 }
14794 }
14795 return !ts.isFunctionBlock(node);
14796 }
14797 // Module references
14798 /* @internal */
14799 function isModuleReference(node) {
14800 var kind = node.kind;
14801 return kind === 259 /* ExternalModuleReference */
14802 || kind === 148 /* QualifiedName */
14803 || kind === 72 /* Identifier */;
14804 }
14805 ts.isModuleReference = isModuleReference;
14806 // JSX
14807 /* @internal */
14808 function isJsxTagNameExpression(node) {
14809 var kind = node.kind;
14810 return kind === 100 /* ThisKeyword */
14811 || kind === 72 /* Identifier */
14812 || kind === 189 /* PropertyAccessExpression */;
14813 }
14814 ts.isJsxTagNameExpression = isJsxTagNameExpression;
14815 /* @internal */
14816 function isJsxChild(node) {
14817 var kind = node.kind;
14818 return kind === 260 /* JsxElement */
14819 || kind === 270 /* JsxExpression */
14820 || kind === 261 /* JsxSelfClosingElement */
14821 || kind === 11 /* JsxText */
14822 || kind === 264 /* JsxFragment */;
14823 }
14824 ts.isJsxChild = isJsxChild;
14825 /* @internal */
14826 function isJsxAttributeLike(node) {
14827 var kind = node.kind;
14828 return kind === 267 /* JsxAttribute */
14829 || kind === 269 /* JsxSpreadAttribute */;
14830 }
14831 ts.isJsxAttributeLike = isJsxAttributeLike;
14832 /* @internal */
14833 function isStringLiteralOrJsxExpression(node) {
14834 var kind = node.kind;
14835 return kind === 10 /* StringLiteral */
14836 || kind === 270 /* JsxExpression */;
14837 }
14838 ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
14839 function isJsxOpeningLikeElement(node) {
14840 var kind = node.kind;
14841 return kind === 262 /* JsxOpeningElement */
14842 || kind === 261 /* JsxSelfClosingElement */;
14843 }
14844 ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
14845 // Clauses
14846 function isCaseOrDefaultClause(node) {
14847 var kind = node.kind;
14848 return kind === 271 /* CaseClause */
14849 || kind === 272 /* DefaultClause */;
14850 }
14851 ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
14852 // JSDoc
14853 /** True if node is of some JSDoc syntax kind. */
14854 /* @internal */
14855 function isJSDocNode(node) {
14856 return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
14857 }
14858 ts.isJSDocNode = isJSDocNode;
14859 /** True if node is of a kind that may contain comment text. */
14860 function isJSDocCommentContainingNode(node) {
14861 return node.kind === 296 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
14862 }
14863 ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
14864 // TODO: determine what this does before making it public.
14865 /* @internal */
14866 function isJSDocTag(node) {
14867 return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
14868 }
14869 ts.isJSDocTag = isJSDocTag;
14870 function isSetAccessor(node) {
14871 return node.kind === 159 /* SetAccessor */;
14872 }
14873 ts.isSetAccessor = isSetAccessor;
14874 function isGetAccessor(node) {
14875 return node.kind === 158 /* GetAccessor */;
14876 }
14877 ts.isGetAccessor = isGetAccessor;
14878 /** True if has jsdoc nodes attached to it. */
14879 /* @internal */
14880 // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
14881 function hasJSDocNodes(node) {
14882 var jsDoc = node.jsDoc;
14883 return !!jsDoc && jsDoc.length > 0;
14884 }
14885 ts.hasJSDocNodes = hasJSDocNodes;
14886 /** True if has type node attached to it. */
14887 /* @internal */
14888 function hasType(node) {
14889 return !!node.type;
14890 }
14891 ts.hasType = hasType;
14892 /** True if has initializer node attached to it. */
14893 /* @internal */
14894 function hasInitializer(node) {
14895 return !!node.initializer;
14896 }
14897 ts.hasInitializer = hasInitializer;
14898 /** True if has initializer node attached to it. */
14899 /* @internal */
14900 function hasOnlyExpressionInitializer(node) {
14901 return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node);
14902 }
14903 ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
14904 function isObjectLiteralElement(node) {
14905 return node.kind === 267 /* JsxAttribute */ || node.kind === 269 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
14906 }
14907 ts.isObjectLiteralElement = isObjectLiteralElement;
14908 /* @internal */
14909 function isTypeReferenceType(node) {
14910 return node.kind === 164 /* TypeReference */ || node.kind === 211 /* ExpressionWithTypeArguments */;
14911 }
14912 ts.isTypeReferenceType = isTypeReferenceType;
14913 var MAX_SMI_X86 = 1073741823;
14914 /* @internal */
14915 function guessIndentation(lines) {
14916 var indentation = MAX_SMI_X86;
14917 for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
14918 var line = lines_1[_i];
14919 if (!line.length) {
14920 continue;
14921 }
14922 var i = 0;
14923 for (; i < line.length && i < indentation; i++) {
14924 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
14925 break;
14926 }
14927 }
14928 if (i < indentation) {
14929 indentation = i;
14930 }
14931 if (indentation === 0) {
14932 return 0;
14933 }
14934 }
14935 return indentation === MAX_SMI_X86 ? undefined : indentation;
14936 }
14937 ts.guessIndentation = guessIndentation;
14938 function isStringLiteralLike(node) {
14939 return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
14940 }
14941 ts.isStringLiteralLike = isStringLiteralLike;
14942})(ts || (ts = {}));
14943/* @internal */
14944(function (ts) {
14945 function isNamedImportsOrExports(node) {
14946 return node.kind === 252 /* NamedImports */ || node.kind === 256 /* NamedExports */;
14947 }
14948 ts.isNamedImportsOrExports = isNamedImportsOrExports;
14949 function Symbol(flags, name) {
14950 this.flags = flags;
14951 this.escapedName = name;
14952 this.declarations = undefined;
14953 this.valueDeclaration = undefined;
14954 this.id = undefined;
14955 this.mergeId = undefined;
14956 this.parent = undefined;
14957 }
14958 function Type(checker, flags) {
14959 this.flags = flags;
14960 if (ts.Debug.isDebugging) {
14961 this.checker = checker;
14962 }
14963 }
14964 function Signature() { } // tslint:disable-line no-empty
14965 function Node(kind, pos, end) {
14966 this.pos = pos;
14967 this.end = end;
14968 this.kind = kind;
14969 this.id = 0;
14970 this.flags = 0 /* None */;
14971 this.modifierFlagsCache = 0 /* None */;
14972 this.transformFlags = 0 /* None */;
14973 this.parent = undefined;
14974 this.original = undefined;
14975 }
14976 function SourceMapSource(fileName, text, skipTrivia) {
14977 this.fileName = fileName;
14978 this.text = text;
14979 this.skipTrivia = skipTrivia || (function (pos) { return pos; });
14980 }
14981 ts.objectAllocator = {
14982 getNodeConstructor: function () { return Node; },
14983 getTokenConstructor: function () { return Node; },
14984 getIdentifierConstructor: function () { return Node; },
14985 getSourceFileConstructor: function () { return Node; },
14986 getSymbolConstructor: function () { return Symbol; },
14987 getTypeConstructor: function () { return Type; },
14988 getSignatureConstructor: function () { return Signature; },
14989 getSourceMapSourceConstructor: function () { return SourceMapSource; },
14990 };
14991 function formatStringFromArgs(text, args, baseIndex) {
14992 if (baseIndex === void 0) { baseIndex = 0; }
14993 return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); });
14994 }
14995 ts.formatStringFromArgs = formatStringFromArgs;
14996 function getLocaleSpecificMessage(message) {
14997 return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
14998 }
14999 ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
15000 function createFileDiagnostic(file, start, length, message) {
15001 ts.Debug.assertGreaterThanOrEqual(start, 0);
15002 ts.Debug.assertGreaterThanOrEqual(length, 0);
15003 if (file) {
15004 ts.Debug.assertLessThanOrEqual(start, file.text.length);
15005 ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
15006 }
15007 var text = getLocaleSpecificMessage(message);
15008 if (arguments.length > 4) {
15009 text = formatStringFromArgs(text, arguments, 4);
15010 }
15011 return {
15012 file: file,
15013 start: start,
15014 length: length,
15015 messageText: text,
15016 category: message.category,
15017 code: message.code,
15018 reportsUnnecessary: message.reportsUnnecessary,
15019 };
15020 }
15021 ts.createFileDiagnostic = createFileDiagnostic;
15022 function formatMessage(_dummy, message) {
15023 var text = getLocaleSpecificMessage(message);
15024 if (arguments.length > 2) {
15025 text = formatStringFromArgs(text, arguments, 2);
15026 }
15027 return text;
15028 }
15029 ts.formatMessage = formatMessage;
15030 function createCompilerDiagnostic(message) {
15031 var text = getLocaleSpecificMessage(message);
15032 if (arguments.length > 1) {
15033 text = formatStringFromArgs(text, arguments, 1);
15034 }
15035 return {
15036 file: undefined,
15037 start: undefined,
15038 length: undefined,
15039 messageText: text,
15040 category: message.category,
15041 code: message.code,
15042 reportsUnnecessary: message.reportsUnnecessary,
15043 };
15044 }
15045 ts.createCompilerDiagnostic = createCompilerDiagnostic;
15046 function createCompilerDiagnosticFromMessageChain(chain) {
15047 return {
15048 file: undefined,
15049 start: undefined,
15050 length: undefined,
15051 code: chain.code,
15052 category: chain.category,
15053 messageText: chain.next ? chain : chain.messageText,
15054 };
15055 }
15056 ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
15057 function chainDiagnosticMessages(details, message) {
15058 var text = getLocaleSpecificMessage(message);
15059 if (arguments.length > 2) {
15060 text = formatStringFromArgs(text, arguments, 2);
15061 }
15062 return {
15063 messageText: text,
15064 category: message.category,
15065 code: message.code,
15066 next: details
15067 };
15068 }
15069 ts.chainDiagnosticMessages = chainDiagnosticMessages;
15070 function concatenateDiagnosticMessageChains(headChain, tailChain) {
15071 var lastChain = headChain;
15072 while (lastChain.next) {
15073 lastChain = lastChain.next;
15074 }
15075 lastChain.next = tailChain;
15076 return headChain;
15077 }
15078 ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
15079 function getDiagnosticFilePath(diagnostic) {
15080 return diagnostic.file ? diagnostic.file.path : undefined;
15081 }
15082 function compareDiagnostics(d1, d2) {
15083 return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
15084 compareRelatedInformation(d1, d2) ||
15085 0 /* EqualTo */;
15086 }
15087 ts.compareDiagnostics = compareDiagnostics;
15088 function compareDiagnosticsSkipRelatedInformation(d1, d2) {
15089 return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
15090 ts.compareValues(d1.start, d2.start) ||
15091 ts.compareValues(d1.length, d2.length) ||
15092 ts.compareValues(d1.code, d2.code) ||
15093 compareMessageText(d1.messageText, d2.messageText) ||
15094 0 /* EqualTo */;
15095 }
15096 ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
15097 function compareRelatedInformation(d1, d2) {
15098 if (!d1.relatedInformation && !d2.relatedInformation) {
15099 return 0 /* EqualTo */;
15100 }
15101 if (d1.relatedInformation && d2.relatedInformation) {
15102 return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
15103 var d2i = d2.relatedInformation[index];
15104 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
15105 }) || 0 /* EqualTo */;
15106 }
15107 return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
15108 }
15109 function compareMessageText(t1, t2) {
15110 var text1 = t1;
15111 var text2 = t2;
15112 while (text1 && text2) {
15113 // We still have both chains.
15114 var string1 = ts.isString(text1) ? text1 : text1.messageText;
15115 var string2 = ts.isString(text2) ? text2 : text2.messageText;
15116 var res = ts.compareStringsCaseSensitive(string1, string2);
15117 if (res) {
15118 return res;
15119 }
15120 text1 = ts.isString(text1) ? undefined : text1.next;
15121 text2 = ts.isString(text2) ? undefined : text2.next;
15122 }
15123 if (!text1 && !text2) {
15124 // if the chains are done, then these messages are the same.
15125 return 0 /* EqualTo */;
15126 }
15127 // We still have one chain remaining. The shorter chain should come first.
15128 return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */;
15129 }
15130 function getEmitScriptTarget(compilerOptions) {
15131 return compilerOptions.target || 0 /* ES3 */;
15132 }
15133 ts.getEmitScriptTarget = getEmitScriptTarget;
15134 function getEmitModuleKind(compilerOptions) {
15135 return typeof compilerOptions.module === "number" ?
15136 compilerOptions.module :
15137 getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
15138 }
15139 ts.getEmitModuleKind = getEmitModuleKind;
15140 function getEmitModuleResolutionKind(compilerOptions) {
15141 var moduleResolution = compilerOptions.moduleResolution;
15142 if (moduleResolution === undefined) {
15143 moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
15144 }
15145 return moduleResolution;
15146 }
15147 ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
15148 function hasJsonModuleEmitEnabled(options) {
15149 switch (getEmitModuleKind(options)) {
15150 case ts.ModuleKind.CommonJS:
15151 case ts.ModuleKind.AMD:
15152 case ts.ModuleKind.ES2015:
15153 case ts.ModuleKind.ESNext:
15154 return true;
15155 default:
15156 return false;
15157 }
15158 }
15159 ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
15160 function unreachableCodeIsError(options) {
15161 return options.allowUnreachableCode === false;
15162 }
15163 ts.unreachableCodeIsError = unreachableCodeIsError;
15164 function unusedLabelIsError(options) {
15165 return options.allowUnusedLabels === false;
15166 }
15167 ts.unusedLabelIsError = unusedLabelIsError;
15168 function getAreDeclarationMapsEnabled(options) {
15169 return !!(getEmitDeclarations(options) && options.declarationMap);
15170 }
15171 ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
15172 function getAllowSyntheticDefaultImports(compilerOptions) {
15173 var moduleKind = getEmitModuleKind(compilerOptions);
15174 return compilerOptions.allowSyntheticDefaultImports !== undefined
15175 ? compilerOptions.allowSyntheticDefaultImports
15176 : compilerOptions.esModuleInterop ||
15177 moduleKind === ts.ModuleKind.System;
15178 }
15179 ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
15180 function getEmitDeclarations(compilerOptions) {
15181 return !!(compilerOptions.declaration || compilerOptions.composite);
15182 }
15183 ts.getEmitDeclarations = getEmitDeclarations;
15184 function isIncrementalCompilation(options) {
15185 return !!(options.incremental || options.composite);
15186 }
15187 ts.isIncrementalCompilation = isIncrementalCompilation;
15188 function getStrictOptionValue(compilerOptions, flag) {
15189 return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
15190 }
15191 ts.getStrictOptionValue = getStrictOptionValue;
15192 function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
15193 return oldOptions !== newOptions &&
15194 ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
15195 }
15196 ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
15197 function getCompilerOptionValue(options, option) {
15198 return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
15199 }
15200 ts.getCompilerOptionValue = getCompilerOptionValue;
15201 function hasZeroOrOneAsteriskCharacter(str) {
15202 var seenAsterisk = false;
15203 for (var i = 0; i < str.length; i++) {
15204 if (str.charCodeAt(i) === 42 /* asterisk */) {
15205 if (!seenAsterisk) {
15206 seenAsterisk = true;
15207 }
15208 else {
15209 // have already seen asterisk
15210 return false;
15211 }
15212 }
15213 }
15214 return true;
15215 }
15216 ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
15217 /**
15218 * Internally, we represent paths as strings with '/' as the directory separator.
15219 * When we make system calls (eg: LanguageServiceHost.getDirectory()),
15220 * we expect the host to correctly handle paths in our specified format.
15221 */
15222 ts.directorySeparator = "/";
15223 var altDirectorySeparator = "\\";
15224 var urlSchemeSeparator = "://";
15225 var backslashRegExp = /\\/g;
15226 /**
15227 * Normalize path separators.
15228 */
15229 function normalizeSlashes(path) {
15230 return path.replace(backslashRegExp, ts.directorySeparator);
15231 }
15232 ts.normalizeSlashes = normalizeSlashes;
15233 function isVolumeCharacter(charCode) {
15234 return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
15235 (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
15236 }
15237 function getFileUrlVolumeSeparatorEnd(url, start) {
15238 var ch0 = url.charCodeAt(start);
15239 if (ch0 === 58 /* colon */)
15240 return start + 1;
15241 if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
15242 var ch2 = url.charCodeAt(start + 2);
15243 if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
15244 return start + 3;
15245 }
15246 return -1;
15247 }
15248 /**
15249 * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
15250 * If the root is part of a URL, the twos-complement of the root length is returned.
15251 */
15252 function getEncodedRootLength(path) {
15253 if (!path)
15254 return 0;
15255 var ch0 = path.charCodeAt(0);
15256 // POSIX or UNC
15257 if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
15258 if (path.charCodeAt(1) !== ch0)
15259 return 1; // POSIX: "/" (or non-normalized "\")
15260 var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
15261 if (p1 < 0)
15262 return path.length; // UNC: "//server" or "\\server"
15263 return p1 + 1; // UNC: "//server/" or "\\server\"
15264 }
15265 // DOS
15266 if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
15267 var ch2 = path.charCodeAt(2);
15268 if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
15269 return 3; // DOS: "c:/" or "c:\"
15270 if (path.length === 2)
15271 return 2; // DOS: "c:" (but not "c:d")
15272 }
15273 // URL
15274 var schemeEnd = path.indexOf(urlSchemeSeparator);
15275 if (schemeEnd !== -1) {
15276 var authorityStart = schemeEnd + urlSchemeSeparator.length;
15277 var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
15278 if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
15279 // For local "file" URLs, include the leading DOS volume (if present).
15280 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
15281 // special case interpreted as "the machine from which the URL is being interpreted".
15282 var scheme = path.slice(0, schemeEnd);
15283 var authority = path.slice(authorityStart, authorityEnd);
15284 if (scheme === "file" && (authority === "" || authority === "localhost") &&
15285 isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
15286 var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
15287 if (volumeSeparatorEnd !== -1) {
15288 if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
15289 // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
15290 return ~(volumeSeparatorEnd + 1);
15291 }
15292 if (volumeSeparatorEnd === path.length) {
15293 // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
15294 // but not "file:///c:d" or "file:///c%3ad"
15295 return ~volumeSeparatorEnd;
15296 }
15297 }
15298 }
15299 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
15300 }
15301 return ~path.length; // URL: "file://server", "http://server"
15302 }
15303 // relative
15304 return 0;
15305 }
15306 /**
15307 * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
15308 *
15309 * For example:
15310 * ```ts
15311 * getRootLength("a") === 0 // ""
15312 * getRootLength("/") === 1 // "/"
15313 * getRootLength("c:") === 2 // "c:"
15314 * getRootLength("c:d") === 0 // ""
15315 * getRootLength("c:/") === 3 // "c:/"
15316 * getRootLength("c:\\") === 3 // "c:\\"
15317 * getRootLength("//server") === 7 // "//server"
15318 * getRootLength("//server/share") === 8 // "//server/"
15319 * getRootLength("\\\\server") === 7 // "\\\\server"
15320 * getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
15321 * getRootLength("file:///path") === 8 // "file:///"
15322 * getRootLength("file:///c:") === 10 // "file:///c:"
15323 * getRootLength("file:///c:d") === 8 // "file:///"
15324 * getRootLength("file:///c:/path") === 11 // "file:///c:/"
15325 * getRootLength("file://server") === 13 // "file://server"
15326 * getRootLength("file://server/path") === 14 // "file://server/"
15327 * getRootLength("http://server") === 13 // "http://server"
15328 * getRootLength("http://server/path") === 14 // "http://server/"
15329 * ```
15330 */
15331 function getRootLength(path) {
15332 var rootLength = getEncodedRootLength(path);
15333 return rootLength < 0 ? ~rootLength : rootLength;
15334 }
15335 ts.getRootLength = getRootLength;
15336 // TODO(rbuckton): replace references with `resolvePath`
15337 function normalizePath(path) {
15338 return ts.resolvePath(path);
15339 }
15340 ts.normalizePath = normalizePath;
15341 function normalizePathAndParts(path) {
15342 path = normalizeSlashes(path);
15343 var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
15344 if (parts.length) {
15345 var joinedParts = root + parts.join(ts.directorySeparator);
15346 return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
15347 }
15348 else {
15349 return { path: root, parts: parts };
15350 }
15351 }
15352 ts.normalizePathAndParts = normalizePathAndParts;
15353 function getDirectoryPath(path) {
15354 path = normalizeSlashes(path);
15355 // If the path provided is itself the root, then return it.
15356 var rootLength = getRootLength(path);
15357 if (rootLength === path.length)
15358 return path;
15359 // return the leading portion of the path up to the last (non-terminal) directory separator
15360 // but not including any trailing directory separator.
15361 path = ts.removeTrailingDirectorySeparator(path);
15362 return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
15363 }
15364 ts.getDirectoryPath = getDirectoryPath;
15365 function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
15366 var canonicalFileName = getCanonicalFileName(fileName);
15367 var canonicalDirectoryName = getCanonicalFileName(directoryName);
15368 return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
15369 }
15370 ts.startsWithDirectory = startsWithDirectory;
15371 function isUrl(path) {
15372 return getEncodedRootLength(path) < 0;
15373 }
15374 ts.isUrl = isUrl;
15375 function pathIsRelative(path) {
15376 return /^\.\.?($|[\\/])/.test(path);
15377 }
15378 ts.pathIsRelative = pathIsRelative;
15379 /**
15380 * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path
15381 * like `c:`, `c:\` or `c:/`).
15382 */
15383 function isRootedDiskPath(path) {
15384 return getEncodedRootLength(path) > 0;
15385 }
15386 ts.isRootedDiskPath = isRootedDiskPath;
15387 /**
15388 * Determines whether a path consists only of a path root.
15389 */
15390 function isDiskPathRoot(path) {
15391 var rootLength = getEncodedRootLength(path);
15392 return rootLength > 0 && rootLength === path.length;
15393 }
15394 ts.isDiskPathRoot = isDiskPathRoot;
15395 function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
15396 return !isRootedDiskPath(absoluteOrRelativePath)
15397 ? absoluteOrRelativePath
15398 : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
15399 }
15400 ts.convertToRelativePath = convertToRelativePath;
15401 function pathComponents(path, rootLength) {
15402 var root = path.substring(0, rootLength);
15403 var rest = path.substring(rootLength).split(ts.directorySeparator);
15404 if (rest.length && !ts.lastOrUndefined(rest))
15405 rest.pop();
15406 return [root].concat(rest);
15407 }
15408 /**
15409 * Parse a path into an array containing a root component (at index 0) and zero or more path
15410 * components (at indices > 0). The result is not normalized.
15411 * If the path is relative, the root component is `""`.
15412 * If the path is absolute, the root component includes the first path separator (`/`).
15413 */
15414 function getPathComponents(path, currentDirectory) {
15415 if (currentDirectory === void 0) { currentDirectory = ""; }
15416 path = ts.combinePaths(currentDirectory, path);
15417 var rootLength = getRootLength(path);
15418 return pathComponents(path, rootLength);
15419 }
15420 ts.getPathComponents = getPathComponents;
15421 /**
15422 * Reduce an array of path components to a more simplified path by navigating any
15423 * `"."` or `".."` entries in the path.
15424 */
15425 function reducePathComponents(components) {
15426 if (!ts.some(components))
15427 return [];
15428 var reduced = [components[0]];
15429 for (var i = 1; i < components.length; i++) {
15430 var component = components[i];
15431 if (!component)
15432 continue;
15433 if (component === ".")
15434 continue;
15435 if (component === "..") {
15436 if (reduced.length > 1) {
15437 if (reduced[reduced.length - 1] !== "..") {
15438 reduced.pop();
15439 continue;
15440 }
15441 }
15442 else if (reduced[0])
15443 continue;
15444 }
15445 reduced.push(component);
15446 }
15447 return reduced;
15448 }
15449 ts.reducePathComponents = reducePathComponents;
15450 /**
15451 * Parse a path into an array containing a root component (at index 0) and zero or more path
15452 * components (at indices > 0). The result is normalized.
15453 * If the path is relative, the root component is `""`.
15454 * If the path is absolute, the root component includes the first path separator (`/`).
15455 */
15456 function getNormalizedPathComponents(path, currentDirectory) {
15457 return reducePathComponents(getPathComponents(path, currentDirectory));
15458 }
15459 ts.getNormalizedPathComponents = getNormalizedPathComponents;
15460 function getNormalizedAbsolutePath(fileName, currentDirectory) {
15461 return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
15462 }
15463 ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
15464 /**
15465 * Formats a parsed path consisting of a root component (at index 0) and zero or more path
15466 * segments (at indices > 0).
15467 */
15468 function getPathFromPathComponents(pathComponents) {
15469 if (pathComponents.length === 0)
15470 return "";
15471 var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]);
15472 return root + pathComponents.slice(1).join(ts.directorySeparator);
15473 }
15474 ts.getPathFromPathComponents = getPathFromPathComponents;
15475})(ts || (ts = {}));
15476/* @internal */
15477(function (ts) {
15478 function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
15479 var fromComponents = ts.reducePathComponents(ts.getPathComponents(from));
15480 var toComponents = ts.reducePathComponents(ts.getPathComponents(to));
15481 var start;
15482 for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
15483 var fromComponent = getCanonicalFileName(fromComponents[start]);
15484 var toComponent = getCanonicalFileName(toComponents[start]);
15485 var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
15486 if (!comparer(fromComponent, toComponent))
15487 break;
15488 }
15489 if (start === 0) {
15490 return toComponents;
15491 }
15492 var components = toComponents.slice(start);
15493 var relative = [];
15494 for (; start < fromComponents.length; start++) {
15495 relative.push("..");
15496 }
15497 return [""].concat(relative, components);
15498 }
15499 ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
15500 function getRelativePathFromFile(from, to, getCanonicalFileName) {
15501 return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName));
15502 }
15503 ts.getRelativePathFromFile = getRelativePathFromFile;
15504 function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
15505 Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
15506 var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
15507 var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
15508 var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
15509 return ts.getPathFromPathComponents(pathComponents);
15510 }
15511 ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
15512 function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
15513 var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
15514 var firstComponent = pathComponents[0];
15515 if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) {
15516 var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
15517 pathComponents[0] = prefix + firstComponent;
15518 }
15519 return ts.getPathFromPathComponents(pathComponents);
15520 }
15521 ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
15522 /**
15523 * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
15524 * with `./` or `../`) so as not to be confused with an unprefixed module name.
15525 */
15526 function ensurePathIsNonModuleName(path) {
15527 return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path;
15528 }
15529 ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
15530 function getBaseFileName(path, extensions, ignoreCase) {
15531 path = ts.normalizeSlashes(path);
15532 // if the path provided is itself the root, then it has not file name.
15533 var rootLength = ts.getRootLength(path);
15534 if (rootLength === path.length)
15535 return "";
15536 // return the trailing portion of the path starting after the last (non-terminal) directory
15537 // separator but not including any trailing directory separator.
15538 path = removeTrailingDirectorySeparator(path);
15539 var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
15540 var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
15541 return extension ? name.slice(0, name.length - extension.length) : name;
15542 }
15543 ts.getBaseFileName = getBaseFileName;
15544 /**
15545 * Combines paths. If a path is absolute, it replaces any previous path.
15546 */
15547 function combinePaths(path) {
15548 var paths = [];
15549 for (var _i = 1; _i < arguments.length; _i++) {
15550 paths[_i - 1] = arguments[_i];
15551 }
15552 if (path)
15553 path = ts.normalizeSlashes(path);
15554 for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
15555 var relativePath = paths_1[_a];
15556 if (!relativePath)
15557 continue;
15558 relativePath = ts.normalizeSlashes(relativePath);
15559 if (!path || ts.getRootLength(relativePath) !== 0) {
15560 path = relativePath;
15561 }
15562 else {
15563 path = ensureTrailingDirectorySeparator(path) + relativePath;
15564 }
15565 }
15566 return path;
15567 }
15568 ts.combinePaths = combinePaths;
15569 /**
15570 * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
15571 * `.` and `..` path components are resolved.
15572 */
15573 function resolvePath(path) {
15574 var paths = [];
15575 for (var _i = 1; _i < arguments.length; _i++) {
15576 paths[_i - 1] = arguments[_i];
15577 }
15578 var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path);
15579 var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined)));
15580 return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
15581 }
15582 ts.resolvePath = resolvePath;
15583 /**
15584 * Determines whether a path has a trailing separator (`/` or `\\`).
15585 */
15586 function hasTrailingDirectorySeparator(path) {
15587 if (path.length === 0)
15588 return false;
15589 var ch = path.charCodeAt(path.length - 1);
15590 return ch === 47 /* slash */ || ch === 92 /* backslash */;
15591 }
15592 ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
15593 function removeTrailingDirectorySeparator(path) {
15594 if (hasTrailingDirectorySeparator(path)) {
15595 return path.substr(0, path.length - 1);
15596 }
15597 return path;
15598 }
15599 ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
15600 function ensureTrailingDirectorySeparator(path) {
15601 if (!hasTrailingDirectorySeparator(path)) {
15602 return path + ts.directorySeparator;
15603 }
15604 return path;
15605 }
15606 ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
15607 // check path for these segments: '', '.'. '..'
15608 var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
15609 function comparePathsWorker(a, b, componentComparer) {
15610 if (a === b)
15611 return 0 /* EqualTo */;
15612 if (a === undefined)
15613 return -1 /* LessThan */;
15614 if (b === undefined)
15615 return 1 /* GreaterThan */;
15616 // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
15617 // need to perform path reduction.
15618 var aRoot = a.substring(0, ts.getRootLength(a));
15619 var bRoot = b.substring(0, ts.getRootLength(b));
15620 var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
15621 if (result !== 0 /* EqualTo */) {
15622 return result;
15623 }
15624 // NOTE: Performance optimization - shortcut if there are no relative path segments in
15625 // the non-root portion of the path
15626 var aRest = a.substring(aRoot.length);
15627 var bRest = b.substring(bRoot.length);
15628 if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
15629 return componentComparer(aRest, bRest);
15630 }
15631 // The path contains a relative path segment. Normalize the paths and perform a slower component
15632 // by component comparison.
15633 var aComponents = ts.reducePathComponents(ts.getPathComponents(a));
15634 var bComponents = ts.reducePathComponents(ts.getPathComponents(b));
15635 var sharedLength = Math.min(aComponents.length, bComponents.length);
15636 for (var i = 1; i < sharedLength; i++) {
15637 var result_1 = componentComparer(aComponents[i], bComponents[i]);
15638 if (result_1 !== 0 /* EqualTo */) {
15639 return result_1;
15640 }
15641 }
15642 return ts.compareValues(aComponents.length, bComponents.length);
15643 }
15644 /**
15645 * Performs a case-sensitive comparison of two paths.
15646 */
15647 function comparePathsCaseSensitive(a, b) {
15648 return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
15649 }
15650 ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
15651 /**
15652 * Performs a case-insensitive comparison of two paths.
15653 */
15654 function comparePathsCaseInsensitive(a, b) {
15655 return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
15656 }
15657 ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
15658 function comparePaths(a, b, currentDirectory, ignoreCase) {
15659 if (typeof currentDirectory === "string") {
15660 a = combinePaths(currentDirectory, a);
15661 b = combinePaths(currentDirectory, b);
15662 }
15663 else if (typeof currentDirectory === "boolean") {
15664 ignoreCase = currentDirectory;
15665 }
15666 return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
15667 }
15668 ts.comparePaths = comparePaths;
15669 function containsPath(parent, child, currentDirectory, ignoreCase) {
15670 if (typeof currentDirectory === "string") {
15671 parent = combinePaths(currentDirectory, parent);
15672 child = combinePaths(currentDirectory, child);
15673 }
15674 else if (typeof currentDirectory === "boolean") {
15675 ignoreCase = currentDirectory;
15676 }
15677 if (parent === undefined || child === undefined)
15678 return false;
15679 if (parent === child)
15680 return true;
15681 var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent));
15682 var childComponents = ts.reducePathComponents(ts.getPathComponents(child));
15683 if (childComponents.length < parentComponents.length) {
15684 return false;
15685 }
15686 var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
15687 for (var i = 0; i < parentComponents.length; i++) {
15688 var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
15689 if (!equalityComparer(parentComponents[i], childComponents[i])) {
15690 return false;
15691 }
15692 }
15693 return true;
15694 }
15695 ts.containsPath = containsPath;
15696 function isDirectorySeparator(charCode) {
15697 return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
15698 }
15699 function stripLeadingDirectorySeparator(s) {
15700 return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
15701 }
15702 function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
15703 var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
15704 return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
15705 }
15706 ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
15707 // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
15708 // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
15709 // proof.
15710 var reservedCharacterPattern = /[^\w\s\/]/g;
15711 function regExpEscape(text) {
15712 return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
15713 }
15714 ts.regExpEscape = regExpEscape;
15715 function escapeRegExpCharacter(match) {
15716 return "\\" + match;
15717 }
15718 var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
15719 function hasExtension(fileName) {
15720 return ts.stringContains(getBaseFileName(fileName), ".");
15721 }
15722 ts.hasExtension = hasExtension;
15723 ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
15724 var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
15725 var filesMatcher = {
15726 /**
15727 * Matches any single directory segment unless it is the last segment and a .min.js file
15728 * Breakdown:
15729 * [^./] # matches everything up to the first . character (excluding directory separators)
15730 * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension
15731 */
15732 singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
15733 /**
15734 * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
15735 * files or directories, does not match subdirectories that start with a . character
15736 */
15737 doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
15738 replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
15739 };
15740 var directoriesMatcher = {
15741 singleAsteriskRegexFragment: "[^/]*",
15742 /**
15743 * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
15744 * files or directories, does not match subdirectories that start with a . character
15745 */
15746 doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
15747 replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
15748 };
15749 var excludeMatcher = {
15750 singleAsteriskRegexFragment: "[^/]*",
15751 doubleAsteriskRegexFragment: "(/.+?)?",
15752 replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
15753 };
15754 var wildcardMatchers = {
15755 files: filesMatcher,
15756 directories: directoriesMatcher,
15757 exclude: excludeMatcher
15758 };
15759 function getRegularExpressionForWildcard(specs, basePath, usage) {
15760 var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
15761 if (!patterns || !patterns.length) {
15762 return undefined;
15763 }
15764 var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
15765 // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
15766 var terminator = usage === "exclude" ? "($|/)" : "$";
15767 return "^(" + pattern + ")" + terminator;
15768 }
15769 ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
15770 function getRegularExpressionsForWildcards(specs, basePath, usage) {
15771 if (specs === undefined || specs.length === 0) {
15772 return undefined;
15773 }
15774 return ts.flatMap(specs, function (spec) {
15775 return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
15776 });
15777 }
15778 ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
15779 /**
15780 * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
15781 * and does not contain any glob characters itself.
15782 */
15783 function isImplicitGlob(lastPathComponent) {
15784 return !/[.*?]/.test(lastPathComponent);
15785 }
15786 ts.isImplicitGlob = isImplicitGlob;
15787 function getSubPatternFromSpec(spec, basePath, usage, _a) {
15788 var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
15789 var subpattern = "";
15790 var hasWrittenComponent = false;
15791 var components = ts.getNormalizedPathComponents(spec, basePath);
15792 var lastComponent = ts.last(components);
15793 if (usage !== "exclude" && lastComponent === "**") {
15794 return undefined;
15795 }
15796 // getNormalizedPathComponents includes the separator for the root component.
15797 // We need to remove to create our regex correctly.
15798 components[0] = removeTrailingDirectorySeparator(components[0]);
15799 if (isImplicitGlob(lastComponent)) {
15800 components.push("**", "*");
15801 }
15802 var optionalCount = 0;
15803 for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
15804 var component = components_1[_i];
15805 if (component === "**") {
15806 subpattern += doubleAsteriskRegexFragment;
15807 }
15808 else {
15809 if (usage === "directories") {
15810 subpattern += "(";
15811 optionalCount++;
15812 }
15813 if (hasWrittenComponent) {
15814 subpattern += ts.directorySeparator;
15815 }
15816 if (usage !== "exclude") {
15817 var componentPattern = "";
15818 // The * and ? wildcards should not match directories or files that start with . if they
15819 // appear first in a component. Dotted directories and files can be included explicitly
15820 // like so: **/.*/.*
15821 if (component.charCodeAt(0) === 42 /* asterisk */) {
15822 componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
15823 component = component.substr(1);
15824 }
15825 else if (component.charCodeAt(0) === 63 /* question */) {
15826 componentPattern += "[^./]";
15827 component = component.substr(1);
15828 }
15829 componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
15830 // Patterns should not include subfolders like node_modules unless they are
15831 // explicitly included as part of the path.
15832 //
15833 // As an optimization, if the component pattern is the same as the component,
15834 // then there definitely were no wildcard characters and we do not need to
15835 // add the exclusion pattern.
15836 if (componentPattern !== component) {
15837 subpattern += implicitExcludePathRegexPattern;
15838 }
15839 subpattern += componentPattern;
15840 }
15841 else {
15842 subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
15843 }
15844 }
15845 hasWrittenComponent = true;
15846 }
15847 while (optionalCount > 0) {
15848 subpattern += ")?";
15849 optionalCount--;
15850 }
15851 return subpattern;
15852 }
15853 function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
15854 return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
15855 }
15856 /** @param path directory of the tsconfig.json */
15857 function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
15858 path = ts.normalizePath(path);
15859 currentDirectory = ts.normalizePath(currentDirectory);
15860 var absolutePath = combinePaths(currentDirectory, path);
15861 return {
15862 includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
15863 includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
15864 includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
15865 excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
15866 basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
15867 };
15868 }
15869 ts.getFileMatcherPatterns = getFileMatcherPatterns;
15870 function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
15871 return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
15872 }
15873 ts.getRegexFromPattern = getRegexFromPattern;
15874 /** @param path directory of the tsconfig.json */
15875 function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
15876 path = ts.normalizePath(path);
15877 currentDirectory = ts.normalizePath(currentDirectory);
15878 var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
15879 var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
15880 var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
15881 var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
15882 // Associate an array of results with each include regex. This keeps results in order of the "include" order.
15883 // If there are no "includes", then just put everything in results[0].
15884 var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
15885 var visited = ts.createMap();
15886 var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
15887 for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
15888 var basePath = _a[_i];
15889 visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
15890 }
15891 return ts.flatten(results);
15892 function visitDirectory(path, absolutePath, depth) {
15893 var canonicalPath = toCanonical(realpath(absolutePath));
15894 if (visited.has(canonicalPath))
15895 return;
15896 visited.set(canonicalPath, true);
15897 var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
15898 var _loop_1 = function (current) {
15899 var name = combinePaths(path, current);
15900 var absoluteName = combinePaths(absolutePath, current);
15901 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
15902 return "continue";
15903 if (excludeRegex && excludeRegex.test(absoluteName))
15904 return "continue";
15905 if (!includeFileRegexes) {
15906 results[0].push(name);
15907 }
15908 else {
15909 var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
15910 if (includeIndex !== -1) {
15911 results[includeIndex].push(name);
15912 }
15913 }
15914 };
15915 for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
15916 var current = _b[_i];
15917 _loop_1(current);
15918 }
15919 if (depth !== undefined) {
15920 depth--;
15921 if (depth === 0) {
15922 return;
15923 }
15924 }
15925 for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
15926 var current = _d[_c];
15927 var name = combinePaths(path, current);
15928 var absoluteName = combinePaths(absolutePath, current);
15929 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
15930 (!excludeRegex || !excludeRegex.test(absoluteName))) {
15931 visitDirectory(name, absoluteName, depth);
15932 }
15933 }
15934 }
15935 }
15936 ts.matchFiles = matchFiles;
15937 /**
15938 * Computes the unique non-wildcard base paths amongst the provided include patterns.
15939 */
15940 function getBasePaths(path, includes, useCaseSensitiveFileNames) {
15941 // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
15942 var basePaths = [path];
15943 if (includes) {
15944 // Storage for literal base paths amongst the include patterns.
15945 var includeBasePaths = [];
15946 for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
15947 var include = includes_1[_i];
15948 // We also need to check the relative paths by converting them to absolute and normalizing
15949 // in case they escape the base path (e.g "..\somedirectory")
15950 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include));
15951 // Append the literal and canonical candidate base paths.
15952 includeBasePaths.push(getIncludeBasePath(absolute));
15953 }
15954 // Sort the offsets array using either the literal or canonical path representations.
15955 includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
15956 var _loop_2 = function (includeBasePath) {
15957 if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
15958 basePaths.push(includeBasePath);
15959 }
15960 };
15961 // Iterate over each include base path and include unique base paths that are not a
15962 // subpath of an existing base path
15963 for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
15964 var includeBasePath = includeBasePaths_1[_a];
15965 _loop_2(includeBasePath);
15966 }
15967 }
15968 return basePaths;
15969 }
15970 function getIncludeBasePath(absolute) {
15971 var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
15972 if (wildcardOffset < 0) {
15973 // No "*" or "?" in the path
15974 return !hasExtension(absolute)
15975 ? absolute
15976 : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
15977 }
15978 return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
15979 }
15980 function ensureScriptKind(fileName, scriptKind) {
15981 // Using scriptKind as a condition handles both:
15982 // - 'scriptKind' is unspecified and thus it is `undefined`
15983 // - 'scriptKind' is set and it is `Unknown` (0)
15984 // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
15985 // to get the ScriptKind from the file name. If it cannot be resolved
15986 // from the file name then the default 'TS' script kind is returned.
15987 return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
15988 }
15989 ts.ensureScriptKind = ensureScriptKind;
15990 function getScriptKindFromFileName(fileName) {
15991 var ext = fileName.substr(fileName.lastIndexOf("."));
15992 switch (ext.toLowerCase()) {
15993 case ".js" /* Js */:
15994 return 1 /* JS */;
15995 case ".jsx" /* Jsx */:
15996 return 2 /* JSX */;
15997 case ".ts" /* Ts */:
15998 return 3 /* TS */;
15999 case ".tsx" /* Tsx */:
16000 return 4 /* TSX */;
16001 case ".json" /* Json */:
16002 return 6 /* JSON */;
16003 default:
16004 return 0 /* Unknown */;
16005 }
16006 }
16007 ts.getScriptKindFromFileName = getScriptKindFromFileName;
16008 /**
16009 * List of supported extensions in order of file resolution precedence.
16010 */
16011 ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
16012 ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
16013 /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
16014 ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
16015 ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
16016 ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
16017 var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions);
16018 var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]);
16019 function getSupportedExtensions(options, extraFileExtensions) {
16020 var needJsExtensions = options && options.allowJs;
16021 if (!extraFileExtensions || extraFileExtensions.length === 0) {
16022 return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
16023 }
16024 var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
16025 return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
16026 }
16027 ts.getSupportedExtensions = getSupportedExtensions;
16028 function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
16029 if (!options || !options.resolveJsonModule) {
16030 return supportedExtensions;
16031 }
16032 if (supportedExtensions === allSupportedExtensions) {
16033 return allSupportedExtensionsWithJson;
16034 }
16035 if (supportedExtensions === ts.supportedTSExtensions) {
16036 return ts.supportedTSExtensionsWithJson;
16037 }
16038 return supportedExtensions.concat([".json" /* Json */]);
16039 }
16040 ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
16041 function isJSLike(scriptKind) {
16042 return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
16043 }
16044 function hasJSFileExtension(fileName) {
16045 return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
16046 }
16047 ts.hasJSFileExtension = hasJSFileExtension;
16048 function hasJSOrJsonFileExtension(fileName) {
16049 return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); });
16050 }
16051 ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension;
16052 function hasTSFileExtension(fileName) {
16053 return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
16054 }
16055 ts.hasTSFileExtension = hasTSFileExtension;
16056 function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
16057 if (!fileName) {
16058 return false;
16059 }
16060 var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
16061 for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
16062 var extension = _a[_i];
16063 if (ts.fileExtensionIs(fileName, extension)) {
16064 return true;
16065 }
16066 }
16067 return false;
16068 }
16069 ts.isSupportedSourceFileName = isSupportedSourceFileName;
16070 /**
16071 * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
16072 * aligned to the offset of the highest priority extension in the
16073 * allSupportedExtensions array.
16074 */
16075 var ExtensionPriority;
16076 (function (ExtensionPriority) {
16077 ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
16078 ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
16079 ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
16080 ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
16081 })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
16082 function getExtensionPriority(path, supportedExtensions) {
16083 for (var i = supportedExtensions.length - 1; i >= 0; i--) {
16084 if (ts.fileExtensionIs(path, supportedExtensions[i])) {
16085 return adjustExtensionPriority(i, supportedExtensions);
16086 }
16087 }
16088 // If its not in the list of supported extensions, this is likely a
16089 // TypeScript file with a non-ts extension
16090 return 0 /* Highest */;
16091 }
16092 ts.getExtensionPriority = getExtensionPriority;
16093 /**
16094 * Adjusts an extension priority to be the highest priority within the same range.
16095 */
16096 function adjustExtensionPriority(extensionPriority, supportedExtensions) {
16097 if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
16098 return 0 /* TypeScriptFiles */;
16099 }
16100 else if (extensionPriority < supportedExtensions.length) {
16101 return 2 /* DeclarationAndJavaScriptFiles */;
16102 }
16103 else {
16104 return supportedExtensions.length;
16105 }
16106 }
16107 ts.adjustExtensionPriority = adjustExtensionPriority;
16108 /**
16109 * Gets the next lowest extension priority for a given priority.
16110 */
16111 function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
16112 if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
16113 return 2 /* DeclarationAndJavaScriptFiles */;
16114 }
16115 else {
16116 return supportedExtensions.length;
16117 }
16118 }
16119 ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
16120 var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
16121 function removeFileExtension(path) {
16122 for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
16123 var ext = extensionsToRemove_1[_i];
16124 var extensionless = tryRemoveExtension(path, ext);
16125 if (extensionless !== undefined) {
16126 return extensionless;
16127 }
16128 }
16129 return path;
16130 }
16131 ts.removeFileExtension = removeFileExtension;
16132 function tryRemoveExtension(path, extension) {
16133 return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
16134 }
16135 ts.tryRemoveExtension = tryRemoveExtension;
16136 function removeExtension(path, extension) {
16137 return path.substring(0, path.length - extension.length);
16138 }
16139 ts.removeExtension = removeExtension;
16140 function changeExtension(path, newExtension) {
16141 return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
16142 }
16143 ts.changeExtension = changeExtension;
16144 function changeAnyExtension(path, ext, extensions, ignoreCase) {
16145 var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
16146 return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
16147 }
16148 ts.changeAnyExtension = changeAnyExtension;
16149 var Debug;
16150 (function (Debug) {
16151 function showSymbol(symbol) {
16152 var symbolFlags = ts.SymbolFlags;
16153 return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + ts.map(symbol.declarations, showSyntaxKind) + " }";
16154 }
16155 Debug.showSymbol = showSymbol;
16156 function showFlags(flags, flagsEnum) {
16157 var out = [];
16158 for (var pow = 0; pow <= 30; pow++) {
16159 var n = 1 << pow;
16160 if (flags & n) {
16161 out.push(flagsEnum[n]);
16162 }
16163 }
16164 return out.join("|");
16165 }
16166 function showSyntaxKind(node) {
16167 var syntaxKind = ts.SyntaxKind;
16168 return syntaxKind ? syntaxKind[node.kind] : node.kind.toString();
16169 }
16170 Debug.showSyntaxKind = showSyntaxKind;
16171 })(Debug = ts.Debug || (ts.Debug = {}));
16172 function tryParsePattern(pattern) {
16173 // This should be verified outside of here and a proper error thrown.
16174 Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern));
16175 var indexOfStar = pattern.indexOf("*");
16176 return indexOfStar === -1 ? undefined : {
16177 prefix: pattern.substr(0, indexOfStar),
16178 suffix: pattern.substr(indexOfStar + 1)
16179 };
16180 }
16181 ts.tryParsePattern = tryParsePattern;
16182 function positionIsSynthesized(pos) {
16183 // This is a fast way of testing the following conditions:
16184 // pos === undefined || pos === null || isNaN(pos) || pos < 0;
16185 return !(pos >= 0);
16186 }
16187 ts.positionIsSynthesized = positionIsSynthesized;
16188 /** True if an extension is one of the supported TypeScript extensions. */
16189 function extensionIsTS(ext) {
16190 return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
16191 }
16192 ts.extensionIsTS = extensionIsTS;
16193 function resolutionExtensionIsTSOrJson(ext) {
16194 return extensionIsTS(ext) || ext === ".json" /* Json */;
16195 }
16196 ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
16197 /**
16198 * Gets the extension from a path.
16199 * Path must have a valid extension.
16200 */
16201 function extensionFromPath(path) {
16202 var ext = tryGetExtensionFromPath(path);
16203 return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension.");
16204 }
16205 ts.extensionFromPath = extensionFromPath;
16206 function isAnySupportedFileExtension(path) {
16207 return tryGetExtensionFromPath(path) !== undefined;
16208 }
16209 ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
16210 function tryGetExtensionFromPath(path) {
16211 return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
16212 }
16213 ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
16214 function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
16215 if (typeof extensions === "string")
16216 extensions = [extensions];
16217 for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
16218 var extension = extensions_2[_i];
16219 if (!ts.startsWith(extension, "."))
16220 extension = "." + extension;
16221 if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") {
16222 var pathExtension = path.slice(path.length - extension.length);
16223 if (stringEqualityComparer(pathExtension, extension)) {
16224 return pathExtension;
16225 }
16226 }
16227 }
16228 return "";
16229 }
16230 function getAnyExtensionFromPath(path, extensions, ignoreCase) {
16231 // Retrieves any string from the final "." onwards from a base file name.
16232 // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
16233 if (extensions) {
16234 return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
16235 }
16236 var baseFileName = getBaseFileName(path);
16237 var extensionIndex = baseFileName.lastIndexOf(".");
16238 if (extensionIndex >= 0) {
16239 return baseFileName.substring(extensionIndex);
16240 }
16241 return "";
16242 }
16243 ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
16244 function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
16245 return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
16246 }
16247 ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
16248 ts.emptyFileSystemEntries = {
16249 files: ts.emptyArray,
16250 directories: ts.emptyArray
16251 };
16252 /**
16253 * patternStrings contains both pattern strings (containing "*") and regular strings.
16254 * Return an exact match if possible, or a pattern match, or undefined.
16255 * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
16256 */
16257 function matchPatternOrExact(patternStrings, candidate) {
16258 var patterns = [];
16259 for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
16260 var patternString = patternStrings_1[_i];
16261 var pattern = tryParsePattern(patternString);
16262 if (pattern) {
16263 patterns.push(pattern);
16264 }
16265 else if (patternString === candidate) {
16266 // pattern was matched as is - no need to search further
16267 return patternString;
16268 }
16269 }
16270 return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
16271 }
16272 ts.matchPatternOrExact = matchPatternOrExact;
16273 function sliceAfter(arr, value) {
16274 var index = arr.indexOf(value);
16275 Debug.assert(index !== -1);
16276 return arr.slice(index);
16277 }
16278 ts.sliceAfter = sliceAfter;
16279 function addRelatedInfo(diagnostic) {
16280 var _a;
16281 var relatedInformation = [];
16282 for (var _i = 1; _i < arguments.length; _i++) {
16283 relatedInformation[_i - 1] = arguments[_i];
16284 }
16285 if (!diagnostic.relatedInformation) {
16286 diagnostic.relatedInformation = [];
16287 }
16288 (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
16289 return diagnostic;
16290 }
16291 ts.addRelatedInfo = addRelatedInfo;
16292 function minAndMax(arr, getValue) {
16293 Debug.assert(arr.length !== 0);
16294 var min = getValue(arr[0]);
16295 var max = min;
16296 for (var i = 1; i < arr.length; i++) {
16297 var value = getValue(arr[i]);
16298 if (value < min) {
16299 min = value;
16300 }
16301 else if (value > max) {
16302 max = value;
16303 }
16304 }
16305 return { min: min, max: max };
16306 }
16307 ts.minAndMax = minAndMax;
16308 var NodeSet = /** @class */ (function () {
16309 function NodeSet() {
16310 this.map = ts.createMap();
16311 }
16312 NodeSet.prototype.add = function (node) {
16313 this.map.set(String(ts.getNodeId(node)), node);
16314 };
16315 NodeSet.prototype.tryAdd = function (node) {
16316 if (this.has(node))
16317 return false;
16318 this.add(node);
16319 return true;
16320 };
16321 NodeSet.prototype.has = function (node) {
16322 return this.map.has(String(ts.getNodeId(node)));
16323 };
16324 NodeSet.prototype.forEach = function (cb) {
16325 this.map.forEach(cb);
16326 };
16327 NodeSet.prototype.some = function (pred) {
16328 return ts.forEachEntry(this.map, pred) || false;
16329 };
16330 return NodeSet;
16331 }());
16332 ts.NodeSet = NodeSet;
16333 var NodeMap = /** @class */ (function () {
16334 function NodeMap() {
16335 this.map = ts.createMap();
16336 }
16337 NodeMap.prototype.get = function (node) {
16338 var res = this.map.get(String(ts.getNodeId(node)));
16339 return res && res.value;
16340 };
16341 NodeMap.prototype.getOrUpdate = function (node, setValue) {
16342 var res = this.get(node);
16343 if (res)
16344 return res;
16345 var value = setValue();
16346 this.set(node, value);
16347 return value;
16348 };
16349 NodeMap.prototype.set = function (node, value) {
16350 this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
16351 };
16352 NodeMap.prototype.has = function (node) {
16353 return this.map.has(String(ts.getNodeId(node)));
16354 };
16355 NodeMap.prototype.forEach = function (cb) {
16356 this.map.forEach(function (_a) {
16357 var node = _a.node, value = _a.value;
16358 return cb(value, node);
16359 });
16360 };
16361 return NodeMap;
16362 }());
16363 ts.NodeMap = NodeMap;
16364 function rangeOfNode(node) {
16365 return { pos: ts.getTokenPosOfNode(node), end: node.end };
16366 }
16367 ts.rangeOfNode = rangeOfNode;
16368 function rangeOfTypeParameters(typeParameters) {
16369 // Include the `<>`
16370 return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
16371 }
16372 ts.rangeOfTypeParameters = rangeOfTypeParameters;
16373 function skipTypeChecking(sourceFile, options) {
16374 // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
16375 // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
16376 // '/// <reference no-default-lib="true"/>' directive.
16377 return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib;
16378 }
16379 ts.skipTypeChecking = skipTypeChecking;
16380 function isJsonEqual(a, b) {
16381 return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
16382 }
16383 ts.isJsonEqual = isJsonEqual;
16384 function getOrUpdate(map, key, getDefault) {
16385 var got = map.get(key);
16386 if (got === undefined) {
16387 var value = getDefault();
16388 map.set(key, value);
16389 return value;
16390 }
16391 else {
16392 return got;
16393 }
16394 }
16395 ts.getOrUpdate = getOrUpdate;
16396 /**
16397 * Converts a bigint literal string, e.g. `0x1234n`,
16398 * to its decimal string representation, e.g. `4660`.
16399 */
16400 function parsePseudoBigInt(stringValue) {
16401 var log2Base;
16402 switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
16403 case 98 /* b */:
16404 case 66 /* B */: // 0b or 0B
16405 log2Base = 1;
16406 break;
16407 case 111 /* o */:
16408 case 79 /* O */: // 0o or 0O
16409 log2Base = 3;
16410 break;
16411 case 120 /* x */:
16412 case 88 /* X */: // 0x or 0X
16413 log2Base = 4;
16414 break;
16415 default: // already in decimal; omit trailing "n"
16416 var nIndex = stringValue.length - 1;
16417 // Skip leading 0s
16418 var nonZeroStart = 0;
16419 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
16420 nonZeroStart++;
16421 }
16422 return stringValue.slice(nonZeroStart, nIndex) || "0";
16423 }
16424 // Omit leading "0b", "0o", or "0x", and trailing "n"
16425 var startIndex = 2, endIndex = stringValue.length - 1;
16426 var bitsNeeded = (endIndex - startIndex) * log2Base;
16427 // Stores the value specified by the string as a LE array of 16-bit integers
16428 // using Uint16 instead of Uint32 so combining steps can use bitwise operators
16429 var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
16430 // Add the digits, one at a time
16431 for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
16432 var segment = bitOffset >>> 4;
16433 var digitChar = stringValue.charCodeAt(i);
16434 // Find character range: 0-9 < A-F < a-f
16435 var digit = digitChar <= 57 /* _9 */
16436 ? digitChar - 48 /* _0 */
16437 : 10 + digitChar -
16438 (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
16439 var shiftedDigit = digit << (bitOffset & 15);
16440 segments[segment] |= shiftedDigit;
16441 var residual = shiftedDigit >>> 16;
16442 if (residual)
16443 segments[segment + 1] |= residual; // overflows segment
16444 }
16445 // Repeatedly divide segments by 10 and add remainder to base10Value
16446 var base10Value = "";
16447 var firstNonzeroSegment = segments.length - 1;
16448 var segmentsRemaining = true;
16449 while (segmentsRemaining) {
16450 var mod10 = 0;
16451 segmentsRemaining = false;
16452 for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
16453 var newSegment = mod10 << 16 | segments[segment];
16454 var segmentValue = (newSegment / 10) | 0;
16455 segments[segment] = segmentValue;
16456 mod10 = newSegment - segmentValue * 10;
16457 if (segmentValue && !segmentsRemaining) {
16458 firstNonzeroSegment = segment;
16459 segmentsRemaining = true;
16460 }
16461 }
16462 base10Value = mod10 + base10Value;
16463 }
16464 return base10Value;
16465 }
16466 ts.parsePseudoBigInt = parsePseudoBigInt;
16467 function pseudoBigIntToString(_a) {
16468 var negative = _a.negative, base10Value = _a.base10Value;
16469 return (negative && base10Value !== "0" ? "-" : "") + base10Value;
16470 }
16471 ts.pseudoBigIntToString = pseudoBigIntToString;
16472})(ts || (ts = {}));
16473var ts;
16474(function (ts) {
16475 var SignatureFlags;
16476 (function (SignatureFlags) {
16477 SignatureFlags[SignatureFlags["None"] = 0] = "None";
16478 SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
16479 SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
16480 SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
16481 SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
16482 SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
16483 })(SignatureFlags || (SignatureFlags = {}));
16484 // tslint:disable variable-name
16485 var NodeConstructor;
16486 var TokenConstructor;
16487 var IdentifierConstructor;
16488 var SourceFileConstructor;
16489 // tslint:enable variable-name
16490 function createNode(kind, pos, end) {
16491 if (kind === 284 /* SourceFile */) {
16492 return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
16493 }
16494 else if (kind === 72 /* Identifier */) {
16495 return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
16496 }
16497 else if (!ts.isNodeKind(kind)) {
16498 return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
16499 }
16500 else {
16501 return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
16502 }
16503 }
16504 ts.createNode = createNode;
16505 function visitNode(cbNode, node) {
16506 return node && cbNode(node);
16507 }
16508 function visitNodes(cbNode, cbNodes, nodes) {
16509 if (nodes) {
16510 if (cbNodes) {
16511 return cbNodes(nodes);
16512 }
16513 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
16514 var node = nodes_1[_i];
16515 var result = cbNode(node);
16516 if (result) {
16517 return result;
16518 }
16519 }
16520 }
16521 }
16522 /*@internal*/
16523 function isJSDocLikeText(text, start) {
16524 return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
16525 text.charCodeAt(start + 2) === 42 /* asterisk */ &&
16526 text.charCodeAt(start + 3) !== 47 /* slash */;
16527 }
16528 ts.isJSDocLikeText = isJSDocLikeText;
16529 /**
16530 * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
16531 * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
16532 * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
16533 * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
16534 *
16535 * @param node a given node to visit its children
16536 * @param cbNode a callback to be invoked for all child nodes
16537 * @param cbNodes a callback to be invoked for embedded array
16538 *
16539 * @remarks `forEachChild` must visit the children of a node in the order
16540 * that they appear in the source code. The language service depends on this property to locate nodes by position.
16541 */
16542 function forEachChild(node, cbNode, cbNodes) {
16543 if (!node || node.kind <= 147 /* LastToken */) {
16544 return;
16545 }
16546 switch (node.kind) {
16547 case 148 /* QualifiedName */:
16548 return visitNode(cbNode, node.left) ||
16549 visitNode(cbNode, node.right);
16550 case 150 /* TypeParameter */:
16551 return visitNode(cbNode, node.name) ||
16552 visitNode(cbNode, node.constraint) ||
16553 visitNode(cbNode, node.default) ||
16554 visitNode(cbNode, node.expression);
16555 case 276 /* ShorthandPropertyAssignment */:
16556 return visitNodes(cbNode, cbNodes, node.decorators) ||
16557 visitNodes(cbNode, cbNodes, node.modifiers) ||
16558 visitNode(cbNode, node.name) ||
16559 visitNode(cbNode, node.questionToken) ||
16560 visitNode(cbNode, node.exclamationToken) ||
16561 visitNode(cbNode, node.equalsToken) ||
16562 visitNode(cbNode, node.objectAssignmentInitializer);
16563 case 277 /* SpreadAssignment */:
16564 return visitNode(cbNode, node.expression);
16565 case 151 /* Parameter */:
16566 return visitNodes(cbNode, cbNodes, node.decorators) ||
16567 visitNodes(cbNode, cbNodes, node.modifiers) ||
16568 visitNode(cbNode, node.dotDotDotToken) ||
16569 visitNode(cbNode, node.name) ||
16570 visitNode(cbNode, node.questionToken) ||
16571 visitNode(cbNode, node.type) ||
16572 visitNode(cbNode, node.initializer);
16573 case 154 /* PropertyDeclaration */:
16574 return visitNodes(cbNode, cbNodes, node.decorators) ||
16575 visitNodes(cbNode, cbNodes, node.modifiers) ||
16576 visitNode(cbNode, node.name) ||
16577 visitNode(cbNode, node.questionToken) ||
16578 visitNode(cbNode, node.exclamationToken) ||
16579 visitNode(cbNode, node.type) ||
16580 visitNode(cbNode, node.initializer);
16581 case 153 /* PropertySignature */:
16582 return visitNodes(cbNode, cbNodes, node.decorators) ||
16583 visitNodes(cbNode, cbNodes, node.modifiers) ||
16584 visitNode(cbNode, node.name) ||
16585 visitNode(cbNode, node.questionToken) ||
16586 visitNode(cbNode, node.type) ||
16587 visitNode(cbNode, node.initializer);
16588 case 275 /* PropertyAssignment */:
16589 return visitNodes(cbNode, cbNodes, node.decorators) ||
16590 visitNodes(cbNode, cbNodes, node.modifiers) ||
16591 visitNode(cbNode, node.name) ||
16592 visitNode(cbNode, node.questionToken) ||
16593 visitNode(cbNode, node.initializer);
16594 case 237 /* VariableDeclaration */:
16595 return visitNodes(cbNode, cbNodes, node.decorators) ||
16596 visitNodes(cbNode, cbNodes, node.modifiers) ||
16597 visitNode(cbNode, node.name) ||
16598 visitNode(cbNode, node.exclamationToken) ||
16599 visitNode(cbNode, node.type) ||
16600 visitNode(cbNode, node.initializer);
16601 case 186 /* BindingElement */:
16602 return visitNodes(cbNode, cbNodes, node.decorators) ||
16603 visitNodes(cbNode, cbNodes, node.modifiers) ||
16604 visitNode(cbNode, node.dotDotDotToken) ||
16605 visitNode(cbNode, node.propertyName) ||
16606 visitNode(cbNode, node.name) ||
16607 visitNode(cbNode, node.initializer);
16608 case 165 /* FunctionType */:
16609 case 166 /* ConstructorType */:
16610 case 160 /* CallSignature */:
16611 case 161 /* ConstructSignature */:
16612 case 162 /* IndexSignature */:
16613 return visitNodes(cbNode, cbNodes, node.decorators) ||
16614 visitNodes(cbNode, cbNodes, node.modifiers) ||
16615 visitNodes(cbNode, cbNodes, node.typeParameters) ||
16616 visitNodes(cbNode, cbNodes, node.parameters) ||
16617 visitNode(cbNode, node.type);
16618 case 156 /* MethodDeclaration */:
16619 case 155 /* MethodSignature */:
16620 case 157 /* Constructor */:
16621 case 158 /* GetAccessor */:
16622 case 159 /* SetAccessor */:
16623 case 196 /* FunctionExpression */:
16624 case 239 /* FunctionDeclaration */:
16625 case 197 /* ArrowFunction */:
16626 return visitNodes(cbNode, cbNodes, node.decorators) ||
16627 visitNodes(cbNode, cbNodes, node.modifiers) ||
16628 visitNode(cbNode, node.asteriskToken) ||
16629 visitNode(cbNode, node.name) ||
16630 visitNode(cbNode, node.questionToken) ||
16631 visitNode(cbNode, node.exclamationToken) ||
16632 visitNodes(cbNode, cbNodes, node.typeParameters) ||
16633 visitNodes(cbNode, cbNodes, node.parameters) ||
16634 visitNode(cbNode, node.type) ||
16635 visitNode(cbNode, node.equalsGreaterThanToken) ||
16636 visitNode(cbNode, node.body);
16637 case 164 /* TypeReference */:
16638 return visitNode(cbNode, node.typeName) ||
16639 visitNodes(cbNode, cbNodes, node.typeArguments);
16640 case 163 /* TypePredicate */:
16641 return visitNode(cbNode, node.parameterName) ||
16642 visitNode(cbNode, node.type);
16643 case 167 /* TypeQuery */:
16644 return visitNode(cbNode, node.exprName);
16645 case 168 /* TypeLiteral */:
16646 return visitNodes(cbNode, cbNodes, node.members);
16647 case 169 /* ArrayType */:
16648 return visitNode(cbNode, node.elementType);
16649 case 170 /* TupleType */:
16650 return visitNodes(cbNode, cbNodes, node.elementTypes);
16651 case 173 /* UnionType */:
16652 case 174 /* IntersectionType */:
16653 return visitNodes(cbNode, cbNodes, node.types);
16654 case 175 /* ConditionalType */:
16655 return visitNode(cbNode, node.checkType) ||
16656 visitNode(cbNode, node.extendsType) ||
16657 visitNode(cbNode, node.trueType) ||
16658 visitNode(cbNode, node.falseType);
16659 case 176 /* InferType */:
16660 return visitNode(cbNode, node.typeParameter);
16661 case 183 /* ImportType */:
16662 return visitNode(cbNode, node.argument) ||
16663 visitNode(cbNode, node.qualifier) ||
16664 visitNodes(cbNode, cbNodes, node.typeArguments);
16665 case 177 /* ParenthesizedType */:
16666 case 179 /* TypeOperator */:
16667 return visitNode(cbNode, node.type);
16668 case 180 /* IndexedAccessType */:
16669 return visitNode(cbNode, node.objectType) ||
16670 visitNode(cbNode, node.indexType);
16671 case 181 /* MappedType */:
16672 return visitNode(cbNode, node.readonlyToken) ||
16673 visitNode(cbNode, node.typeParameter) ||
16674 visitNode(cbNode, node.questionToken) ||
16675 visitNode(cbNode, node.type);
16676 case 182 /* LiteralType */:
16677 return visitNode(cbNode, node.literal);
16678 case 184 /* ObjectBindingPattern */:
16679 case 185 /* ArrayBindingPattern */:
16680 return visitNodes(cbNode, cbNodes, node.elements);
16681 case 187 /* ArrayLiteralExpression */:
16682 return visitNodes(cbNode, cbNodes, node.elements);
16683 case 188 /* ObjectLiteralExpression */:
16684 return visitNodes(cbNode, cbNodes, node.properties);
16685 case 189 /* PropertyAccessExpression */:
16686 return visitNode(cbNode, node.expression) ||
16687 visitNode(cbNode, node.name);
16688 case 190 /* ElementAccessExpression */:
16689 return visitNode(cbNode, node.expression) ||
16690 visitNode(cbNode, node.argumentExpression);
16691 case 191 /* CallExpression */:
16692 case 192 /* NewExpression */:
16693 return visitNode(cbNode, node.expression) ||
16694 visitNodes(cbNode, cbNodes, node.typeArguments) ||
16695 visitNodes(cbNode, cbNodes, node.arguments);
16696 case 193 /* TaggedTemplateExpression */:
16697 return visitNode(cbNode, node.tag) ||
16698 visitNodes(cbNode, cbNodes, node.typeArguments) ||
16699 visitNode(cbNode, node.template);
16700 case 194 /* TypeAssertionExpression */:
16701 return visitNode(cbNode, node.type) ||
16702 visitNode(cbNode, node.expression);
16703 case 195 /* ParenthesizedExpression */:
16704 return visitNode(cbNode, node.expression);
16705 case 198 /* DeleteExpression */:
16706 return visitNode(cbNode, node.expression);
16707 case 199 /* TypeOfExpression */:
16708 return visitNode(cbNode, node.expression);
16709 case 200 /* VoidExpression */:
16710 return visitNode(cbNode, node.expression);
16711 case 202 /* PrefixUnaryExpression */:
16712 return visitNode(cbNode, node.operand);
16713 case 207 /* YieldExpression */:
16714 return visitNode(cbNode, node.asteriskToken) ||
16715 visitNode(cbNode, node.expression);
16716 case 201 /* AwaitExpression */:
16717 return visitNode(cbNode, node.expression);
16718 case 203 /* PostfixUnaryExpression */:
16719 return visitNode(cbNode, node.operand);
16720 case 204 /* BinaryExpression */:
16721 return visitNode(cbNode, node.left) ||
16722 visitNode(cbNode, node.operatorToken) ||
16723 visitNode(cbNode, node.right);
16724 case 212 /* AsExpression */:
16725 return visitNode(cbNode, node.expression) ||
16726 visitNode(cbNode, node.type);
16727 case 213 /* NonNullExpression */:
16728 return visitNode(cbNode, node.expression);
16729 case 214 /* MetaProperty */:
16730 return visitNode(cbNode, node.name);
16731 case 205 /* ConditionalExpression */:
16732 return visitNode(cbNode, node.condition) ||
16733 visitNode(cbNode, node.questionToken) ||
16734 visitNode(cbNode, node.whenTrue) ||
16735 visitNode(cbNode, node.colonToken) ||
16736 visitNode(cbNode, node.whenFalse);
16737 case 208 /* SpreadElement */:
16738 return visitNode(cbNode, node.expression);
16739 case 218 /* Block */:
16740 case 245 /* ModuleBlock */:
16741 return visitNodes(cbNode, cbNodes, node.statements);
16742 case 284 /* SourceFile */:
16743 return visitNodes(cbNode, cbNodes, node.statements) ||
16744 visitNode(cbNode, node.endOfFileToken);
16745 case 219 /* VariableStatement */:
16746 return visitNodes(cbNode, cbNodes, node.decorators) ||
16747 visitNodes(cbNode, cbNodes, node.modifiers) ||
16748 visitNode(cbNode, node.declarationList);
16749 case 238 /* VariableDeclarationList */:
16750 return visitNodes(cbNode, cbNodes, node.declarations);
16751 case 221 /* ExpressionStatement */:
16752 return visitNode(cbNode, node.expression);
16753 case 222 /* IfStatement */:
16754 return visitNode(cbNode, node.expression) ||
16755 visitNode(cbNode, node.thenStatement) ||
16756 visitNode(cbNode, node.elseStatement);
16757 case 223 /* DoStatement */:
16758 return visitNode(cbNode, node.statement) ||
16759 visitNode(cbNode, node.expression);
16760 case 224 /* WhileStatement */:
16761 return visitNode(cbNode, node.expression) ||
16762 visitNode(cbNode, node.statement);
16763 case 225 /* ForStatement */:
16764 return visitNode(cbNode, node.initializer) ||
16765 visitNode(cbNode, node.condition) ||
16766 visitNode(cbNode, node.incrementor) ||
16767 visitNode(cbNode, node.statement);
16768 case 226 /* ForInStatement */:
16769 return visitNode(cbNode, node.initializer) ||
16770 visitNode(cbNode, node.expression) ||
16771 visitNode(cbNode, node.statement);
16772 case 227 /* ForOfStatement */:
16773 return visitNode(cbNode, node.awaitModifier) ||
16774 visitNode(cbNode, node.initializer) ||
16775 visitNode(cbNode, node.expression) ||
16776 visitNode(cbNode, node.statement);
16777 case 228 /* ContinueStatement */:
16778 case 229 /* BreakStatement */:
16779 return visitNode(cbNode, node.label);
16780 case 230 /* ReturnStatement */:
16781 return visitNode(cbNode, node.expression);
16782 case 231 /* WithStatement */:
16783 return visitNode(cbNode, node.expression) ||
16784 visitNode(cbNode, node.statement);
16785 case 232 /* SwitchStatement */:
16786 return visitNode(cbNode, node.expression) ||
16787 visitNode(cbNode, node.caseBlock);
16788 case 246 /* CaseBlock */:
16789 return visitNodes(cbNode, cbNodes, node.clauses);
16790 case 271 /* CaseClause */:
16791 return visitNode(cbNode, node.expression) ||
16792 visitNodes(cbNode, cbNodes, node.statements);
16793 case 272 /* DefaultClause */:
16794 return visitNodes(cbNode, cbNodes, node.statements);
16795 case 233 /* LabeledStatement */:
16796 return visitNode(cbNode, node.label) ||
16797 visitNode(cbNode, node.statement);
16798 case 234 /* ThrowStatement */:
16799 return visitNode(cbNode, node.expression);
16800 case 235 /* TryStatement */:
16801 return visitNode(cbNode, node.tryBlock) ||
16802 visitNode(cbNode, node.catchClause) ||
16803 visitNode(cbNode, node.finallyBlock);
16804 case 274 /* CatchClause */:
16805 return visitNode(cbNode, node.variableDeclaration) ||
16806 visitNode(cbNode, node.block);
16807 case 152 /* Decorator */:
16808 return visitNode(cbNode, node.expression);
16809 case 240 /* ClassDeclaration */:
16810 case 209 /* ClassExpression */:
16811 return visitNodes(cbNode, cbNodes, node.decorators) ||
16812 visitNodes(cbNode, cbNodes, node.modifiers) ||
16813 visitNode(cbNode, node.name) ||
16814 visitNodes(cbNode, cbNodes, node.typeParameters) ||
16815 visitNodes(cbNode, cbNodes, node.heritageClauses) ||
16816 visitNodes(cbNode, cbNodes, node.members);
16817 case 241 /* InterfaceDeclaration */:
16818 return visitNodes(cbNode, cbNodes, node.decorators) ||
16819 visitNodes(cbNode, cbNodes, node.modifiers) ||
16820 visitNode(cbNode, node.name) ||
16821 visitNodes(cbNode, cbNodes, node.typeParameters) ||
16822 visitNodes(cbNode, cbNodes, node.heritageClauses) ||
16823 visitNodes(cbNode, cbNodes, node.members);
16824 case 242 /* TypeAliasDeclaration */:
16825 return visitNodes(cbNode, cbNodes, node.decorators) ||
16826 visitNodes(cbNode, cbNodes, node.modifiers) ||
16827 visitNode(cbNode, node.name) ||
16828 visitNodes(cbNode, cbNodes, node.typeParameters) ||
16829 visitNode(cbNode, node.type);
16830 case 243 /* EnumDeclaration */:
16831 return visitNodes(cbNode, cbNodes, node.decorators) ||
16832 visitNodes(cbNode, cbNodes, node.modifiers) ||
16833 visitNode(cbNode, node.name) ||
16834 visitNodes(cbNode, cbNodes, node.members);
16835 case 278 /* EnumMember */:
16836 return visitNode(cbNode, node.name) ||
16837 visitNode(cbNode, node.initializer);
16838 case 244 /* ModuleDeclaration */:
16839 return visitNodes(cbNode, cbNodes, node.decorators) ||
16840 visitNodes(cbNode, cbNodes, node.modifiers) ||
16841 visitNode(cbNode, node.name) ||
16842 visitNode(cbNode, node.body);
16843 case 248 /* ImportEqualsDeclaration */:
16844 return visitNodes(cbNode, cbNodes, node.decorators) ||
16845 visitNodes(cbNode, cbNodes, node.modifiers) ||
16846 visitNode(cbNode, node.name) ||
16847 visitNode(cbNode, node.moduleReference);
16848 case 249 /* ImportDeclaration */:
16849 return visitNodes(cbNode, cbNodes, node.decorators) ||
16850 visitNodes(cbNode, cbNodes, node.modifiers) ||
16851 visitNode(cbNode, node.importClause) ||
16852 visitNode(cbNode, node.moduleSpecifier);
16853 case 250 /* ImportClause */:
16854 return visitNode(cbNode, node.name) ||
16855 visitNode(cbNode, node.namedBindings);
16856 case 247 /* NamespaceExportDeclaration */:
16857 return visitNode(cbNode, node.name);
16858 case 251 /* NamespaceImport */:
16859 return visitNode(cbNode, node.name);
16860 case 252 /* NamedImports */:
16861 case 256 /* NamedExports */:
16862 return visitNodes(cbNode, cbNodes, node.elements);
16863 case 255 /* ExportDeclaration */:
16864 return visitNodes(cbNode, cbNodes, node.decorators) ||
16865 visitNodes(cbNode, cbNodes, node.modifiers) ||
16866 visitNode(cbNode, node.exportClause) ||
16867 visitNode(cbNode, node.moduleSpecifier);
16868 case 253 /* ImportSpecifier */:
16869 case 257 /* ExportSpecifier */:
16870 return visitNode(cbNode, node.propertyName) ||
16871 visitNode(cbNode, node.name);
16872 case 254 /* ExportAssignment */:
16873 return visitNodes(cbNode, cbNodes, node.decorators) ||
16874 visitNodes(cbNode, cbNodes, node.modifiers) ||
16875 visitNode(cbNode, node.expression);
16876 case 206 /* TemplateExpression */:
16877 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
16878 case 216 /* TemplateSpan */:
16879 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
16880 case 149 /* ComputedPropertyName */:
16881 return visitNode(cbNode, node.expression);
16882 case 273 /* HeritageClause */:
16883 return visitNodes(cbNode, cbNodes, node.types);
16884 case 211 /* ExpressionWithTypeArguments */:
16885 return visitNode(cbNode, node.expression) ||
16886 visitNodes(cbNode, cbNodes, node.typeArguments);
16887 case 259 /* ExternalModuleReference */:
16888 return visitNode(cbNode, node.expression);
16889 case 258 /* MissingDeclaration */:
16890 return visitNodes(cbNode, cbNodes, node.decorators);
16891 case 314 /* CommaListExpression */:
16892 return visitNodes(cbNode, cbNodes, node.elements);
16893 case 260 /* JsxElement */:
16894 return visitNode(cbNode, node.openingElement) ||
16895 visitNodes(cbNode, cbNodes, node.children) ||
16896 visitNode(cbNode, node.closingElement);
16897 case 264 /* JsxFragment */:
16898 return visitNode(cbNode, node.openingFragment) ||
16899 visitNodes(cbNode, cbNodes, node.children) ||
16900 visitNode(cbNode, node.closingFragment);
16901 case 261 /* JsxSelfClosingElement */:
16902 case 262 /* JsxOpeningElement */:
16903 return visitNode(cbNode, node.tagName) ||
16904 visitNodes(cbNode, cbNodes, node.typeArguments) ||
16905 visitNode(cbNode, node.attributes);
16906 case 268 /* JsxAttributes */:
16907 return visitNodes(cbNode, cbNodes, node.properties);
16908 case 267 /* JsxAttribute */:
16909 return visitNode(cbNode, node.name) ||
16910 visitNode(cbNode, node.initializer);
16911 case 269 /* JsxSpreadAttribute */:
16912 return visitNode(cbNode, node.expression);
16913 case 270 /* JsxExpression */:
16914 return visitNode(cbNode, node.dotDotDotToken) ||
16915 visitNode(cbNode, node.expression);
16916 case 263 /* JsxClosingElement */:
16917 return visitNode(cbNode, node.tagName);
16918 case 171 /* OptionalType */:
16919 case 172 /* RestType */:
16920 case 288 /* JSDocTypeExpression */:
16921 case 292 /* JSDocNonNullableType */:
16922 case 291 /* JSDocNullableType */:
16923 case 293 /* JSDocOptionalType */:
16924 case 295 /* JSDocVariadicType */:
16925 return visitNode(cbNode, node.type);
16926 case 294 /* JSDocFunctionType */:
16927 return visitNodes(cbNode, cbNodes, node.parameters) ||
16928 visitNode(cbNode, node.type);
16929 case 296 /* JSDocComment */:
16930 return visitNodes(cbNode, cbNodes, node.tags);
16931 case 304 /* JSDocParameterTag */:
16932 case 310 /* JSDocPropertyTag */:
16933 return visitNode(cbNode, node.tagName) ||
16934 (node.isNameFirst
16935 ? visitNode(cbNode, node.name) ||
16936 visitNode(cbNode, node.typeExpression)
16937 : visitNode(cbNode, node.typeExpression) ||
16938 visitNode(cbNode, node.name));
16939 case 300 /* JSDocAugmentsTag */:
16940 return visitNode(cbNode, node.tagName) ||
16941 visitNode(cbNode, node.class);
16942 case 308 /* JSDocTemplateTag */:
16943 return visitNode(cbNode, node.tagName) ||
16944 visitNode(cbNode, node.constraint) ||
16945 visitNodes(cbNode, cbNodes, node.typeParameters);
16946 case 309 /* JSDocTypedefTag */:
16947 return visitNode(cbNode, node.tagName) ||
16948 (node.typeExpression &&
16949 node.typeExpression.kind === 288 /* JSDocTypeExpression */
16950 ? visitNode(cbNode, node.typeExpression) ||
16951 visitNode(cbNode, node.fullName)
16952 : visitNode(cbNode, node.fullName) ||
16953 visitNode(cbNode, node.typeExpression));
16954 case 302 /* JSDocCallbackTag */:
16955 return visitNode(cbNode, node.tagName) ||
16956 visitNode(cbNode, node.fullName) ||
16957 visitNode(cbNode, node.typeExpression);
16958 case 305 /* JSDocReturnTag */:
16959 case 307 /* JSDocTypeTag */:
16960 case 306 /* JSDocThisTag */:
16961 case 303 /* JSDocEnumTag */:
16962 return visitNode(cbNode, node.tagName) ||
16963 visitNode(cbNode, node.typeExpression);
16964 case 298 /* JSDocSignature */:
16965 return ts.forEach(node.typeParameters, cbNode) ||
16966 ts.forEach(node.parameters, cbNode) ||
16967 visitNode(cbNode, node.type);
16968 case 297 /* JSDocTypeLiteral */:
16969 return ts.forEach(node.jsDocPropertyTags, cbNode);
16970 case 299 /* JSDocTag */:
16971 case 301 /* JSDocClassTag */:
16972 return visitNode(cbNode, node.tagName);
16973 case 313 /* PartiallyEmittedExpression */:
16974 return visitNode(cbNode, node.expression);
16975 }
16976 }
16977 ts.forEachChild = forEachChild;
16978 function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
16979 if (setParentNodes === void 0) { setParentNodes = false; }
16980 ts.performance.mark("beforeParse");
16981 var result;
16982 if (languageVersion === 100 /* JSON */) {
16983 result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
16984 }
16985 else {
16986 result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
16987 }
16988 ts.performance.mark("afterParse");
16989 ts.performance.measure("Parse", "beforeParse", "afterParse");
16990 return result;
16991 }
16992 ts.createSourceFile = createSourceFile;
16993 function parseIsolatedEntityName(text, languageVersion) {
16994 return Parser.parseIsolatedEntityName(text, languageVersion);
16995 }
16996 ts.parseIsolatedEntityName = parseIsolatedEntityName;
16997 /**
16998 * Parse json text into SyntaxTree and return node and parse errors if any
16999 * @param fileName
17000 * @param sourceText
17001 */
17002 function parseJsonText(fileName, sourceText) {
17003 return Parser.parseJsonText(fileName, sourceText);
17004 }
17005 ts.parseJsonText = parseJsonText;
17006 // See also `isExternalOrCommonJsModule` in utilities.ts
17007 function isExternalModule(file) {
17008 return file.externalModuleIndicator !== undefined;
17009 }
17010 ts.isExternalModule = isExternalModule;
17011 // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
17012 // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
17013 // The SourceFile will be created with the compiler attempting to reuse as many nodes from
17014 // this file as possible.
17015 //
17016 // Note: this function mutates nodes from this SourceFile. That means any existing nodes
17017 // from this SourceFile that are being held onto may change as a result (including
17018 // becoming detached from any SourceFile). It is recommended that this SourceFile not
17019 // be used once 'update' is called on it.
17020 function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
17021 if (aggressiveChecks === void 0) { aggressiveChecks = false; }
17022 var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
17023 // 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.
17024 // We will manually port the flag to the new source file.
17025 newSourceFile.flags |= (sourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */);
17026 return newSourceFile;
17027 }
17028 ts.updateSourceFile = updateSourceFile;
17029 /* @internal */
17030 function parseIsolatedJSDocComment(content, start, length) {
17031 var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
17032 if (result && result.jsDoc) {
17033 // because the jsDocComment was parsed out of the source file, it might
17034 // not be covered by the fixupParentReferences.
17035 Parser.fixupParentReferences(result.jsDoc);
17036 }
17037 return result;
17038 }
17039 ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
17040 /* @internal */
17041 // Exposed only for testing.
17042 function parseJSDocTypeExpressionForTests(content, start, length) {
17043 return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
17044 }
17045 ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
17046 // Implement the parser as a singleton module. We do this for perf reasons because creating
17047 // parser instances can actually be expensive enough to impact us on projects with many source
17048 // files.
17049 var Parser;
17050 (function (Parser) {
17051 // Share a single scanner across all calls to parse a source file. This helps speed things
17052 // up by avoiding the cost of creating/compiling scanners over and over again.
17053 var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
17054 var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */;
17055 // capture constructors in 'initializeState' to avoid null checks
17056 // tslint:disable variable-name
17057 var NodeConstructor;
17058 var TokenConstructor;
17059 var IdentifierConstructor;
17060 var SourceFileConstructor;
17061 // tslint:enable variable-name
17062 var sourceFile;
17063 var parseDiagnostics;
17064 var syntaxCursor;
17065 var currentToken;
17066 var sourceText;
17067 var nodeCount;
17068 var identifiers;
17069 var identifierCount;
17070 var parsingContext;
17071 // Flags that dictate what parsing context we're in. For example:
17072 // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is
17073 // that some tokens that would be considered identifiers may be considered keywords.
17074 //
17075 // When adding more parser context flags, consider which is the more common case that the
17076 // flag will be in. This should be the 'false' state for that flag. The reason for this is
17077 // that we don't store data in our nodes unless the value is in the *non-default* state. So,
17078 // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for
17079 // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost
17080 // all nodes would need extra state on them to store this info.
17081 //
17082 // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
17083 // grammar specification.
17084 //
17085 // An important thing about these context concepts. By default they are effectively inherited
17086 // while parsing through every grammar production. i.e. if you don't change them, then when
17087 // you parse a sub-production, it will have the same context values as the parent production.
17088 // This is great most of the time. After all, consider all the 'expression' grammar productions
17089 // and how nearly all of them pass along the 'in' and 'yield' context values:
17090 //
17091 // EqualityExpression[In, Yield] :
17092 // RelationalExpression[?In, ?Yield]
17093 // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
17094 // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
17095 // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
17096 // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
17097 //
17098 // Where you have to be careful is then understanding what the points are in the grammar
17099 // where the values are *not* passed along. For example:
17100 //
17101 // SingleNameBinding[Yield,GeneratorParameter]
17102 // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
17103 // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
17104 //
17105 // Here this is saying that if the GeneratorParameter context flag is set, that we should
17106 // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
17107 // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
17108 // production. Conversely, if the GeneratorParameter context flag is not set, then we
17109 // should leave the 'yield' context flag alone.
17110 //
17111 // Getting this all correct is tricky and requires careful reading of the grammar to
17112 // understand when these values should be changed versus when they should be inherited.
17113 //
17114 // Note: it should not be necessary to save/restore these flags during speculative/lookahead
17115 // parsing. These context flags are naturally stored and restored through normal recursive
17116 // descent parsing and unwinding.
17117 var contextFlags;
17118 // Whether or not we've had a parse error since creating the last AST node. If we have
17119 // encountered an error, it will be stored on the next AST node we create. Parse errors
17120 // can be broken down into three categories:
17121 //
17122 // 1) An error that occurred during scanning. For example, an unterminated literal, or a
17123 // character that was completely not understood.
17124 //
17125 // 2) A token was expected, but was not present. This type of error is commonly produced
17126 // by the 'parseExpected' function.
17127 //
17128 // 3) A token was present that no parsing function was able to consume. This type of error
17129 // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
17130 // decides to skip the token.
17131 //
17132 // In all of these cases, we want to mark the next node as having had an error before it.
17133 // With this mark, we can know in incremental settings if this node can be reused, or if
17134 // we have to reparse it. If we don't keep this information around, we may just reuse the
17135 // node. in that event we would then not produce the same errors as we did before, causing
17136 // significant confusion problems.
17137 //
17138 // Note: it is necessary that this value be saved/restored during speculative/lookahead
17139 // parsing. During lookahead parsing, we will often create a node. That node will have
17140 // this value attached, and then this value will be set back to 'false'. If we decide to
17141 // rewind, we must get back to the same value we had prior to the lookahead.
17142 //
17143 // Note: any errors at the end of the file that do not precede a regular node, should get
17144 // attached to the EOF token.
17145 var parseErrorBeforeNextFinishedNode = false;
17146 function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
17147 if (setParentNodes === void 0) { setParentNodes = false; }
17148 scriptKind = ts.ensureScriptKind(fileName, scriptKind);
17149 if (scriptKind === 6 /* JSON */) {
17150 var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
17151 ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
17152 result_2.referencedFiles = ts.emptyArray;
17153 result_2.typeReferenceDirectives = ts.emptyArray;
17154 result_2.libReferenceDirectives = ts.emptyArray;
17155 result_2.amdDependencies = ts.emptyArray;
17156 result_2.hasNoDefaultLib = false;
17157 result_2.pragmas = ts.emptyMap;
17158 return result_2;
17159 }
17160 initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
17161 var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
17162 clearState();
17163 return result;
17164 }
17165 Parser.parseSourceFile = parseSourceFile;
17166 function parseIsolatedEntityName(content, languageVersion) {
17167 // Choice of `isDeclarationFile` should be arbitrary
17168 initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
17169 // Prime the scanner.
17170 nextToken();
17171 var entityName = parseEntityName(/*allowReservedWords*/ true);
17172 var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
17173 clearState();
17174 return isInvalid ? entityName : undefined;
17175 }
17176 Parser.parseIsolatedEntityName = parseIsolatedEntityName;
17177 function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
17178 if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
17179 initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
17180 // Set source file so that errors will be reported with this file name
17181 sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
17182 sourceFile.flags = contextFlags;
17183 // Prime the scanner.
17184 nextToken();
17185 var pos = getNodePos();
17186 if (token() === 1 /* EndOfFileToken */) {
17187 sourceFile.statements = createNodeArray([], pos, pos);
17188 sourceFile.endOfFileToken = parseTokenNode();
17189 }
17190 else {
17191 var statement = createNode(221 /* ExpressionStatement */);
17192 switch (token()) {
17193 case 22 /* OpenBracketToken */:
17194 statement.expression = parseArrayLiteralExpression();
17195 break;
17196 case 102 /* TrueKeyword */:
17197 case 87 /* FalseKeyword */:
17198 case 96 /* NullKeyword */:
17199 statement.expression = parseTokenNode();
17200 break;
17201 case 39 /* MinusToken */:
17202 if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 57 /* ColonToken */; })) {
17203 statement.expression = parsePrefixUnaryExpression();
17204 }
17205 else {
17206 statement.expression = parseObjectLiteralExpression();
17207 }
17208 break;
17209 case 8 /* NumericLiteral */:
17210 case 10 /* StringLiteral */:
17211 if (lookAhead(function () { return nextToken() !== 57 /* ColonToken */; })) {
17212 statement.expression = parseLiteralNode();
17213 break;
17214 }
17215 // falls through
17216 default:
17217 statement.expression = parseObjectLiteralExpression();
17218 break;
17219 }
17220 finishNode(statement);
17221 sourceFile.statements = createNodeArray([statement], pos);
17222 sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
17223 }
17224 if (setParentNodes) {
17225 fixupParentReferences(sourceFile);
17226 }
17227 sourceFile.parseDiagnostics = parseDiagnostics;
17228 var result = sourceFile;
17229 clearState();
17230 return result;
17231 }
17232 Parser.parseJsonText = parseJsonText;
17233 function getLanguageVariant(scriptKind) {
17234 // .tsx and .jsx files are treated as jsx language variant.
17235 return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
17236 }
17237 function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) {
17238 NodeConstructor = ts.objectAllocator.getNodeConstructor();
17239 TokenConstructor = ts.objectAllocator.getTokenConstructor();
17240 IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
17241 SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
17242 sourceText = _sourceText;
17243 syntaxCursor = _syntaxCursor;
17244 parseDiagnostics = [];
17245 parsingContext = 0;
17246 identifiers = ts.createMap();
17247 identifierCount = 0;
17248 nodeCount = 0;
17249 switch (scriptKind) {
17250 case 1 /* JS */:
17251 case 2 /* JSX */:
17252 contextFlags = 65536 /* JavaScriptFile */;
17253 break;
17254 case 6 /* JSON */:
17255 contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */;
17256 break;
17257 default:
17258 contextFlags = 0 /* None */;
17259 break;
17260 }
17261 parseErrorBeforeNextFinishedNode = false;
17262 // Initialize and prime the scanner before parsing the source elements.
17263 scanner.setText(sourceText);
17264 scanner.setOnError(scanError);
17265 scanner.setScriptTarget(languageVersion);
17266 scanner.setLanguageVariant(getLanguageVariant(scriptKind));
17267 }
17268 function clearState() {
17269 // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
17270 scanner.setText("");
17271 scanner.setOnError(undefined);
17272 // Clear any data. We don't want to accidentally hold onto it for too long.
17273 parseDiagnostics = undefined;
17274 sourceFile = undefined;
17275 identifiers = undefined;
17276 syntaxCursor = undefined;
17277 sourceText = undefined;
17278 }
17279 function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
17280 var isDeclarationFile = isDeclarationFileName(fileName);
17281 if (isDeclarationFile) {
17282 contextFlags |= 4194304 /* Ambient */;
17283 }
17284 sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
17285 sourceFile.flags = contextFlags;
17286 // Prime the scanner.
17287 nextToken();
17288 // A member of ReadonlyArray<T> 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
17289 processCommentPragmas(sourceFile, sourceText);
17290 processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
17291 sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
17292 ts.Debug.assert(token() === 1 /* EndOfFileToken */);
17293 sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
17294 setExternalModuleIndicator(sourceFile);
17295 sourceFile.nodeCount = nodeCount;
17296 sourceFile.identifierCount = identifierCount;
17297 sourceFile.identifiers = identifiers;
17298 sourceFile.parseDiagnostics = parseDiagnostics;
17299 if (setParentNodes) {
17300 fixupParentReferences(sourceFile);
17301 }
17302 return sourceFile;
17303 function reportPragmaDiagnostic(pos, end, diagnostic) {
17304 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
17305 }
17306 }
17307 function addJSDocComment(node) {
17308 ts.Debug.assert(!node.jsDoc); // Should only be called once per node
17309 var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
17310 if (jsDoc.length)
17311 node.jsDoc = jsDoc;
17312 return node;
17313 }
17314 function fixupParentReferences(rootNode) {
17315 // normally parent references are set during binding. However, for clients that only need
17316 // a syntax tree, and no semantic features, then the binding process is an unnecessary
17317 // overhead. This functions allows us to set all the parents, without all the expense of
17318 // binding.
17319 var parent = rootNode;
17320 forEachChild(rootNode, visitNode);
17321 return;
17322 function visitNode(n) {
17323 // walk down setting parents that differ from the parent we think it should be. This
17324 // allows us to quickly bail out of setting parents for subtrees during incremental
17325 // parsing
17326 if (n.parent !== parent) {
17327 n.parent = parent;
17328 var saveParent = parent;
17329 parent = n;
17330 forEachChild(n, visitNode);
17331 if (ts.hasJSDocNodes(n)) {
17332 for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) {
17333 var jsDoc = _a[_i];
17334 jsDoc.parent = n;
17335 parent = jsDoc;
17336 forEachChild(jsDoc, visitNode);
17337 }
17338 }
17339 parent = saveParent;
17340 }
17341 }
17342 }
17343 Parser.fixupParentReferences = fixupParentReferences;
17344 function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
17345 // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
17346 // this is quite rare comparing to other nodes and createNode should be as fast as possible
17347 var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
17348 nodeCount++;
17349 sourceFile.text = sourceText;
17350 sourceFile.bindDiagnostics = [];
17351 sourceFile.bindSuggestionDiagnostics = undefined;
17352 sourceFile.languageVersion = languageVersion;
17353 sourceFile.fileName = ts.normalizePath(fileName);
17354 sourceFile.languageVariant = getLanguageVariant(scriptKind);
17355 sourceFile.isDeclarationFile = isDeclarationFile;
17356 sourceFile.scriptKind = scriptKind;
17357 return sourceFile;
17358 }
17359 function setContextFlag(val, flag) {
17360 if (val) {
17361 contextFlags |= flag;
17362 }
17363 else {
17364 contextFlags &= ~flag;
17365 }
17366 }
17367 function setDisallowInContext(val) {
17368 setContextFlag(val, 2048 /* DisallowInContext */);
17369 }
17370 function setYieldContext(val) {
17371 setContextFlag(val, 4096 /* YieldContext */);
17372 }
17373 function setDecoratorContext(val) {
17374 setContextFlag(val, 8192 /* DecoratorContext */);
17375 }
17376 function setAwaitContext(val) {
17377 setContextFlag(val, 16384 /* AwaitContext */);
17378 }
17379 function doOutsideOfContext(context, func) {
17380 // contextFlagsToClear will contain only the context flags that are
17381 // currently set that we need to temporarily clear
17382 // We don't just blindly reset to the previous flags to ensure
17383 // that we do not mutate cached flags for the incremental
17384 // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
17385 // HasAggregatedChildData).
17386 var contextFlagsToClear = context & contextFlags;
17387 if (contextFlagsToClear) {
17388 // clear the requested context flags
17389 setContextFlag(/*val*/ false, contextFlagsToClear);
17390 var result = func();
17391 // restore the context flags we just cleared
17392 setContextFlag(/*val*/ true, contextFlagsToClear);
17393 return result;
17394 }
17395 // no need to do anything special as we are not in any of the requested contexts
17396 return func();
17397 }
17398 function doInsideOfContext(context, func) {
17399 // contextFlagsToSet will contain only the context flags that
17400 // are not currently set that we need to temporarily enable.
17401 // We don't just blindly reset to the previous flags to ensure
17402 // that we do not mutate cached flags for the incremental
17403 // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
17404 // HasAggregatedChildData).
17405 var contextFlagsToSet = context & ~contextFlags;
17406 if (contextFlagsToSet) {
17407 // set the requested context flags
17408 setContextFlag(/*val*/ true, contextFlagsToSet);
17409 var result = func();
17410 // reset the context flags we just set
17411 setContextFlag(/*val*/ false, contextFlagsToSet);
17412 return result;
17413 }
17414 // no need to do anything special as we are already in all of the requested contexts
17415 return func();
17416 }
17417 function allowInAnd(func) {
17418 return doOutsideOfContext(2048 /* DisallowInContext */, func);
17419 }
17420 function disallowInAnd(func) {
17421 return doInsideOfContext(2048 /* DisallowInContext */, func);
17422 }
17423 function doInYieldContext(func) {
17424 return doInsideOfContext(4096 /* YieldContext */, func);
17425 }
17426 function doInDecoratorContext(func) {
17427 return doInsideOfContext(8192 /* DecoratorContext */, func);
17428 }
17429 function doInAwaitContext(func) {
17430 return doInsideOfContext(16384 /* AwaitContext */, func);
17431 }
17432 function doOutsideOfAwaitContext(func) {
17433 return doOutsideOfContext(16384 /* AwaitContext */, func);
17434 }
17435 function doInYieldAndAwaitContext(func) {
17436 return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func);
17437 }
17438 function inContext(flags) {
17439 return (contextFlags & flags) !== 0;
17440 }
17441 function inYieldContext() {
17442 return inContext(4096 /* YieldContext */);
17443 }
17444 function inDisallowInContext() {
17445 return inContext(2048 /* DisallowInContext */);
17446 }
17447 function inDecoratorContext() {
17448 return inContext(8192 /* DecoratorContext */);
17449 }
17450 function inAwaitContext() {
17451 return inContext(16384 /* AwaitContext */);
17452 }
17453 function parseErrorAtCurrentToken(message, arg0) {
17454 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
17455 }
17456 function parseErrorAtPosition(start, length, message, arg0) {
17457 // Don't report another error if it would just be at the same position as the last error.
17458 var lastError = ts.lastOrUndefined(parseDiagnostics);
17459 if (!lastError || start !== lastError.start) {
17460 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0));
17461 }
17462 // Mark that we've encountered an error. We'll set an appropriate bit on the next
17463 // node we finish so that it can't be reused incrementally.
17464 parseErrorBeforeNextFinishedNode = true;
17465 }
17466 function parseErrorAt(start, end, message, arg0) {
17467 parseErrorAtPosition(start, end - start, message, arg0);
17468 }
17469 function parseErrorAtRange(range, message, arg0) {
17470 parseErrorAt(range.pos, range.end, message, arg0);
17471 }
17472 function scanError(message, length) {
17473 parseErrorAtPosition(scanner.getTextPos(), length, message);
17474 }
17475 function getNodePos() {
17476 return scanner.getStartPos();
17477 }
17478 // Use this function to access the current token instead of reading the currentToken
17479 // variable. Since function results aren't narrowed in control flow analysis, this ensures
17480 // that the type checker doesn't make wrong assumptions about the type of the current
17481 // token (e.g. a call to nextToken() changes the current token but the checker doesn't
17482 // reason about this side effect). Mainstream VMs inline simple functions like this, so
17483 // there is no performance penalty.
17484 function token() {
17485 return currentToken;
17486 }
17487 function nextToken() {
17488 return currentToken = scanner.scan();
17489 }
17490 function reScanGreaterToken() {
17491 return currentToken = scanner.reScanGreaterToken();
17492 }
17493 function reScanSlashToken() {
17494 return currentToken = scanner.reScanSlashToken();
17495 }
17496 function reScanTemplateToken() {
17497 return currentToken = scanner.reScanTemplateToken();
17498 }
17499 function reScanLessThanToken() {
17500 return currentToken = scanner.reScanLessThanToken();
17501 }
17502 function scanJsxIdentifier() {
17503 return currentToken = scanner.scanJsxIdentifier();
17504 }
17505 function scanJsxText() {
17506 return currentToken = scanner.scanJsxToken();
17507 }
17508 function scanJsxAttributeValue() {
17509 return currentToken = scanner.scanJsxAttributeValue();
17510 }
17511 function speculationHelper(callback, isLookAhead) {
17512 // Keep track of the state we'll need to rollback to if lookahead fails (or if the
17513 // caller asked us to always reset our state).
17514 var saveToken = currentToken;
17515 var saveParseDiagnosticsLength = parseDiagnostics.length;
17516 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
17517 // Note: it is not actually necessary to save/restore the context flags here. That's
17518 // because the saving/restoring of these flags happens naturally through the recursive
17519 // descent nature of our parser. However, we still store this here just so we can
17520 // assert that invariant holds.
17521 var saveContextFlags = contextFlags;
17522 // If we're only looking ahead, then tell the scanner to only lookahead as well.
17523 // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
17524 // same.
17525 var result = isLookAhead
17526 ? scanner.lookAhead(callback)
17527 : scanner.tryScan(callback);
17528 ts.Debug.assert(saveContextFlags === contextFlags);
17529 // If our callback returned something 'falsy' or we're just looking ahead,
17530 // then unconditionally restore us to where we were.
17531 if (!result || isLookAhead) {
17532 currentToken = saveToken;
17533 parseDiagnostics.length = saveParseDiagnosticsLength;
17534 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
17535 }
17536 return result;
17537 }
17538 /** Invokes the provided callback then unconditionally restores the parser to the state it
17539 * was in immediately prior to invoking the callback. The result of invoking the callback
17540 * is returned from this function.
17541 */
17542 function lookAhead(callback) {
17543 return speculationHelper(callback, /*isLookAhead*/ true);
17544 }
17545 /** Invokes the provided callback. If the callback returns something falsy, then it restores
17546 * the parser to the state it was in immediately prior to invoking the callback. If the
17547 * callback returns something truthy, then the parser state is not rolled back. The result
17548 * of invoking the callback is returned from this function.
17549 */
17550 function tryParse(callback) {
17551 return speculationHelper(callback, /*isLookAhead*/ false);
17552 }
17553 // Ignore strict mode flag because we will report an error in type checker instead.
17554 function isIdentifier() {
17555 if (token() === 72 /* Identifier */) {
17556 return true;
17557 }
17558 // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
17559 // considered a keyword and is not an identifier.
17560 if (token() === 117 /* YieldKeyword */ && inYieldContext()) {
17561 return false;
17562 }
17563 // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
17564 // considered a keyword and is not an identifier.
17565 if (token() === 122 /* AwaitKeyword */ && inAwaitContext()) {
17566 return false;
17567 }
17568 return token() > 108 /* LastReservedWord */;
17569 }
17570 function parseExpected(kind, diagnosticMessage, shouldAdvance) {
17571 if (shouldAdvance === void 0) { shouldAdvance = true; }
17572 if (token() === kind) {
17573 if (shouldAdvance) {
17574 nextToken();
17575 }
17576 return true;
17577 }
17578 // Report specific message if provided with one. Otherwise, report generic fallback message.
17579 if (diagnosticMessage) {
17580 parseErrorAtCurrentToken(diagnosticMessage);
17581 }
17582 else {
17583 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
17584 }
17585 return false;
17586 }
17587 function parseOptional(t) {
17588 if (token() === t) {
17589 nextToken();
17590 return true;
17591 }
17592 return false;
17593 }
17594 function parseOptionalToken(t) {
17595 if (token() === t) {
17596 return parseTokenNode();
17597 }
17598 return undefined;
17599 }
17600 function parseExpectedToken(t, diagnosticMessage, arg0) {
17601 return parseOptionalToken(t) ||
17602 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
17603 }
17604 function parseTokenNode() {
17605 var node = createNode(token());
17606 nextToken();
17607 return finishNode(node);
17608 }
17609 function canParseSemicolon() {
17610 // If there's a real semicolon, then we can always parse it out.
17611 if (token() === 26 /* SemicolonToken */) {
17612 return true;
17613 }
17614 // We can parse out an optional semicolon in ASI cases in the following cases.
17615 return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
17616 }
17617 function parseSemicolon() {
17618 if (canParseSemicolon()) {
17619 if (token() === 26 /* SemicolonToken */) {
17620 // consume the semicolon if it was explicitly provided.
17621 nextToken();
17622 }
17623 return true;
17624 }
17625 else {
17626 return parseExpected(26 /* SemicolonToken */);
17627 }
17628 }
17629 function createNode(kind, pos) {
17630 nodeCount++;
17631 var p = pos >= 0 ? pos : scanner.getStartPos();
17632 return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
17633 kind === 72 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
17634 new TokenConstructor(kind, p, p);
17635 }
17636 function createNodeWithJSDoc(kind, pos) {
17637 var node = createNode(kind, pos);
17638 if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) {
17639 addJSDocComment(node);
17640 }
17641 return node;
17642 }
17643 function createNodeArray(elements, pos, end) {
17644 // Since the element list of a node array is typically created by starting with an empty array and
17645 // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
17646 // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
17647 var length = elements.length;
17648 var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
17649 array.pos = pos;
17650 array.end = end === undefined ? scanner.getStartPos() : end;
17651 return array;
17652 }
17653 function finishNode(node, end) {
17654 node.end = end === undefined ? scanner.getStartPos() : end;
17655 if (contextFlags) {
17656 node.flags |= contextFlags;
17657 }
17658 // Keep track on the node if we encountered an error while parsing it. If we did, then
17659 // we cannot reuse the node incrementally. Once we've marked this node, clear out the
17660 // flag so that we don't mark any subsequent nodes.
17661 if (parseErrorBeforeNextFinishedNode) {
17662 parseErrorBeforeNextFinishedNode = false;
17663 node.flags |= 32768 /* ThisNodeHasError */;
17664 }
17665 return node;
17666 }
17667 function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
17668 if (reportAtCurrentPosition) {
17669 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
17670 }
17671 else if (diagnosticMessage) {
17672 parseErrorAtCurrentToken(diagnosticMessage, arg0);
17673 }
17674 var result = createNode(kind);
17675 if (kind === 72 /* Identifier */) {
17676 result.escapedText = "";
17677 }
17678 else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
17679 result.text = "";
17680 }
17681 return finishNode(result);
17682 }
17683 function internIdentifier(text) {
17684 var identifier = identifiers.get(text);
17685 if (identifier === undefined) {
17686 identifiers.set(text, identifier = text);
17687 }
17688 return identifier;
17689 }
17690 // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
17691 // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
17692 // each identifier in order to reduce memory consumption.
17693 function createIdentifier(isIdentifier, diagnosticMessage) {
17694 identifierCount++;
17695 if (isIdentifier) {
17696 var node = createNode(72 /* Identifier */);
17697 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
17698 if (token() !== 72 /* Identifier */) {
17699 node.originalKeywordKind = token();
17700 }
17701 node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
17702 nextToken();
17703 return finishNode(node);
17704 }
17705 // Only for end of file because the error gets reported incorrectly on embedded script tags.
17706 var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
17707 return createMissingNode(72 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected);
17708 }
17709 function parseIdentifier(diagnosticMessage) {
17710 return createIdentifier(isIdentifier(), diagnosticMessage);
17711 }
17712 function parseIdentifierName(diagnosticMessage) {
17713 return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
17714 }
17715 function isLiteralPropertyName() {
17716 return ts.tokenIsIdentifierOrKeyword(token()) ||
17717 token() === 10 /* StringLiteral */ ||
17718 token() === 8 /* NumericLiteral */;
17719 }
17720 function parsePropertyNameWorker(allowComputedPropertyNames) {
17721 if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
17722 var node = parseLiteralNode();
17723 node.text = internIdentifier(node.text);
17724 return node;
17725 }
17726 if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
17727 return parseComputedPropertyName();
17728 }
17729 return parseIdentifierName();
17730 }
17731 function parsePropertyName() {
17732 return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
17733 }
17734 function parseComputedPropertyName() {
17735 // PropertyName [Yield]:
17736 // LiteralPropertyName
17737 // ComputedPropertyName[?Yield]
17738 var node = createNode(149 /* ComputedPropertyName */);
17739 parseExpected(22 /* OpenBracketToken */);
17740 // We parse any expression (including a comma expression). But the grammar
17741 // says that only an assignment expression is allowed, so the grammar checker
17742 // will error if it sees a comma expression.
17743 node.expression = allowInAnd(parseExpression);
17744 parseExpected(23 /* CloseBracketToken */);
17745 return finishNode(node);
17746 }
17747 function parseContextualModifier(t) {
17748 return token() === t && tryParse(nextTokenCanFollowModifier);
17749 }
17750 function nextTokenIsOnSameLineAndCanFollowModifier() {
17751 nextToken();
17752 if (scanner.hasPrecedingLineBreak()) {
17753 return false;
17754 }
17755 return canFollowModifier();
17756 }
17757 function nextTokenCanFollowModifier() {
17758 switch (token()) {
17759 case 77 /* ConstKeyword */:
17760 // 'const' is only a modifier if followed by 'enum'.
17761 return nextToken() === 84 /* EnumKeyword */;
17762 case 85 /* ExportKeyword */:
17763 nextToken();
17764 if (token() === 80 /* DefaultKeyword */) {
17765 return lookAhead(nextTokenCanFollowDefaultKeyword);
17766 }
17767 return token() !== 40 /* AsteriskToken */ && token() !== 119 /* AsKeyword */ && token() !== 18 /* OpenBraceToken */ && canFollowModifier();
17768 case 80 /* DefaultKeyword */:
17769 return nextTokenCanFollowDefaultKeyword();
17770 case 116 /* StaticKeyword */:
17771 case 126 /* GetKeyword */:
17772 case 137 /* SetKeyword */:
17773 nextToken();
17774 return canFollowModifier();
17775 default:
17776 return nextTokenIsOnSameLineAndCanFollowModifier();
17777 }
17778 }
17779 function parseAnyContextualModifier() {
17780 return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
17781 }
17782 function canFollowModifier() {
17783 return token() === 22 /* OpenBracketToken */
17784 || token() === 18 /* OpenBraceToken */
17785 || token() === 40 /* AsteriskToken */
17786 || token() === 25 /* DotDotDotToken */
17787 || isLiteralPropertyName();
17788 }
17789 function nextTokenCanFollowDefaultKeyword() {
17790 nextToken();
17791 return token() === 76 /* ClassKeyword */ || token() === 90 /* FunctionKeyword */ ||
17792 token() === 110 /* InterfaceKeyword */ ||
17793 (token() === 118 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
17794 (token() === 121 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
17795 }
17796 // True if positioned at the start of a list element
17797 function isListElement(parsingContext, inErrorRecovery) {
17798 var node = currentNode(parsingContext);
17799 if (node) {
17800 return true;
17801 }
17802 switch (parsingContext) {
17803 case 0 /* SourceElements */:
17804 case 1 /* BlockStatements */:
17805 case 3 /* SwitchClauseStatements */:
17806 // If we're in error recovery, then we don't want to treat ';' as an empty statement.
17807 // The problem is that ';' can show up in far too many contexts, and if we see one
17808 // and assume it's a statement, then we may bail out inappropriately from whatever
17809 // we're parsing. For example, if we have a semicolon in the middle of a class, then
17810 // we really don't want to assume the class is over and we're on a statement in the
17811 // outer module. We just want to consume and move on.
17812 return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
17813 case 2 /* SwitchClauses */:
17814 return token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */;
17815 case 4 /* TypeMembers */:
17816 return lookAhead(isTypeMemberStart);
17817 case 5 /* ClassMembers */:
17818 // We allow semicolons as class elements (as specified by ES6) as long as we're
17819 // not in error recovery. If we're in error recovery, we don't want an errant
17820 // semicolon to be treated as a class member (since they're almost always used
17821 // for statements.
17822 return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
17823 case 6 /* EnumMembers */:
17824 // Include open bracket computed properties. This technically also lets in indexers,
17825 // which would be a candidate for improved error reporting.
17826 return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
17827 case 12 /* ObjectLiteralMembers */:
17828 switch (token()) {
17829 case 22 /* OpenBracketToken */:
17830 case 40 /* AsteriskToken */:
17831 case 25 /* DotDotDotToken */:
17832 case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
17833 return true;
17834 default:
17835 return isLiteralPropertyName();
17836 }
17837 case 18 /* RestProperties */:
17838 return isLiteralPropertyName();
17839 case 9 /* ObjectBindingElements */:
17840 return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
17841 case 7 /* HeritageClauseElement */:
17842 // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
17843 // That way we won't consume the body of a class in its heritage clause.
17844 if (token() === 18 /* OpenBraceToken */) {
17845 return lookAhead(isValidHeritageClauseObjectLiteral);
17846 }
17847 if (!inErrorRecovery) {
17848 return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
17849 }
17850 else {
17851 // If we're in error recovery we tighten up what we're willing to match.
17852 // That way we don't treat something like "this" as a valid heritage clause
17853 // element during recovery.
17854 return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
17855 }
17856 case 8 /* VariableDeclarations */:
17857 return isIdentifierOrPattern();
17858 case 10 /* ArrayBindingElements */:
17859 return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPattern();
17860 case 19 /* TypeParameters */:
17861 return isIdentifier();
17862 case 15 /* ArrayLiteralMembers */:
17863 switch (token()) {
17864 case 27 /* CommaToken */:
17865 case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
17866 return true;
17867 }
17868 // falls through
17869 case 11 /* ArgumentExpressions */:
17870 return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
17871 case 16 /* Parameters */:
17872 return isStartOfParameter(/*isJSDocParameter*/ false);
17873 case 17 /* JSDocParameters */:
17874 return isStartOfParameter(/*isJSDocParameter*/ true);
17875 case 20 /* TypeArguments */:
17876 case 21 /* TupleElementTypes */:
17877 return token() === 27 /* CommaToken */ || isStartOfType();
17878 case 22 /* HeritageClauses */:
17879 return isHeritageClause();
17880 case 23 /* ImportOrExportSpecifiers */:
17881 return ts.tokenIsIdentifierOrKeyword(token());
17882 case 13 /* JsxAttributes */:
17883 return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
17884 case 14 /* JsxChildren */:
17885 return true;
17886 }
17887 return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
17888 }
17889 function isValidHeritageClauseObjectLiteral() {
17890 ts.Debug.assert(token() === 18 /* OpenBraceToken */);
17891 if (nextToken() === 19 /* CloseBraceToken */) {
17892 // if we see "extends {}" then only treat the {} as what we're extending (and not
17893 // the class body) if we have:
17894 //
17895 // extends {} {
17896 // extends {},
17897 // extends {} extends
17898 // extends {} implements
17899 var next = nextToken();
17900 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 86 /* ExtendsKeyword */ || next === 109 /* ImplementsKeyword */;
17901 }
17902 return true;
17903 }
17904 function nextTokenIsIdentifier() {
17905 nextToken();
17906 return isIdentifier();
17907 }
17908 function nextTokenIsIdentifierOrKeyword() {
17909 nextToken();
17910 return ts.tokenIsIdentifierOrKeyword(token());
17911 }
17912 function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
17913 nextToken();
17914 return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
17915 }
17916 function isHeritageClauseExtendsOrImplementsKeyword() {
17917 if (token() === 109 /* ImplementsKeyword */ ||
17918 token() === 86 /* ExtendsKeyword */) {
17919 return lookAhead(nextTokenIsStartOfExpression);
17920 }
17921 return false;
17922 }
17923 function nextTokenIsStartOfExpression() {
17924 nextToken();
17925 return isStartOfExpression();
17926 }
17927 function nextTokenIsStartOfType() {
17928 nextToken();
17929 return isStartOfType();
17930 }
17931 // True if positioned at a list terminator
17932 function isListTerminator(kind) {
17933 if (token() === 1 /* EndOfFileToken */) {
17934 // Being at the end of the file ends all lists.
17935 return true;
17936 }
17937 switch (kind) {
17938 case 1 /* BlockStatements */:
17939 case 2 /* SwitchClauses */:
17940 case 4 /* TypeMembers */:
17941 case 5 /* ClassMembers */:
17942 case 6 /* EnumMembers */:
17943 case 12 /* ObjectLiteralMembers */:
17944 case 9 /* ObjectBindingElements */:
17945 case 23 /* ImportOrExportSpecifiers */:
17946 return token() === 19 /* CloseBraceToken */;
17947 case 3 /* SwitchClauseStatements */:
17948 return token() === 19 /* CloseBraceToken */ || token() === 74 /* CaseKeyword */ || token() === 80 /* DefaultKeyword */;
17949 case 7 /* HeritageClauseElement */:
17950 return token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */;
17951 case 8 /* VariableDeclarations */:
17952 return isVariableDeclaratorListTerminator();
17953 case 19 /* TypeParameters */:
17954 // Tokens other than '>' are here for better error recovery
17955 return token() === 30 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */;
17956 case 11 /* ArgumentExpressions */:
17957 // Tokens other than ')' are here for better error recovery
17958 return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
17959 case 15 /* ArrayLiteralMembers */:
17960 case 21 /* TupleElementTypes */:
17961 case 10 /* ArrayBindingElements */:
17962 return token() === 23 /* CloseBracketToken */;
17963 case 17 /* JSDocParameters */:
17964 case 16 /* Parameters */:
17965 case 18 /* RestProperties */:
17966 // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
17967 return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
17968 case 20 /* TypeArguments */:
17969 // All other tokens should cause the type-argument to terminate except comma token
17970 return token() !== 27 /* CommaToken */;
17971 case 22 /* HeritageClauses */:
17972 return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
17973 case 13 /* JsxAttributes */:
17974 return token() === 30 /* GreaterThanToken */ || token() === 42 /* SlashToken */;
17975 case 14 /* JsxChildren */:
17976 return token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
17977 default:
17978 return false;
17979 }
17980 }
17981 function isVariableDeclaratorListTerminator() {
17982 // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
17983 // with parsing the list of variable declarators.
17984 if (canParseSemicolon()) {
17985 return true;
17986 }
17987 // in the case where we're parsing the variable declarator of a 'for-in' statement, we
17988 // are done if we see an 'in' keyword in front of us. Same with for-of
17989 if (isInOrOfKeyword(token())) {
17990 return true;
17991 }
17992 // ERROR RECOVERY TWEAK:
17993 // For better error recovery, if we see an '=>' then we just stop immediately. We've got an
17994 // arrow function here and it's going to be very unlikely that we'll resynchronize and get
17995 // another variable declaration.
17996 if (token() === 37 /* EqualsGreaterThanToken */) {
17997 return true;
17998 }
17999 // Keep trying to parse out variable declarators.
18000 return false;
18001 }
18002 // True if positioned at element or terminator of the current list or any enclosing list
18003 function isInSomeParsingContext() {
18004 for (var kind = 0; kind < 24 /* Count */; kind++) {
18005 if (parsingContext & (1 << kind)) {
18006 if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
18007 return true;
18008 }
18009 }
18010 }
18011 return false;
18012 }
18013 // Parses a list of elements
18014 function parseList(kind, parseElement) {
18015 var saveParsingContext = parsingContext;
18016 parsingContext |= 1 << kind;
18017 var list = [];
18018 var listPos = getNodePos();
18019 while (!isListTerminator(kind)) {
18020 if (isListElement(kind, /*inErrorRecovery*/ false)) {
18021 var element = parseListElement(kind, parseElement);
18022 list.push(element);
18023 continue;
18024 }
18025 if (abortParsingListOrMoveToNextToken(kind)) {
18026 break;
18027 }
18028 }
18029 parsingContext = saveParsingContext;
18030 return createNodeArray(list, listPos);
18031 }
18032 function parseListElement(parsingContext, parseElement) {
18033 var node = currentNode(parsingContext);
18034 if (node) {
18035 return consumeNode(node);
18036 }
18037 return parseElement();
18038 }
18039 function currentNode(parsingContext) {
18040 // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
18041 //
18042 // If there is an outstanding parse error that we've encountered, but not attached to
18043 // some node, then we cannot get a node from the old source tree. This is because we
18044 // want to mark the next node we encounter as being unusable.
18045 //
18046 // Note: This may be too conservative. Perhaps we could reuse the node and set the bit
18047 // on it (or its leftmost child) as having the error. For now though, being conservative
18048 // is nice and likely won't ever affect perf.
18049 if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
18050 return undefined;
18051 }
18052 var node = syntaxCursor.currentNode(scanner.getStartPos());
18053 // Can't reuse a missing node.
18054 // Can't reuse a node that intersected the change range.
18055 // Can't reuse a node that contains a parse error. This is necessary so that we
18056 // produce the same set of errors again.
18057 if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
18058 return undefined;
18059 }
18060 // We can only reuse a node if it was parsed under the same strict mode that we're
18061 // currently in. i.e. if we originally parsed a node in non-strict mode, but then
18062 // the user added 'using strict' at the top of the file, then we can't use that node
18063 // again as the presence of strict mode may cause us to parse the tokens in the file
18064 // differently.
18065 //
18066 // Note: we *can* reuse tokens when the strict mode changes. That's because tokens
18067 // are unaffected by strict mode. It's just the parser will decide what to do with it
18068 // differently depending on what mode it is in.
18069 //
18070 // This also applies to all our other context flags as well.
18071 var nodeContextFlags = node.flags & 12679168 /* ContextFlags */;
18072 if (nodeContextFlags !== contextFlags) {
18073 return undefined;
18074 }
18075 // Ok, we have a node that looks like it could be reused. Now verify that it is valid
18076 // in the current list parsing context that we're currently at.
18077 if (!canReuseNode(node, parsingContext)) {
18078 return undefined;
18079 }
18080 if (node.jsDocCache) {
18081 // jsDocCache may include tags from parent nodes, which might have been modified.
18082 node.jsDocCache = undefined;
18083 }
18084 return node;
18085 }
18086 function consumeNode(node) {
18087 // Move the scanner so it is after the node we just consumed.
18088 scanner.setTextPos(node.end);
18089 nextToken();
18090 return node;
18091 }
18092 function isReusableParsingContext(parsingContext) {
18093 switch (parsingContext) {
18094 case 5 /* ClassMembers */:
18095 case 2 /* SwitchClauses */:
18096 case 0 /* SourceElements */:
18097 case 1 /* BlockStatements */:
18098 case 3 /* SwitchClauseStatements */:
18099 case 6 /* EnumMembers */:
18100 case 4 /* TypeMembers */:
18101 case 8 /* VariableDeclarations */:
18102 case 17 /* JSDocParameters */:
18103 case 16 /* Parameters */:
18104 return true;
18105 }
18106 return false;
18107 }
18108 function canReuseNode(node, parsingContext) {
18109 switch (parsingContext) {
18110 case 5 /* ClassMembers */:
18111 return isReusableClassMember(node);
18112 case 2 /* SwitchClauses */:
18113 return isReusableSwitchClause(node);
18114 case 0 /* SourceElements */:
18115 case 1 /* BlockStatements */:
18116 case 3 /* SwitchClauseStatements */:
18117 return isReusableStatement(node);
18118 case 6 /* EnumMembers */:
18119 return isReusableEnumMember(node);
18120 case 4 /* TypeMembers */:
18121 return isReusableTypeMember(node);
18122 case 8 /* VariableDeclarations */:
18123 return isReusableVariableDeclaration(node);
18124 case 17 /* JSDocParameters */:
18125 case 16 /* Parameters */:
18126 return isReusableParameter(node);
18127 // Any other lists we do not care about reusing nodes in. But feel free to add if
18128 // you can do so safely. Danger areas involve nodes that may involve speculative
18129 // parsing. If speculative parsing is involved with the node, then the range the
18130 // parser reached while looking ahead might be in the edited range (see the example
18131 // in canReuseVariableDeclaratorNode for a good case of this).
18132 // case ParsingContext.HeritageClauses:
18133 // This would probably be safe to reuse. There is no speculative parsing with
18134 // heritage clauses.
18135 // case ParsingContext.TypeParameters:
18136 // This would probably be safe to reuse. There is no speculative parsing with
18137 // type parameters. Note that that's because type *parameters* only occur in
18138 // unambiguous *type* contexts. While type *arguments* occur in very ambiguous
18139 // *expression* contexts.
18140 // case ParsingContext.TupleElementTypes:
18141 // This would probably be safe to reuse. There is no speculative parsing with
18142 // tuple types.
18143 // Technically, type argument list types are probably safe to reuse. While
18144 // speculative parsing is involved with them (since type argument lists are only
18145 // produced from speculative parsing a < as a type argument list), we only have
18146 // the types because speculative parsing succeeded. Thus, the lookahead never
18147 // went past the end of the list and rewound.
18148 // case ParsingContext.TypeArguments:
18149 // Note: these are almost certainly not safe to ever reuse. Expressions commonly
18150 // need a large amount of lookahead, and we should not reuse them as they may
18151 // have actually intersected the edit.
18152 // case ParsingContext.ArgumentExpressions:
18153 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
18154 // cases. i.e. a property assignment may end with an expression, and thus might
18155 // have lookahead far beyond it's old node.
18156 // case ParsingContext.ObjectLiteralMembers:
18157 // This is probably not safe to reuse. There can be speculative parsing with
18158 // type names in a heritage clause. There can be generic names in the type
18159 // name list, and there can be left hand side expressions (which can have type
18160 // arguments.)
18161 // case ParsingContext.HeritageClauseElement:
18162 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
18163 // on any given element. Same for children.
18164 // case ParsingContext.JsxAttributes:
18165 // case ParsingContext.JsxChildren:
18166 }
18167 return false;
18168 }
18169 function isReusableClassMember(node) {
18170 if (node) {
18171 switch (node.kind) {
18172 case 157 /* Constructor */:
18173 case 162 /* IndexSignature */:
18174 case 158 /* GetAccessor */:
18175 case 159 /* SetAccessor */:
18176 case 154 /* PropertyDeclaration */:
18177 case 217 /* SemicolonClassElement */:
18178 return true;
18179 case 156 /* MethodDeclaration */:
18180 // Method declarations are not necessarily reusable. An object-literal
18181 // may have a method calls "constructor(...)" and we must reparse that
18182 // into an actual .ConstructorDeclaration.
18183 var methodDeclaration = node;
18184 var nameIsConstructor = methodDeclaration.name.kind === 72 /* Identifier */ &&
18185 methodDeclaration.name.originalKeywordKind === 124 /* ConstructorKeyword */;
18186 return !nameIsConstructor;
18187 }
18188 }
18189 return false;
18190 }
18191 function isReusableSwitchClause(node) {
18192 if (node) {
18193 switch (node.kind) {
18194 case 271 /* CaseClause */:
18195 case 272 /* DefaultClause */:
18196 return true;
18197 }
18198 }
18199 return false;
18200 }
18201 function isReusableStatement(node) {
18202 if (node) {
18203 switch (node.kind) {
18204 case 239 /* FunctionDeclaration */:
18205 case 219 /* VariableStatement */:
18206 case 218 /* Block */:
18207 case 222 /* IfStatement */:
18208 case 221 /* ExpressionStatement */:
18209 case 234 /* ThrowStatement */:
18210 case 230 /* ReturnStatement */:
18211 case 232 /* SwitchStatement */:
18212 case 229 /* BreakStatement */:
18213 case 228 /* ContinueStatement */:
18214 case 226 /* ForInStatement */:
18215 case 227 /* ForOfStatement */:
18216 case 225 /* ForStatement */:
18217 case 224 /* WhileStatement */:
18218 case 231 /* WithStatement */:
18219 case 220 /* EmptyStatement */:
18220 case 235 /* TryStatement */:
18221 case 233 /* LabeledStatement */:
18222 case 223 /* DoStatement */:
18223 case 236 /* DebuggerStatement */:
18224 case 249 /* ImportDeclaration */:
18225 case 248 /* ImportEqualsDeclaration */:
18226 case 255 /* ExportDeclaration */:
18227 case 254 /* ExportAssignment */:
18228 case 244 /* ModuleDeclaration */:
18229 case 240 /* ClassDeclaration */:
18230 case 241 /* InterfaceDeclaration */:
18231 case 243 /* EnumDeclaration */:
18232 case 242 /* TypeAliasDeclaration */:
18233 return true;
18234 }
18235 }
18236 return false;
18237 }
18238 function isReusableEnumMember(node) {
18239 return node.kind === 278 /* EnumMember */;
18240 }
18241 function isReusableTypeMember(node) {
18242 if (node) {
18243 switch (node.kind) {
18244 case 161 /* ConstructSignature */:
18245 case 155 /* MethodSignature */:
18246 case 162 /* IndexSignature */:
18247 case 153 /* PropertySignature */:
18248 case 160 /* CallSignature */:
18249 return true;
18250 }
18251 }
18252 return false;
18253 }
18254 function isReusableVariableDeclaration(node) {
18255 if (node.kind !== 237 /* VariableDeclaration */) {
18256 return false;
18257 }
18258 // Very subtle incremental parsing bug. Consider the following code:
18259 //
18260 // let v = new List < A, B
18261 //
18262 // This is actually legal code. It's a list of variable declarators "v = new List<A"
18263 // on one side and "B" on the other. If you then change that to:
18264 //
18265 // let v = new List < A, B >()
18266 //
18267 // then we have a problem. "v = new List<A" doesn't intersect the change range, so we
18268 // start reparsing at "B" and we completely fail to handle this properly.
18269 //
18270 // In order to prevent this, we do not allow a variable declarator to be reused if it
18271 // has an initializer.
18272 var variableDeclarator = node;
18273 return variableDeclarator.initializer === undefined;
18274 }
18275 function isReusableParameter(node) {
18276 if (node.kind !== 151 /* Parameter */) {
18277 return false;
18278 }
18279 // See the comment in isReusableVariableDeclaration for why we do this.
18280 var parameter = node;
18281 return parameter.initializer === undefined;
18282 }
18283 // Returns true if we should abort parsing.
18284 function abortParsingListOrMoveToNextToken(kind) {
18285 parseErrorAtCurrentToken(parsingContextErrors(kind));
18286 if (isInSomeParsingContext()) {
18287 return true;
18288 }
18289 nextToken();
18290 return false;
18291 }
18292 function parsingContextErrors(context) {
18293 switch (context) {
18294 case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected;
18295 case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected;
18296 case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected;
18297 case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected;
18298 case 18 /* RestProperties */: // fallthrough
18299 case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected;
18300 case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
18301 case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected;
18302 case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected;
18303 case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected;
18304 case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected;
18305 case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected;
18306 case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected;
18307 case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected;
18308 case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected;
18309 case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected;
18310 case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected;
18311 case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected;
18312 case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected;
18313 case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected;
18314 case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected;
18315 case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected;
18316 case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected;
18317 case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected;
18318 default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);`
18319 }
18320 }
18321 // Parses a comma-delimited list of elements
18322 function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
18323 var saveParsingContext = parsingContext;
18324 parsingContext |= 1 << kind;
18325 var list = [];
18326 var listPos = getNodePos();
18327 var commaStart = -1; // Meaning the previous token was not a comma
18328 while (true) {
18329 if (isListElement(kind, /*inErrorRecovery*/ false)) {
18330 var startPos = scanner.getStartPos();
18331 list.push(parseListElement(kind, parseElement));
18332 commaStart = scanner.getTokenPos();
18333 if (parseOptional(27 /* CommaToken */)) {
18334 // No need to check for a zero length node since we know we parsed a comma
18335 continue;
18336 }
18337 commaStart = -1; // Back to the state where the last token was not a comma
18338 if (isListTerminator(kind)) {
18339 break;
18340 }
18341 // We didn't get a comma, and the list wasn't terminated, explicitly parse
18342 // out a comma so we give a good error message.
18343 parseExpected(27 /* CommaToken */);
18344 // If the token was a semicolon, and the caller allows that, then skip it and
18345 // continue. This ensures we get back on track and don't result in tons of
18346 // parse errors. For example, this can happen when people do things like use
18347 // a semicolon to delimit object literal members. Note: we'll have already
18348 // reported an error when we called parseExpected above.
18349 if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
18350 nextToken();
18351 }
18352 if (startPos === scanner.getStartPos()) {
18353 // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
18354 // Consume a token to advance the parser in some way and avoid an infinite loop
18355 // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
18356 // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
18357 nextToken();
18358 }
18359 continue;
18360 }
18361 if (isListTerminator(kind)) {
18362 break;
18363 }
18364 if (abortParsingListOrMoveToNextToken(kind)) {
18365 break;
18366 }
18367 }
18368 parsingContext = saveParsingContext;
18369 var result = createNodeArray(list, listPos);
18370 // Recording the trailing comma is deliberately done after the previous
18371 // loop, and not just if we see a list terminator. This is because the list
18372 // may have ended incorrectly, but it is still important to know if there
18373 // was a trailing comma.
18374 // Check if the last token was a comma.
18375 if (commaStart >= 0) {
18376 // Always preserve a trailing comma by marking it on the NodeArray
18377 result.hasTrailingComma = true;
18378 }
18379 return result;
18380 }
18381 function createMissingList() {
18382 var list = createNodeArray([], getNodePos());
18383 list.isMissingList = true;
18384 return list;
18385 }
18386 function isMissingList(arr) {
18387 return !!arr.isMissingList;
18388 }
18389 function parseBracketedList(kind, parseElement, open, close) {
18390 if (parseExpected(open)) {
18391 var result = parseDelimitedList(kind, parseElement);
18392 parseExpected(close);
18393 return result;
18394 }
18395 return createMissingList();
18396 }
18397 function parseEntityName(allowReservedWords, diagnosticMessage) {
18398 var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
18399 var dotPos = scanner.getStartPos();
18400 while (parseOptional(24 /* DotToken */)) {
18401 if (token() === 28 /* LessThanToken */) {
18402 // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
18403 entity.jsdocDotPos = dotPos;
18404 break;
18405 }
18406 dotPos = scanner.getStartPos();
18407 entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords));
18408 }
18409 return entity;
18410 }
18411 function createQualifiedName(entity, name) {
18412 var node = createNode(148 /* QualifiedName */, entity.pos);
18413 node.left = entity;
18414 node.right = name;
18415 return finishNode(node);
18416 }
18417 function parseRightSideOfDot(allowIdentifierNames) {
18418 // Technically a keyword is valid here as all identifiers and keywords are identifier names.
18419 // However, often we'll encounter this in error situations when the identifier or keyword
18420 // is actually starting another valid construct.
18421 //
18422 // So, we check for the following specific case:
18423 //
18424 // name.
18425 // identifierOrKeyword identifierNameOrKeyword
18426 //
18427 // Note: the newlines are important here. For example, if that above code
18428 // were rewritten into:
18429 //
18430 // name.identifierOrKeyword
18431 // identifierNameOrKeyword
18432 //
18433 // Then we would consider it valid. That's because ASI would take effect and
18434 // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
18435 // In the first case though, ASI will not take effect because there is not a
18436 // line terminator after the identifier or keyword.
18437 if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
18438 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
18439 if (matchesPattern) {
18440 // Report that we need an identifier. However, report it right after the dot,
18441 // and not on the next token. This is because the next token might actually
18442 // be an identifier and the error would be quite confusing.
18443 return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
18444 }
18445 }
18446 return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
18447 }
18448 function parseTemplateExpression() {
18449 var template = createNode(206 /* TemplateExpression */);
18450 template.head = parseTemplateHead();
18451 ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
18452 var list = [];
18453 var listPos = getNodePos();
18454 do {
18455 list.push(parseTemplateSpan());
18456 } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */);
18457 template.templateSpans = createNodeArray(list, listPos);
18458 return finishNode(template);
18459 }
18460 function parseTemplateSpan() {
18461 var span = createNode(216 /* TemplateSpan */);
18462 span.expression = allowInAnd(parseExpression);
18463 var literal;
18464 if (token() === 19 /* CloseBraceToken */) {
18465 reScanTemplateToken();
18466 literal = parseTemplateMiddleOrTemplateTail();
18467 }
18468 else {
18469 literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
18470 }
18471 span.literal = literal;
18472 return finishNode(span);
18473 }
18474 function parseLiteralNode() {
18475 return parseLiteralLikeNode(token());
18476 }
18477 function parseTemplateHead() {
18478 var fragment = parseLiteralLikeNode(token());
18479 ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
18480 return fragment;
18481 }
18482 function parseTemplateMiddleOrTemplateTail() {
18483 var fragment = parseLiteralLikeNode(token());
18484 ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
18485 return fragment;
18486 }
18487 function parseLiteralLikeNode(kind) {
18488 var node = createNode(kind);
18489 node.text = scanner.getTokenValue();
18490 if (scanner.hasExtendedUnicodeEscape()) {
18491 node.hasExtendedUnicodeEscape = true;
18492 }
18493 if (scanner.isUnterminated()) {
18494 node.isUnterminated = true;
18495 }
18496 // Octal literals are not allowed in strict mode or ES5
18497 // Note that theoretically the following condition would hold true literals like 009,
18498 // which is not octal.But because of how the scanner separates the tokens, we would
18499 // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
18500 // We also do not need to check for negatives because any prefix operator would be part of a
18501 // parent unary expression.
18502 if (node.kind === 8 /* NumericLiteral */) {
18503 node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */;
18504 }
18505 nextToken();
18506 finishNode(node);
18507 return node;
18508 }
18509 // TYPES
18510 function parseTypeReference() {
18511 var node = createNode(164 /* TypeReference */);
18512 node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
18513 if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 28 /* LessThanToken */) {
18514 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */);
18515 }
18516 return finishNode(node);
18517 }
18518 // If true, we should abort parsing an error function.
18519 function typeHasArrowFunctionBlockingParseError(node) {
18520 switch (node.kind) {
18521 case 164 /* TypeReference */:
18522 return ts.nodeIsMissing(node.typeName);
18523 case 165 /* FunctionType */:
18524 case 166 /* ConstructorType */: {
18525 var _a = node, parameters = _a.parameters, type = _a.type;
18526 return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
18527 }
18528 case 177 /* ParenthesizedType */:
18529 return typeHasArrowFunctionBlockingParseError(node.type);
18530 default:
18531 return false;
18532 }
18533 }
18534 function parseThisTypePredicate(lhs) {
18535 nextToken();
18536 var node = createNode(163 /* TypePredicate */, lhs.pos);
18537 node.parameterName = lhs;
18538 node.type = parseType();
18539 return finishNode(node);
18540 }
18541 function parseThisTypeNode() {
18542 var node = createNode(178 /* ThisType */);
18543 nextToken();
18544 return finishNode(node);
18545 }
18546 function parseJSDocAllType(postFixEquals) {
18547 var result = createNode(289 /* JSDocAllType */);
18548 if (postFixEquals) {
18549 return createPostfixType(293 /* JSDocOptionalType */, result);
18550 }
18551 else {
18552 nextToken();
18553 }
18554 return finishNode(result);
18555 }
18556 function parseJSDocNonNullableType() {
18557 var result = createNode(292 /* JSDocNonNullableType */);
18558 nextToken();
18559 result.type = parseNonArrayType();
18560 return finishNode(result);
18561 }
18562 function parseJSDocUnknownOrNullableType() {
18563 var pos = scanner.getStartPos();
18564 // skip the ?
18565 nextToken();
18566 // Need to lookahead to decide if this is a nullable or unknown type.
18567 // Here are cases where we'll pick the unknown type:
18568 //
18569 // Foo(?,
18570 // { a: ? }
18571 // Foo(?)
18572 // Foo<?>
18573 // Foo(?=
18574 // (?|
18575 if (token() === 27 /* CommaToken */ ||
18576 token() === 19 /* CloseBraceToken */ ||
18577 token() === 21 /* CloseParenToken */ ||
18578 token() === 30 /* GreaterThanToken */ ||
18579 token() === 59 /* EqualsToken */ ||
18580 token() === 50 /* BarToken */) {
18581 var result = createNode(290 /* JSDocUnknownType */, pos);
18582 return finishNode(result);
18583 }
18584 else {
18585 var result = createNode(291 /* JSDocNullableType */, pos);
18586 result.type = parseType();
18587 return finishNode(result);
18588 }
18589 }
18590 function parseJSDocFunctionType() {
18591 if (lookAhead(nextTokenIsOpenParen)) {
18592 var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
18593 nextToken();
18594 fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
18595 return finishNode(result);
18596 }
18597 var node = createNode(164 /* TypeReference */);
18598 node.typeName = parseIdentifierName();
18599 return finishNode(node);
18600 }
18601 function parseJSDocParameter() {
18602 var parameter = createNode(151 /* Parameter */);
18603 if (token() === 100 /* ThisKeyword */ || token() === 95 /* NewKeyword */) {
18604 parameter.name = parseIdentifierName();
18605 parseExpected(57 /* ColonToken */);
18606 }
18607 parameter.type = parseJSDocType();
18608 return finishNode(parameter);
18609 }
18610 function parseJSDocType() {
18611 scanner.setInJSDocType(true);
18612 var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */);
18613 var type = parseTypeOrTypePredicate();
18614 scanner.setInJSDocType(false);
18615 if (dotdotdot) {
18616 var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
18617 variadic.type = type;
18618 type = finishNode(variadic);
18619 }
18620 if (token() === 59 /* EqualsToken */) {
18621 return createPostfixType(293 /* JSDocOptionalType */, type);
18622 }
18623 return type;
18624 }
18625 function parseTypeQuery() {
18626 var node = createNode(167 /* TypeQuery */);
18627 parseExpected(104 /* TypeOfKeyword */);
18628 node.exprName = parseEntityName(/*allowReservedWords*/ true);
18629 return finishNode(node);
18630 }
18631 function parseTypeParameter() {
18632 var node = createNode(150 /* TypeParameter */);
18633 node.name = parseIdentifier();
18634 if (parseOptional(86 /* ExtendsKeyword */)) {
18635 // It's not uncommon for people to write improper constraints to a generic. If the
18636 // user writes a constraint that is an expression and not an actual type, then parse
18637 // it out as an expression (so we can recover well), but report that a type is needed
18638 // instead.
18639 if (isStartOfType() || !isStartOfExpression()) {
18640 node.constraint = parseType();
18641 }
18642 else {
18643 // It was not a type, and it looked like an expression. Parse out an expression
18644 // here so we recover well. Note: it is important that we call parseUnaryExpression
18645 // and not parseExpression here. If the user has:
18646 //
18647 // <T extends "">
18648 //
18649 // We do *not* want to consume the `>` as we're consuming the expression for "".
18650 node.expression = parseUnaryExpressionOrHigher();
18651 }
18652 }
18653 if (parseOptional(59 /* EqualsToken */)) {
18654 node.default = parseType();
18655 }
18656 return finishNode(node);
18657 }
18658 function parseTypeParameters() {
18659 if (token() === 28 /* LessThanToken */) {
18660 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 28 /* LessThanToken */, 30 /* GreaterThanToken */);
18661 }
18662 }
18663 function parseParameterType() {
18664 if (parseOptional(57 /* ColonToken */)) {
18665 return parseType();
18666 }
18667 return undefined;
18668 }
18669 function isStartOfParameter(isJSDocParameter) {
18670 return token() === 25 /* DotDotDotToken */ ||
18671 isIdentifierOrPattern() ||
18672 ts.isModifierKind(token()) ||
18673 token() === 58 /* AtToken */ ||
18674 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
18675 }
18676 function parseParameter() {
18677 var node = createNodeWithJSDoc(151 /* Parameter */);
18678 if (token() === 100 /* ThisKeyword */) {
18679 node.name = createIdentifier(/*isIdentifier*/ true);
18680 node.type = parseParameterType();
18681 return finishNode(node);
18682 }
18683 node.decorators = parseDecorators();
18684 node.modifiers = parseModifiers();
18685 node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
18686 // FormalParameter [Yield,Await]:
18687 // BindingElement[?Yield,?Await]
18688 node.name = parseIdentifierOrPattern();
18689 if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) {
18690 // in cases like
18691 // 'use strict'
18692 // function foo(static)
18693 // isParameter('static') === true, because of isModifier('static')
18694 // however 'static' is not a legal identifier in a strict mode.
18695 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
18696 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
18697 // to avoid this we'll advance cursor to the next token.
18698 nextToken();
18699 }
18700 node.questionToken = parseOptionalToken(56 /* QuestionToken */);
18701 node.type = parseParameterType();
18702 node.initializer = parseInitializer();
18703 return finishNode(node);
18704 }
18705 /**
18706 * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined.
18707 * @returns If return type parsing succeeds
18708 */
18709 function fillSignature(returnToken, flags, signature) {
18710 if (!(flags & 32 /* JSDoc */)) {
18711 signature.typeParameters = parseTypeParameters();
18712 }
18713 var parametersParsedSuccessfully = parseParameterList(signature, flags);
18714 if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
18715 signature.type = parseTypeOrTypePredicate();
18716 if (typeHasArrowFunctionBlockingParseError(signature.type))
18717 return false;
18718 }
18719 return parametersParsedSuccessfully;
18720 }
18721 function shouldParseReturnType(returnToken, isType) {
18722 if (returnToken === 37 /* EqualsGreaterThanToken */) {
18723 parseExpected(returnToken);
18724 return true;
18725 }
18726 else if (parseOptional(57 /* ColonToken */)) {
18727 return true;
18728 }
18729 else if (isType && token() === 37 /* EqualsGreaterThanToken */) {
18730 // This is easy to get backward, especially in type contexts, so parse the type anyway
18731 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */));
18732 nextToken();
18733 return true;
18734 }
18735 return false;
18736 }
18737 // Returns true on success.
18738 function parseParameterList(signature, flags) {
18739 // FormalParameters [Yield,Await]: (modified)
18740 // [empty]
18741 // FormalParameterList[?Yield,Await]
18742 //
18743 // FormalParameter[Yield,Await]: (modified)
18744 // BindingElement[?Yield,Await]
18745 //
18746 // BindingElement [Yield,Await]: (modified)
18747 // SingleNameBinding[?Yield,?Await]
18748 // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
18749 //
18750 // SingleNameBinding [Yield,Await]:
18751 // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
18752 if (!parseExpected(20 /* OpenParenToken */)) {
18753 signature.parameters = createMissingList();
18754 return false;
18755 }
18756 var savedYieldContext = inYieldContext();
18757 var savedAwaitContext = inAwaitContext();
18758 setYieldContext(!!(flags & 1 /* Yield */));
18759 setAwaitContext(!!(flags & 2 /* Await */));
18760 signature.parameters = flags & 32 /* JSDoc */ ?
18761 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
18762 parseDelimitedList(16 /* Parameters */, parseParameter);
18763 setYieldContext(savedYieldContext);
18764 setAwaitContext(savedAwaitContext);
18765 return parseExpected(21 /* CloseParenToken */);
18766 }
18767 function parseTypeMemberSemicolon() {
18768 // We allow type members to be separated by commas or (possibly ASI) semicolons.
18769 // First check if it was a comma. If so, we're done with the member.
18770 if (parseOptional(27 /* CommaToken */)) {
18771 return;
18772 }
18773 // Didn't have a comma. We must have a (possible ASI) semicolon.
18774 parseSemicolon();
18775 }
18776 function parseSignatureMember(kind) {
18777 var node = createNodeWithJSDoc(kind);
18778 if (kind === 161 /* ConstructSignature */) {
18779 parseExpected(95 /* NewKeyword */);
18780 }
18781 fillSignature(57 /* ColonToken */, 4 /* Type */, node);
18782 parseTypeMemberSemicolon();
18783 return finishNode(node);
18784 }
18785 function isIndexSignature() {
18786 return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
18787 }
18788 function isUnambiguouslyIndexSignature() {
18789 // The only allowed sequence is:
18790 //
18791 // [id:
18792 //
18793 // However, for error recovery, we also check the following cases:
18794 //
18795 // [...
18796 // [id,
18797 // [id?,
18798 // [id?:
18799 // [id?]
18800 // [public id
18801 // [private id
18802 // [protected id
18803 // []
18804 //
18805 nextToken();
18806 if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
18807 return true;
18808 }
18809 if (ts.isModifierKind(token())) {
18810 nextToken();
18811 if (isIdentifier()) {
18812 return true;
18813 }
18814 }
18815 else if (!isIdentifier()) {
18816 return false;
18817 }
18818 else {
18819 // Skip the identifier
18820 nextToken();
18821 }
18822 // A colon signifies a well formed indexer
18823 // A comma should be a badly formed indexer because comma expressions are not allowed
18824 // in computed properties.
18825 if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */) {
18826 return true;
18827 }
18828 // Question mark could be an indexer with an optional property,
18829 // or it could be a conditional expression in a computed property.
18830 if (token() !== 56 /* QuestionToken */) {
18831 return false;
18832 }
18833 // If any of the following tokens are after the question mark, it cannot
18834 // be a conditional expression, so treat it as an indexer.
18835 nextToken();
18836 return token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
18837 }
18838 function parseIndexSignatureDeclaration(node) {
18839 node.kind = 162 /* IndexSignature */;
18840 node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
18841 node.type = parseTypeAnnotation();
18842 parseTypeMemberSemicolon();
18843 return finishNode(node);
18844 }
18845 function parsePropertyOrMethodSignature(node) {
18846 node.name = parsePropertyName();
18847 node.questionToken = parseOptionalToken(56 /* QuestionToken */);
18848 if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) {
18849 node.kind = 155 /* MethodSignature */;
18850 // Method signatures don't exist in expression contexts. So they have neither
18851 // [Yield] nor [Await]
18852 fillSignature(57 /* ColonToken */, 4 /* Type */, node);
18853 }
18854 else {
18855 node.kind = 153 /* PropertySignature */;
18856 node.type = parseTypeAnnotation();
18857 if (token() === 59 /* EqualsToken */) {
18858 // Although type literal properties cannot not have initializers, we attempt
18859 // to parse an initializer so we can report in the checker that an interface
18860 // property or type literal property cannot have an initializer.
18861 node.initializer = parseInitializer();
18862 }
18863 }
18864 parseTypeMemberSemicolon();
18865 return finishNode(node);
18866 }
18867 function isTypeMemberStart() {
18868 // Return true if we have the start of a signature member
18869 if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) {
18870 return true;
18871 }
18872 var idToken = false;
18873 // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
18874 while (ts.isModifierKind(token())) {
18875 idToken = true;
18876 nextToken();
18877 }
18878 // Index signatures and computed property names are type members
18879 if (token() === 22 /* OpenBracketToken */) {
18880 return true;
18881 }
18882 // Try to get the first property-like token following all modifiers
18883 if (isLiteralPropertyName()) {
18884 idToken = true;
18885 nextToken();
18886 }
18887 // If we were able to get any potential identifier, check that it is
18888 // the start of a member declaration
18889 if (idToken) {
18890 return token() === 20 /* OpenParenToken */ ||
18891 token() === 28 /* LessThanToken */ ||
18892 token() === 56 /* QuestionToken */ ||
18893 token() === 57 /* ColonToken */ ||
18894 token() === 27 /* CommaToken */ ||
18895 canParseSemicolon();
18896 }
18897 return false;
18898 }
18899 function parseTypeMember() {
18900 if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) {
18901 return parseSignatureMember(160 /* CallSignature */);
18902 }
18903 if (token() === 95 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
18904 return parseSignatureMember(161 /* ConstructSignature */);
18905 }
18906 var node = createNodeWithJSDoc(0 /* Unknown */);
18907 node.modifiers = parseModifiers();
18908 if (isIndexSignature()) {
18909 return parseIndexSignatureDeclaration(node);
18910 }
18911 return parsePropertyOrMethodSignature(node);
18912 }
18913 function nextTokenIsOpenParenOrLessThan() {
18914 nextToken();
18915 return token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */;
18916 }
18917 function nextTokenIsDot() {
18918 return nextToken() === 24 /* DotToken */;
18919 }
18920 function nextTokenIsOpenParenOrLessThanOrDot() {
18921 switch (nextToken()) {
18922 case 20 /* OpenParenToken */:
18923 case 28 /* LessThanToken */:
18924 case 24 /* DotToken */:
18925 return true;
18926 }
18927 return false;
18928 }
18929 function parseTypeLiteral() {
18930 var node = createNode(168 /* TypeLiteral */);
18931 node.members = parseObjectTypeMembers();
18932 return finishNode(node);
18933 }
18934 function parseObjectTypeMembers() {
18935 var members;
18936 if (parseExpected(18 /* OpenBraceToken */)) {
18937 members = parseList(4 /* TypeMembers */, parseTypeMember);
18938 parseExpected(19 /* CloseBraceToken */);
18939 }
18940 else {
18941 members = createMissingList();
18942 }
18943 return members;
18944 }
18945 function isStartOfMappedType() {
18946 nextToken();
18947 if (token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) {
18948 return nextToken() === 133 /* ReadonlyKeyword */;
18949 }
18950 if (token() === 133 /* ReadonlyKeyword */) {
18951 nextToken();
18952 }
18953 return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 93 /* InKeyword */;
18954 }
18955 function parseMappedTypeParameter() {
18956 var node = createNode(150 /* TypeParameter */);
18957 node.name = parseIdentifier();
18958 parseExpected(93 /* InKeyword */);
18959 node.constraint = parseType();
18960 return finishNode(node);
18961 }
18962 function parseMappedType() {
18963 var node = createNode(181 /* MappedType */);
18964 parseExpected(18 /* OpenBraceToken */);
18965 if (token() === 133 /* ReadonlyKeyword */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) {
18966 node.readonlyToken = parseTokenNode();
18967 if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) {
18968 parseExpectedToken(133 /* ReadonlyKeyword */);
18969 }
18970 }
18971 parseExpected(22 /* OpenBracketToken */);
18972 node.typeParameter = parseMappedTypeParameter();
18973 parseExpected(23 /* CloseBracketToken */);
18974 if (token() === 56 /* QuestionToken */ || token() === 38 /* PlusToken */ || token() === 39 /* MinusToken */) {
18975 node.questionToken = parseTokenNode();
18976 if (node.questionToken.kind !== 56 /* QuestionToken */) {
18977 parseExpectedToken(56 /* QuestionToken */);
18978 }
18979 }
18980 node.type = parseTypeAnnotation();
18981 parseSemicolon();
18982 parseExpected(19 /* CloseBraceToken */);
18983 return finishNode(node);
18984 }
18985 function parseTupleElementType() {
18986 var pos = getNodePos();
18987 if (parseOptional(25 /* DotDotDotToken */)) {
18988 var node = createNode(172 /* RestType */, pos);
18989 node.type = parseType();
18990 return finishNode(node);
18991 }
18992 var type = parseType();
18993 if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
18994 type.kind = 171 /* OptionalType */;
18995 }
18996 return type;
18997 }
18998 function parseTupleType() {
18999 var node = createNode(170 /* TupleType */);
19000 node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
19001 return finishNode(node);
19002 }
19003 function parseParenthesizedType() {
19004 var node = createNode(177 /* ParenthesizedType */);
19005 parseExpected(20 /* OpenParenToken */);
19006 node.type = parseType();
19007 parseExpected(21 /* CloseParenToken */);
19008 return finishNode(node);
19009 }
19010 function parseFunctionOrConstructorType() {
19011 var pos = getNodePos();
19012 var kind = parseOptional(95 /* NewKeyword */) ? 166 /* ConstructorType */ : 165 /* FunctionType */;
19013 var node = createNodeWithJSDoc(kind, pos);
19014 fillSignature(37 /* EqualsGreaterThanToken */, 4 /* Type */, node);
19015 return finishNode(node);
19016 }
19017 function parseKeywordAndNoDot() {
19018 var node = parseTokenNode();
19019 return token() === 24 /* DotToken */ ? undefined : node;
19020 }
19021 function parseLiteralTypeNode(negative) {
19022 var node = createNode(182 /* LiteralType */);
19023 var unaryMinusExpression;
19024 if (negative) {
19025 unaryMinusExpression = createNode(202 /* PrefixUnaryExpression */);
19026 unaryMinusExpression.operator = 39 /* MinusToken */;
19027 nextToken();
19028 }
19029 var expression = token() === 102 /* TrueKeyword */ || token() === 87 /* FalseKeyword */
19030 ? parseTokenNode()
19031 : parseLiteralLikeNode(token());
19032 if (negative) {
19033 unaryMinusExpression.operand = expression;
19034 finishNode(unaryMinusExpression);
19035 expression = unaryMinusExpression;
19036 }
19037 node.literal = expression;
19038 return finishNode(node);
19039 }
19040 function isStartOfTypeOfImportType() {
19041 nextToken();
19042 return token() === 92 /* ImportKeyword */;
19043 }
19044 function parseImportType() {
19045 sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */;
19046 var node = createNode(183 /* ImportType */);
19047 if (parseOptional(104 /* TypeOfKeyword */)) {
19048 node.isTypeOf = true;
19049 }
19050 parseExpected(92 /* ImportKeyword */);
19051 parseExpected(20 /* OpenParenToken */);
19052 node.argument = parseType();
19053 parseExpected(21 /* CloseParenToken */);
19054 if (parseOptional(24 /* DotToken */)) {
19055 node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
19056 }
19057 node.typeArguments = tryParseTypeArguments();
19058 return finishNode(node);
19059 }
19060 function nextTokenIsNumericOrBigIntLiteral() {
19061 nextToken();
19062 return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
19063 }
19064 function parseNonArrayType() {
19065 switch (token()) {
19066 case 120 /* AnyKeyword */:
19067 case 143 /* UnknownKeyword */:
19068 case 138 /* StringKeyword */:
19069 case 135 /* NumberKeyword */:
19070 case 146 /* BigIntKeyword */:
19071 case 139 /* SymbolKeyword */:
19072 case 123 /* BooleanKeyword */:
19073 case 141 /* UndefinedKeyword */:
19074 case 132 /* NeverKeyword */:
19075 case 136 /* ObjectKeyword */:
19076 // If these are followed by a dot, then parse these out as a dotted type reference instead.
19077 return tryParse(parseKeywordAndNoDot) || parseTypeReference();
19078 case 40 /* AsteriskToken */:
19079 return parseJSDocAllType(/*postfixEquals*/ false);
19080 case 62 /* AsteriskEqualsToken */:
19081 return parseJSDocAllType(/*postfixEquals*/ true);
19082 case 56 /* QuestionToken */:
19083 return parseJSDocUnknownOrNullableType();
19084 case 90 /* FunctionKeyword */:
19085 return parseJSDocFunctionType();
19086 case 52 /* ExclamationToken */:
19087 return parseJSDocNonNullableType();
19088 case 14 /* NoSubstitutionTemplateLiteral */:
19089 case 10 /* StringLiteral */:
19090 case 8 /* NumericLiteral */:
19091 case 9 /* BigIntLiteral */:
19092 case 102 /* TrueKeyword */:
19093 case 87 /* FalseKeyword */:
19094 return parseLiteralTypeNode();
19095 case 39 /* MinusToken */:
19096 return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
19097 case 106 /* VoidKeyword */:
19098 case 96 /* NullKeyword */:
19099 return parseTokenNode();
19100 case 100 /* ThisKeyword */: {
19101 var thisKeyword = parseThisTypeNode();
19102 if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
19103 return parseThisTypePredicate(thisKeyword);
19104 }
19105 else {
19106 return thisKeyword;
19107 }
19108 }
19109 case 104 /* TypeOfKeyword */:
19110 return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
19111 case 18 /* OpenBraceToken */:
19112 return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
19113 case 22 /* OpenBracketToken */:
19114 return parseTupleType();
19115 case 20 /* OpenParenToken */:
19116 return parseParenthesizedType();
19117 case 92 /* ImportKeyword */:
19118 return parseImportType();
19119 default:
19120 return parseTypeReference();
19121 }
19122 }
19123 function isStartOfType(inStartOfParameter) {
19124 switch (token()) {
19125 case 120 /* AnyKeyword */:
19126 case 143 /* UnknownKeyword */:
19127 case 138 /* StringKeyword */:
19128 case 135 /* NumberKeyword */:
19129 case 146 /* BigIntKeyword */:
19130 case 123 /* BooleanKeyword */:
19131 case 133 /* ReadonlyKeyword */:
19132 case 139 /* SymbolKeyword */:
19133 case 142 /* UniqueKeyword */:
19134 case 106 /* VoidKeyword */:
19135 case 141 /* UndefinedKeyword */:
19136 case 96 /* NullKeyword */:
19137 case 100 /* ThisKeyword */:
19138 case 104 /* TypeOfKeyword */:
19139 case 132 /* NeverKeyword */:
19140 case 18 /* OpenBraceToken */:
19141 case 22 /* OpenBracketToken */:
19142 case 28 /* LessThanToken */:
19143 case 50 /* BarToken */:
19144 case 49 /* AmpersandToken */:
19145 case 95 /* NewKeyword */:
19146 case 10 /* StringLiteral */:
19147 case 8 /* NumericLiteral */:
19148 case 9 /* BigIntLiteral */:
19149 case 102 /* TrueKeyword */:
19150 case 87 /* FalseKeyword */:
19151 case 136 /* ObjectKeyword */:
19152 case 40 /* AsteriskToken */:
19153 case 56 /* QuestionToken */:
19154 case 52 /* ExclamationToken */:
19155 case 25 /* DotDotDotToken */:
19156 case 127 /* InferKeyword */:
19157 case 92 /* ImportKeyword */:
19158 return true;
19159 case 90 /* FunctionKeyword */:
19160 return !inStartOfParameter;
19161 case 39 /* MinusToken */:
19162 return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
19163 case 20 /* OpenParenToken */:
19164 // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
19165 // or something that starts a type. We don't want to consider things like '(1)' a type.
19166 return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
19167 default:
19168 return isIdentifier();
19169 }
19170 }
19171 function isStartOfParenthesizedOrFunctionType() {
19172 nextToken();
19173 return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
19174 }
19175 function parsePostfixTypeOrHigher() {
19176 var type = parseNonArrayType();
19177 while (!scanner.hasPrecedingLineBreak()) {
19178 switch (token()) {
19179 case 52 /* ExclamationToken */:
19180 type = createPostfixType(292 /* JSDocNonNullableType */, type);
19181 break;
19182 case 56 /* QuestionToken */:
19183 // If not in JSDoc and next token is start of a type we have a conditional type
19184 if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
19185 return type;
19186 }
19187 type = createPostfixType(291 /* JSDocNullableType */, type);
19188 break;
19189 case 22 /* OpenBracketToken */:
19190 parseExpected(22 /* OpenBracketToken */);
19191 if (isStartOfType()) {
19192 var node = createNode(180 /* IndexedAccessType */, type.pos);
19193 node.objectType = type;
19194 node.indexType = parseType();
19195 parseExpected(23 /* CloseBracketToken */);
19196 type = finishNode(node);
19197 }
19198 else {
19199 var node = createNode(169 /* ArrayType */, type.pos);
19200 node.elementType = type;
19201 parseExpected(23 /* CloseBracketToken */);
19202 type = finishNode(node);
19203 }
19204 break;
19205 default:
19206 return type;
19207 }
19208 }
19209 return type;
19210 }
19211 function createPostfixType(kind, type) {
19212 nextToken();
19213 var postfix = createNode(kind, type.pos);
19214 postfix.type = type;
19215 return finishNode(postfix);
19216 }
19217 function parseTypeOperator(operator) {
19218 var node = createNode(179 /* TypeOperator */);
19219 parseExpected(operator);
19220 node.operator = operator;
19221 node.type = parseTypeOperatorOrHigher();
19222 return finishNode(node);
19223 }
19224 function parseInferType() {
19225 var node = createNode(176 /* InferType */);
19226 parseExpected(127 /* InferKeyword */);
19227 var typeParameter = createNode(150 /* TypeParameter */);
19228 typeParameter.name = parseIdentifier();
19229 node.typeParameter = finishNode(typeParameter);
19230 return finishNode(node);
19231 }
19232 function parseTypeOperatorOrHigher() {
19233 var operator = token();
19234 switch (operator) {
19235 case 129 /* KeyOfKeyword */:
19236 case 142 /* UniqueKeyword */:
19237 case 133 /* ReadonlyKeyword */:
19238 return parseTypeOperator(operator);
19239 case 127 /* InferKeyword */:
19240 return parseInferType();
19241 }
19242 return parsePostfixTypeOrHigher();
19243 }
19244 function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
19245 parseOptional(operator);
19246 var type = parseConstituentType();
19247 if (token() === operator) {
19248 var types = [type];
19249 while (parseOptional(operator)) {
19250 types.push(parseConstituentType());
19251 }
19252 var node = createNode(kind, type.pos);
19253 node.types = createNodeArray(types, type.pos);
19254 type = finishNode(node);
19255 }
19256 return type;
19257 }
19258 function parseIntersectionTypeOrHigher() {
19259 return parseUnionOrIntersectionType(174 /* IntersectionType */, parseTypeOperatorOrHigher, 49 /* AmpersandToken */);
19260 }
19261 function parseUnionTypeOrHigher() {
19262 return parseUnionOrIntersectionType(173 /* UnionType */, parseIntersectionTypeOrHigher, 50 /* BarToken */);
19263 }
19264 function isStartOfFunctionType() {
19265 if (token() === 28 /* LessThanToken */) {
19266 return true;
19267 }
19268 return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
19269 }
19270 function skipParameterStart() {
19271 if (ts.isModifierKind(token())) {
19272 // Skip modifiers
19273 parseModifiers();
19274 }
19275 if (isIdentifier() || token() === 100 /* ThisKeyword */) {
19276 nextToken();
19277 return true;
19278 }
19279 if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
19280 // Return true if we can parse an array or object binding pattern with no errors
19281 var previousErrorCount = parseDiagnostics.length;
19282 parseIdentifierOrPattern();
19283 return previousErrorCount === parseDiagnostics.length;
19284 }
19285 return false;
19286 }
19287 function isUnambiguouslyStartOfFunctionType() {
19288 nextToken();
19289 if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
19290 // ( )
19291 // ( ...
19292 return true;
19293 }
19294 if (skipParameterStart()) {
19295 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
19296 // now see if we have something that indicates a parameter declaration
19297 if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ ||
19298 token() === 56 /* QuestionToken */ || token() === 59 /* EqualsToken */) {
19299 // ( xxx :
19300 // ( xxx ,
19301 // ( xxx ?
19302 // ( xxx =
19303 return true;
19304 }
19305 if (token() === 21 /* CloseParenToken */) {
19306 nextToken();
19307 if (token() === 37 /* EqualsGreaterThanToken */) {
19308 // ( xxx ) =>
19309 return true;
19310 }
19311 }
19312 }
19313 return false;
19314 }
19315 function parseTypeOrTypePredicate() {
19316 var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
19317 var type = parseType();
19318 if (typePredicateVariable) {
19319 var node = createNode(163 /* TypePredicate */, typePredicateVariable.pos);
19320 node.parameterName = typePredicateVariable;
19321 node.type = type;
19322 return finishNode(node);
19323 }
19324 else {
19325 return type;
19326 }
19327 }
19328 function parseTypePredicatePrefix() {
19329 var id = parseIdentifier();
19330 if (token() === 128 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
19331 nextToken();
19332 return id;
19333 }
19334 }
19335 function parseType() {
19336 // The rules about 'yield' only apply to actual code/expression contexts. They don't
19337 // apply to 'type' contexts. So we disable these parameters here before moving on.
19338 return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker);
19339 }
19340 function parseTypeWorker(noConditionalTypes) {
19341 if (isStartOfFunctionType() || token() === 95 /* NewKeyword */) {
19342 return parseFunctionOrConstructorType();
19343 }
19344 var type = parseUnionTypeOrHigher();
19345 if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(86 /* ExtendsKeyword */)) {
19346 var node = createNode(175 /* ConditionalType */, type.pos);
19347 node.checkType = type;
19348 // The type following 'extends' is not permitted to be another conditional type
19349 node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
19350 parseExpected(56 /* QuestionToken */);
19351 node.trueType = parseTypeWorker();
19352 parseExpected(57 /* ColonToken */);
19353 node.falseType = parseTypeWorker();
19354 return finishNode(node);
19355 }
19356 return type;
19357 }
19358 function parseTypeAnnotation() {
19359 return parseOptional(57 /* ColonToken */) ? parseType() : undefined;
19360 }
19361 // EXPRESSIONS
19362 function isStartOfLeftHandSideExpression() {
19363 switch (token()) {
19364 case 100 /* ThisKeyword */:
19365 case 98 /* SuperKeyword */:
19366 case 96 /* NullKeyword */:
19367 case 102 /* TrueKeyword */:
19368 case 87 /* FalseKeyword */:
19369 case 8 /* NumericLiteral */:
19370 case 9 /* BigIntLiteral */:
19371 case 10 /* StringLiteral */:
19372 case 14 /* NoSubstitutionTemplateLiteral */:
19373 case 15 /* TemplateHead */:
19374 case 20 /* OpenParenToken */:
19375 case 22 /* OpenBracketToken */:
19376 case 18 /* OpenBraceToken */:
19377 case 90 /* FunctionKeyword */:
19378 case 76 /* ClassKeyword */:
19379 case 95 /* NewKeyword */:
19380 case 42 /* SlashToken */:
19381 case 64 /* SlashEqualsToken */:
19382 case 72 /* Identifier */:
19383 return true;
19384 case 92 /* ImportKeyword */:
19385 return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
19386 default:
19387 return isIdentifier();
19388 }
19389 }
19390 function isStartOfExpression() {
19391 if (isStartOfLeftHandSideExpression()) {
19392 return true;
19393 }
19394 switch (token()) {
19395 case 38 /* PlusToken */:
19396 case 39 /* MinusToken */:
19397 case 53 /* TildeToken */:
19398 case 52 /* ExclamationToken */:
19399 case 81 /* DeleteKeyword */:
19400 case 104 /* TypeOfKeyword */:
19401 case 106 /* VoidKeyword */:
19402 case 44 /* PlusPlusToken */:
19403 case 45 /* MinusMinusToken */:
19404 case 28 /* LessThanToken */:
19405 case 122 /* AwaitKeyword */:
19406 case 117 /* YieldKeyword */:
19407 // Yield/await always starts an expression. Either it is an identifier (in which case
19408 // it is definitely an expression). Or it's a keyword (either because we're in
19409 // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
19410 return true;
19411 default:
19412 // Error tolerance. If we see the start of some binary operator, we consider
19413 // that the start of an expression. That way we'll parse out a missing identifier,
19414 // give a good message about an identifier being missing, and then consume the
19415 // rest of the binary expression.
19416 if (isBinaryOperator()) {
19417 return true;
19418 }
19419 return isIdentifier();
19420 }
19421 }
19422 function isStartOfExpressionStatement() {
19423 // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
19424 return token() !== 18 /* OpenBraceToken */ &&
19425 token() !== 90 /* FunctionKeyword */ &&
19426 token() !== 76 /* ClassKeyword */ &&
19427 token() !== 58 /* AtToken */ &&
19428 isStartOfExpression();
19429 }
19430 function parseExpression() {
19431 // Expression[in]:
19432 // AssignmentExpression[in]
19433 // Expression[in] , AssignmentExpression[in]
19434 // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
19435 var saveDecoratorContext = inDecoratorContext();
19436 if (saveDecoratorContext) {
19437 setDecoratorContext(/*val*/ false);
19438 }
19439 var expr = parseAssignmentExpressionOrHigher();
19440 var operatorToken;
19441 while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
19442 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
19443 }
19444 if (saveDecoratorContext) {
19445 setDecoratorContext(/*val*/ true);
19446 }
19447 return expr;
19448 }
19449 function parseInitializer() {
19450 return parseOptional(59 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
19451 }
19452 function parseAssignmentExpressionOrHigher() {
19453 // AssignmentExpression[in,yield]:
19454 // 1) ConditionalExpression[?in,?yield]
19455 // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
19456 // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
19457 // 4) ArrowFunctionExpression[?in,?yield]
19458 // 5) AsyncArrowFunctionExpression[in,yield,await]
19459 // 6) [+Yield] YieldExpression[?In]
19460 //
19461 // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
19462 // (i.e. they're both BinaryExpressions with an assignment operator in it).
19463 // First, do the simple check if we have a YieldExpression (production '6').
19464 if (isYieldExpression()) {
19465 return parseYieldExpression();
19466 }
19467 // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
19468 // parameter list or is an async arrow function.
19469 // AsyncArrowFunctionExpression:
19470 // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
19471 // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
19472 // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
19473 // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
19474 //
19475 // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
19476 // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done
19477 // with AssignmentExpression if we see one.
19478 var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
19479 if (arrowExpression) {
19480 return arrowExpression;
19481 }
19482 // Now try to see if we're in production '1', '2' or '3'. A conditional expression can
19483 // start with a LogicalOrExpression, while the assignment productions can only start with
19484 // LeftHandSideExpressions.
19485 //
19486 // So, first, we try to just parse out a BinaryExpression. If we get something that is a
19487 // LeftHandSide or higher, then we can try to parse out the assignment expression part.
19488 // Otherwise, we try to parse out the conditional expression bit. We want to allow any
19489 // binary expression here, so we pass in the 'lowest' precedence here so that it matches
19490 // and consumes anything.
19491 var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
19492 // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
19493 // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
19494 // identifier and the current token is an arrow.
19495 if (expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) {
19496 return parseSimpleArrowFunctionExpression(expr);
19497 }
19498 // Now see if we might be in cases '2' or '3'.
19499 // If the expression was a LHS expression, and we have an assignment operator, then
19500 // we're in '2' or '3'. Consume the assignment and return.
19501 //
19502 // Note: we call reScanGreaterToken so that we get an appropriately merged token
19503 // for cases like `> > =` becoming `>>=`
19504 if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
19505 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
19506 }
19507 // It wasn't an assignment or a lambda. This is a conditional expression:
19508 return parseConditionalExpressionRest(expr);
19509 }
19510 function isYieldExpression() {
19511 if (token() === 117 /* YieldKeyword */) {
19512 // If we have a 'yield' keyword, and this is a context where yield expressions are
19513 // allowed, then definitely parse out a yield expression.
19514 if (inYieldContext()) {
19515 return true;
19516 }
19517 // We're in a context where 'yield expr' is not allowed. However, if we can
19518 // definitely tell that the user was trying to parse a 'yield expr' and not
19519 // just a normal expr that start with a 'yield' identifier, then parse out
19520 // a 'yield expr'. We can then report an error later that they are only
19521 // allowed in generator expressions.
19522 //
19523 // for example, if we see 'yield(foo)', then we'll have to treat that as an
19524 // invocation expression of something called 'yield'. However, if we have
19525 // 'yield foo' then that is not legal as a normal expression, so we can
19526 // definitely recognize this as a yield expression.
19527 //
19528 // for now we just check if the next token is an identifier. More heuristics
19529 // can be added here later as necessary. We just need to make sure that we
19530 // don't accidentally consume something legal.
19531 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
19532 }
19533 return false;
19534 }
19535 function nextTokenIsIdentifierOnSameLine() {
19536 nextToken();
19537 return !scanner.hasPrecedingLineBreak() && isIdentifier();
19538 }
19539 function parseYieldExpression() {
19540 var node = createNode(207 /* YieldExpression */);
19541 // YieldExpression[In] :
19542 // yield
19543 // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
19544 // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
19545 nextToken();
19546 if (!scanner.hasPrecedingLineBreak() &&
19547 (token() === 40 /* AsteriskToken */ || isStartOfExpression())) {
19548 node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */);
19549 node.expression = parseAssignmentExpressionOrHigher();
19550 return finishNode(node);
19551 }
19552 else {
19553 // if the next token is not on the same line as yield. or we don't have an '*' or
19554 // the start of an expression, then this is just a simple "yield" expression.
19555 return finishNode(node);
19556 }
19557 }
19558 function parseSimpleArrowFunctionExpression(identifier, asyncModifier) {
19559 ts.Debug.assert(token() === 37 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
19560 var node;
19561 if (asyncModifier) {
19562 node = createNode(197 /* ArrowFunction */, asyncModifier.pos);
19563 node.modifiers = asyncModifier;
19564 }
19565 else {
19566 node = createNode(197 /* ArrowFunction */, identifier.pos);
19567 }
19568 var parameter = createNode(151 /* Parameter */, identifier.pos);
19569 parameter.name = identifier;
19570 finishNode(parameter);
19571 node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
19572 node.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */);
19573 node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
19574 return addJSDocComment(finishNode(node));
19575 }
19576 function tryParseParenthesizedArrowFunctionExpression() {
19577 var triState = isParenthesizedArrowFunctionExpression();
19578 if (triState === 0 /* False */) {
19579 // It's definitely not a parenthesized arrow function expression.
19580 return undefined;
19581 }
19582 // If we definitely have an arrow function, then we can just parse one, not requiring a
19583 // following => or { token. Otherwise, we *might* have an arrow function. Try to parse
19584 // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
19585 // expression instead.
19586 var arrowFunction = triState === 1 /* True */
19587 ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true)
19588 : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
19589 if (!arrowFunction) {
19590 // Didn't appear to actually be a parenthesized arrow function. Just bail out.
19591 return undefined;
19592 }
19593 var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */);
19594 // If we have an arrow, then try to parse the body. Even if not, try to parse if we
19595 // have an opening brace, just in case we're in an error state.
19596 var lastToken = token();
19597 arrowFunction.equalsGreaterThanToken = parseExpectedToken(37 /* EqualsGreaterThanToken */);
19598 arrowFunction.body = (lastToken === 37 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
19599 ? parseArrowFunctionExpressionBody(isAsync)
19600 : parseIdentifier();
19601 return finishNode(arrowFunction);
19602 }
19603 // True -> We definitely expect a parenthesized arrow function here.
19604 // False -> There *cannot* be a parenthesized arrow function here.
19605 // Unknown -> There *might* be a parenthesized arrow function here.
19606 // Speculatively look ahead to be sure, and rollback if not.
19607 function isParenthesizedArrowFunctionExpression() {
19608 if (token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */ || token() === 121 /* AsyncKeyword */) {
19609 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
19610 }
19611 if (token() === 37 /* EqualsGreaterThanToken */) {
19612 // ERROR RECOVERY TWEAK:
19613 // If we see a standalone => try to parse it as an arrow function expression as that's
19614 // likely what the user intended to write.
19615 return 1 /* True */;
19616 }
19617 // Definitely not a parenthesized arrow function.
19618 return 0 /* False */;
19619 }
19620 function isParenthesizedArrowFunctionExpressionWorker() {
19621 if (token() === 121 /* AsyncKeyword */) {
19622 nextToken();
19623 if (scanner.hasPrecedingLineBreak()) {
19624 return 0 /* False */;
19625 }
19626 if (token() !== 20 /* OpenParenToken */ && token() !== 28 /* LessThanToken */) {
19627 return 0 /* False */;
19628 }
19629 }
19630 var first = token();
19631 var second = nextToken();
19632 if (first === 20 /* OpenParenToken */) {
19633 if (second === 21 /* CloseParenToken */) {
19634 // Simple cases: "() =>", "(): ", and "() {".
19635 // This is an arrow function with no parameters.
19636 // The last one is not actually an arrow function,
19637 // but this is probably what the user intended.
19638 var third = nextToken();
19639 switch (third) {
19640 case 37 /* EqualsGreaterThanToken */:
19641 case 57 /* ColonToken */:
19642 case 18 /* OpenBraceToken */:
19643 return 1 /* True */;
19644 default:
19645 return 0 /* False */;
19646 }
19647 }
19648 // If encounter "([" or "({", this could be the start of a binding pattern.
19649 // Examples:
19650 // ([ x ]) => { }
19651 // ({ x }) => { }
19652 // ([ x ])
19653 // ({ x })
19654 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
19655 return 2 /* Unknown */;
19656 }
19657 // Simple case: "(..."
19658 // This is an arrow function with a rest parameter.
19659 if (second === 25 /* DotDotDotToken */) {
19660 return 1 /* True */;
19661 }
19662 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
19663 // isn't actually allowed, but we want to treat it as a lambda so we can provide
19664 // a good error message.
19665 if (ts.isModifierKind(second) && second !== 121 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
19666 return 1 /* True */;
19667 }
19668 // If we had "(" followed by something that's not an identifier,
19669 // then this definitely doesn't look like a lambda. "this" is not
19670 // valid, but we want to parse it and then give a semantic error.
19671 if (!isIdentifier() && second !== 100 /* ThisKeyword */) {
19672 return 0 /* False */;
19673 }
19674 switch (nextToken()) {
19675 case 57 /* ColonToken */:
19676 // If we have something like "(a:", then we must have a
19677 // type-annotated parameter in an arrow function expression.
19678 return 1 /* True */;
19679 case 56 /* QuestionToken */:
19680 nextToken();
19681 // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
19682 if (token() === 57 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 59 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
19683 return 1 /* True */;
19684 }
19685 // Otherwise it is definitely not a lambda.
19686 return 0 /* False */;
19687 case 27 /* CommaToken */:
19688 case 59 /* EqualsToken */:
19689 case 21 /* CloseParenToken */:
19690 // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
19691 return 2 /* Unknown */;
19692 }
19693 // It is definitely not an arrow function
19694 return 0 /* False */;
19695 }
19696 else {
19697 ts.Debug.assert(first === 28 /* LessThanToken */);
19698 // If we have "<" not followed by an identifier,
19699 // then this definitely is not an arrow function.
19700 if (!isIdentifier()) {
19701 return 0 /* False */;
19702 }
19703 // JSX overrides
19704 if (sourceFile.languageVariant === 1 /* JSX */) {
19705 var isArrowFunctionInJsx = lookAhead(function () {
19706 var third = nextToken();
19707 if (third === 86 /* ExtendsKeyword */) {
19708 var fourth = nextToken();
19709 switch (fourth) {
19710 case 59 /* EqualsToken */:
19711 case 30 /* GreaterThanToken */:
19712 return false;
19713 default:
19714 return true;
19715 }
19716 }
19717 else if (third === 27 /* CommaToken */) {
19718 return true;
19719 }
19720 return false;
19721 });
19722 if (isArrowFunctionInJsx) {
19723 return 1 /* True */;
19724 }
19725 return 0 /* False */;
19726 }
19727 // This *could* be a parenthesized arrow function.
19728 return 2 /* Unknown */;
19729 }
19730 }
19731 function parsePossibleParenthesizedArrowFunctionExpressionHead() {
19732 return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
19733 }
19734 function tryParseAsyncSimpleArrowFunctionExpression() {
19735 // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
19736 if (token() === 121 /* AsyncKeyword */) {
19737 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
19738 var asyncModifier = parseModifiersForArrowFunction();
19739 var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
19740 return parseSimpleArrowFunctionExpression(expr, asyncModifier);
19741 }
19742 }
19743 return undefined;
19744 }
19745 function isUnParenthesizedAsyncArrowFunctionWorker() {
19746 // AsyncArrowFunctionExpression:
19747 // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
19748 // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
19749 if (token() === 121 /* AsyncKeyword */) {
19750 nextToken();
19751 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
19752 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
19753 if (scanner.hasPrecedingLineBreak() || token() === 37 /* EqualsGreaterThanToken */) {
19754 return 0 /* False */;
19755 }
19756 // Check for un-parenthesized AsyncArrowFunction
19757 var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
19758 if (!scanner.hasPrecedingLineBreak() && expr.kind === 72 /* Identifier */ && token() === 37 /* EqualsGreaterThanToken */) {
19759 return 1 /* True */;
19760 }
19761 }
19762 return 0 /* False */;
19763 }
19764 function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
19765 var node = createNodeWithJSDoc(197 /* ArrowFunction */);
19766 node.modifiers = parseModifiersForArrowFunction();
19767 var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
19768 // Arrow functions are never generators.
19769 //
19770 // If we're speculatively parsing a signature for a parenthesized arrow function, then
19771 // we have to have a complete parameter list. Otherwise we might see something like
19772 // a => (b => c)
19773 // And think that "(b =>" was actually a parenthesized arrow function with a missing
19774 // close paren.
19775 if (!fillSignature(57 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
19776 return undefined;
19777 }
19778 // Parsing a signature isn't enough.
19779 // Parenthesized arrow signatures often look like other valid expressions.
19780 // For instance:
19781 // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
19782 // - "(x,y)" is a comma expression parsed as a signature with two parameters.
19783 // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
19784 //
19785 // So we need just a bit of lookahead to ensure that it can only be a signature.
19786 if (!allowAmbiguity && token() !== 37 /* EqualsGreaterThanToken */ && token() !== 18 /* OpenBraceToken */) {
19787 // Returning undefined here will cause our caller to rewind to where we started from.
19788 return undefined;
19789 }
19790 return node;
19791 }
19792 function parseArrowFunctionExpressionBody(isAsync) {
19793 if (token() === 18 /* OpenBraceToken */) {
19794 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
19795 }
19796 if (token() !== 26 /* SemicolonToken */ &&
19797 token() !== 90 /* FunctionKeyword */ &&
19798 token() !== 76 /* ClassKeyword */ &&
19799 isStartOfStatement() &&
19800 !isStartOfExpressionStatement()) {
19801 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
19802 //
19803 // Here we try to recover from a potential error situation in the case where the
19804 // user meant to supply a block. For example, if the user wrote:
19805 //
19806 // a =>
19807 // let v = 0;
19808 // }
19809 //
19810 // they may be missing an open brace. Check to see if that's the case so we can
19811 // try to recover better. If we don't do this, then the next close curly we see may end
19812 // up preemptively closing the containing construct.
19813 //
19814 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
19815 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
19816 }
19817 return isAsync
19818 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
19819 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
19820 }
19821 function parseConditionalExpressionRest(leftOperand) {
19822 // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
19823 var questionToken = parseOptionalToken(56 /* QuestionToken */);
19824 if (!questionToken) {
19825 return leftOperand;
19826 }
19827 // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
19828 // we do not that for the 'whenFalse' part.
19829 var node = createNode(205 /* ConditionalExpression */, leftOperand.pos);
19830 node.condition = leftOperand;
19831 node.questionToken = questionToken;
19832 node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
19833 node.colonToken = parseExpectedToken(57 /* ColonToken */);
19834 node.whenFalse = ts.nodeIsPresent(node.colonToken)
19835 ? parseAssignmentExpressionOrHigher()
19836 : createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(57 /* ColonToken */));
19837 return finishNode(node);
19838 }
19839 function parseBinaryExpressionOrHigher(precedence) {
19840 var leftOperand = parseUnaryExpressionOrHigher();
19841 return parseBinaryExpressionRest(precedence, leftOperand);
19842 }
19843 function isInOrOfKeyword(t) {
19844 return t === 93 /* InKeyword */ || t === 147 /* OfKeyword */;
19845 }
19846 function parseBinaryExpressionRest(precedence, leftOperand) {
19847 while (true) {
19848 // We either have a binary operator here, or we're finished. We call
19849 // reScanGreaterToken so that we merge token sequences like > and = into >=
19850 reScanGreaterToken();
19851 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
19852 // Check the precedence to see if we should "take" this operator
19853 // - For left associative operator (all operator but **), consume the operator,
19854 // recursively call the function below, and parse binaryExpression as a rightOperand
19855 // of the caller if the new precedence of the operator is greater then or equal to the current precedence.
19856 // For example:
19857 // a - b - c;
19858 // ^token; leftOperand = b. Return b to the caller as a rightOperand
19859 // a * b - c
19860 // ^token; leftOperand = b. Return b to the caller as a rightOperand
19861 // a - b * c;
19862 // ^token; leftOperand = b. Return b * c to the caller as a rightOperand
19863 // - For right associative operator (**), consume the operator, recursively call the function
19864 // and parse binaryExpression as a rightOperand of the caller if the new precedence of
19865 // the operator is strictly grater than the current precedence
19866 // For example:
19867 // a ** b ** c;
19868 // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
19869 // a - b ** c;
19870 // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
19871 // a ** b - c
19872 // ^token; leftOperand = b. Return b to the caller as a rightOperand
19873 var consumeCurrentOperator = token() === 41 /* AsteriskAsteriskToken */ ?
19874 newPrecedence >= precedence :
19875 newPrecedence > precedence;
19876 if (!consumeCurrentOperator) {
19877 break;
19878 }
19879 if (token() === 93 /* InKeyword */ && inDisallowInContext()) {
19880 break;
19881 }
19882 if (token() === 119 /* AsKeyword */) {
19883 // Make sure we *do* perform ASI for constructs like this:
19884 // var x = foo
19885 // as (Bar)
19886 // This should be parsed as an initialized variable, followed
19887 // by a function call to 'as' with the argument 'Bar'
19888 if (scanner.hasPrecedingLineBreak()) {
19889 break;
19890 }
19891 else {
19892 nextToken();
19893 leftOperand = makeAsExpression(leftOperand, parseType());
19894 }
19895 }
19896 else {
19897 leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
19898 }
19899 }
19900 return leftOperand;
19901 }
19902 function isBinaryOperator() {
19903 if (inDisallowInContext() && token() === 93 /* InKeyword */) {
19904 return false;
19905 }
19906 return ts.getBinaryOperatorPrecedence(token()) > 0;
19907 }
19908 function makeBinaryExpression(left, operatorToken, right) {
19909 var node = createNode(204 /* BinaryExpression */, left.pos);
19910 node.left = left;
19911 node.operatorToken = operatorToken;
19912 node.right = right;
19913 return finishNode(node);
19914 }
19915 function makeAsExpression(left, right) {
19916 var node = createNode(212 /* AsExpression */, left.pos);
19917 node.expression = left;
19918 node.type = right;
19919 return finishNode(node);
19920 }
19921 function parsePrefixUnaryExpression() {
19922 var node = createNode(202 /* PrefixUnaryExpression */);
19923 node.operator = token();
19924 nextToken();
19925 node.operand = parseSimpleUnaryExpression();
19926 return finishNode(node);
19927 }
19928 function parseDeleteExpression() {
19929 var node = createNode(198 /* DeleteExpression */);
19930 nextToken();
19931 node.expression = parseSimpleUnaryExpression();
19932 return finishNode(node);
19933 }
19934 function parseTypeOfExpression() {
19935 var node = createNode(199 /* TypeOfExpression */);
19936 nextToken();
19937 node.expression = parseSimpleUnaryExpression();
19938 return finishNode(node);
19939 }
19940 function parseVoidExpression() {
19941 var node = createNode(200 /* VoidExpression */);
19942 nextToken();
19943 node.expression = parseSimpleUnaryExpression();
19944 return finishNode(node);
19945 }
19946 function isAwaitExpression() {
19947 if (token() === 122 /* AwaitKeyword */) {
19948 if (inAwaitContext()) {
19949 return true;
19950 }
19951 // here we are using similar heuristics as 'isYieldExpression'
19952 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
19953 }
19954 return false;
19955 }
19956 function parseAwaitExpression() {
19957 var node = createNode(201 /* AwaitExpression */);
19958 nextToken();
19959 node.expression = parseSimpleUnaryExpression();
19960 return finishNode(node);
19961 }
19962 /**
19963 * Parse ES7 exponential expression and await expression
19964 *
19965 * ES7 ExponentiationExpression:
19966 * 1) UnaryExpression[?Yield]
19967 * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
19968 *
19969 */
19970 function parseUnaryExpressionOrHigher() {
19971 /**
19972 * ES7 UpdateExpression:
19973 * 1) LeftHandSideExpression[?Yield]
19974 * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++
19975 * 3) LeftHandSideExpression[?Yield][no LineTerminator here]--
19976 * 4) ++UnaryExpression[?Yield]
19977 * 5) --UnaryExpression[?Yield]
19978 */
19979 if (isUpdateExpression()) {
19980 var updateExpression = parseUpdateExpression();
19981 return token() === 41 /* AsteriskAsteriskToken */ ?
19982 parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
19983 updateExpression;
19984 }
19985 /**
19986 * ES7 UnaryExpression:
19987 * 1) UpdateExpression[?yield]
19988 * 2) delete UpdateExpression[?yield]
19989 * 3) void UpdateExpression[?yield]
19990 * 4) typeof UpdateExpression[?yield]
19991 * 5) + UpdateExpression[?yield]
19992 * 6) - UpdateExpression[?yield]
19993 * 7) ~ UpdateExpression[?yield]
19994 * 8) ! UpdateExpression[?yield]
19995 */
19996 var unaryOperator = token();
19997 var simpleUnaryExpression = parseSimpleUnaryExpression();
19998 if (token() === 41 /* AsteriskAsteriskToken */) {
19999 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
20000 var end = simpleUnaryExpression.end;
20001 if (simpleUnaryExpression.kind === 194 /* TypeAssertionExpression */) {
20002 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);
20003 }
20004 else {
20005 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));
20006 }
20007 }
20008 return simpleUnaryExpression;
20009 }
20010 /**
20011 * Parse ES7 simple-unary expression or higher:
20012 *
20013 * ES7 UnaryExpression:
20014 * 1) UpdateExpression[?yield]
20015 * 2) delete UnaryExpression[?yield]
20016 * 3) void UnaryExpression[?yield]
20017 * 4) typeof UnaryExpression[?yield]
20018 * 5) + UnaryExpression[?yield]
20019 * 6) - UnaryExpression[?yield]
20020 * 7) ~ UnaryExpression[?yield]
20021 * 8) ! UnaryExpression[?yield]
20022 * 9) [+Await] await UnaryExpression[?yield]
20023 */
20024 function parseSimpleUnaryExpression() {
20025 switch (token()) {
20026 case 38 /* PlusToken */:
20027 case 39 /* MinusToken */:
20028 case 53 /* TildeToken */:
20029 case 52 /* ExclamationToken */:
20030 return parsePrefixUnaryExpression();
20031 case 81 /* DeleteKeyword */:
20032 return parseDeleteExpression();
20033 case 104 /* TypeOfKeyword */:
20034 return parseTypeOfExpression();
20035 case 106 /* VoidKeyword */:
20036 return parseVoidExpression();
20037 case 28 /* LessThanToken */:
20038 // This is modified UnaryExpression grammar in TypeScript
20039 // UnaryExpression (modified):
20040 // < type > UnaryExpression
20041 return parseTypeAssertion();
20042 case 122 /* AwaitKeyword */:
20043 if (isAwaitExpression()) {
20044 return parseAwaitExpression();
20045 }
20046 // falls through
20047 default:
20048 return parseUpdateExpression();
20049 }
20050 }
20051 /**
20052 * Check if the current token can possibly be an ES7 increment expression.
20053 *
20054 * ES7 UpdateExpression:
20055 * LeftHandSideExpression[?Yield]
20056 * LeftHandSideExpression[?Yield][no LineTerminator here]++
20057 * LeftHandSideExpression[?Yield][no LineTerminator here]--
20058 * ++LeftHandSideExpression[?Yield]
20059 * --LeftHandSideExpression[?Yield]
20060 */
20061 function isUpdateExpression() {
20062 // This function is called inside parseUnaryExpression to decide
20063 // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
20064 switch (token()) {
20065 case 38 /* PlusToken */:
20066 case 39 /* MinusToken */:
20067 case 53 /* TildeToken */:
20068 case 52 /* ExclamationToken */:
20069 case 81 /* DeleteKeyword */:
20070 case 104 /* TypeOfKeyword */:
20071 case 106 /* VoidKeyword */:
20072 case 122 /* AwaitKeyword */:
20073 return false;
20074 case 28 /* LessThanToken */:
20075 // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
20076 if (sourceFile.languageVariant !== 1 /* JSX */) {
20077 return false;
20078 }
20079 // We are in JSX context and the token is part of JSXElement.
20080 // falls through
20081 default:
20082 return true;
20083 }
20084 }
20085 /**
20086 * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
20087 *
20088 * ES7 UpdateExpression[yield]:
20089 * 1) LeftHandSideExpression[?yield]
20090 * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
20091 * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
20092 * 4) ++LeftHandSideExpression[?yield]
20093 * 5) --LeftHandSideExpression[?yield]
20094 * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
20095 */
20096 function parseUpdateExpression() {
20097 if (token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) {
20098 var node = createNode(202 /* PrefixUnaryExpression */);
20099 node.operator = token();
20100 nextToken();
20101 node.operand = parseLeftHandSideExpressionOrHigher();
20102 return finishNode(node);
20103 }
20104 else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 28 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
20105 // JSXElement is part of primaryExpression
20106 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
20107 }
20108 var expression = parseLeftHandSideExpressionOrHigher();
20109 ts.Debug.assert(ts.isLeftHandSideExpression(expression));
20110 if ((token() === 44 /* PlusPlusToken */ || token() === 45 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
20111 var node = createNode(203 /* PostfixUnaryExpression */, expression.pos);
20112 node.operand = expression;
20113 node.operator = token();
20114 nextToken();
20115 return finishNode(node);
20116 }
20117 return expression;
20118 }
20119 function parseLeftHandSideExpressionOrHigher() {
20120 // Original Ecma:
20121 // LeftHandSideExpression: See 11.2
20122 // NewExpression
20123 // CallExpression
20124 //
20125 // Our simplification:
20126 //
20127 // LeftHandSideExpression: See 11.2
20128 // MemberExpression
20129 // CallExpression
20130 //
20131 // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
20132 // MemberExpression to make our lives easier.
20133 //
20134 // to best understand the below code, it's important to see how CallExpression expands
20135 // out into its own productions:
20136 //
20137 // CallExpression:
20138 // MemberExpression Arguments
20139 // CallExpression Arguments
20140 // CallExpression[Expression]
20141 // CallExpression.IdentifierName
20142 // import (AssignmentExpression)
20143 // super Arguments
20144 // super.IdentifierName
20145 //
20146 // Because of the recursion in these calls, we need to bottom out first. There are three
20147 // bottom out states we can run into: 1) We see 'super' which must start either of
20148 // the last two CallExpression productions. 2) We see 'import' which must start import call.
20149 // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
20150 // or starts the beginning of the first four CallExpression productions.
20151 var expression;
20152 if (token() === 92 /* ImportKeyword */) {
20153 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
20154 // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
20155 // For example:
20156 // var foo3 = require("subfolder
20157 // import * as foo1 from "module-from-node
20158 // We want this import to be a statement rather than import call expression
20159 sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */;
20160 expression = parseTokenNode();
20161 }
20162 else if (lookAhead(nextTokenIsDot)) {
20163 // This is an 'import.*' metaproperty (i.e. 'import.meta')
20164 var fullStart = scanner.getStartPos();
20165 nextToken(); // advance past the 'import'
20166 nextToken(); // advance past the dot
20167 var node = createNode(214 /* MetaProperty */, fullStart);
20168 node.keywordToken = 92 /* ImportKeyword */;
20169 node.name = parseIdentifierName();
20170 expression = finishNode(node);
20171 sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */;
20172 }
20173 else {
20174 expression = parseMemberExpressionOrHigher();
20175 }
20176 }
20177 else {
20178 expression = token() === 98 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
20179 }
20180 // Now, we *may* be complete. However, we might have consumed the start of a
20181 // CallExpression. As such, we need to consume the rest of it here to be complete.
20182 return parseCallExpressionRest(expression);
20183 }
20184 function parseMemberExpressionOrHigher() {
20185 // Note: to make our lives simpler, we decompose the NewExpression productions and
20186 // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
20187 // like so:
20188 //
20189 // PrimaryExpression : See 11.1
20190 // this
20191 // Identifier
20192 // Literal
20193 // ArrayLiteral
20194 // ObjectLiteral
20195 // (Expression)
20196 // FunctionExpression
20197 // new MemberExpression Arguments?
20198 //
20199 // MemberExpression : See 11.2
20200 // PrimaryExpression
20201 // MemberExpression[Expression]
20202 // MemberExpression.IdentifierName
20203 //
20204 // CallExpression : See 11.2
20205 // MemberExpression
20206 // CallExpression Arguments
20207 // CallExpression[Expression]
20208 // CallExpression.IdentifierName
20209 //
20210 // Technically this is ambiguous. i.e. CallExpression defines:
20211 //
20212 // CallExpression:
20213 // CallExpression Arguments
20214 //
20215 // If you see: "new Foo()"
20216 //
20217 // Then that could be treated as a single ObjectCreationExpression, or it could be
20218 // treated as the invocation of "new Foo". We disambiguate that in code (to match
20219 // the original grammar) by making sure that if we see an ObjectCreationExpression
20220 // we always consume arguments if they are there. So we treat "new Foo()" as an
20221 // object creation only, and not at all as an invocation. Another way to think
20222 // about this is that for every "new" that we see, we will consume an argument list if
20223 // it is there as part of the *associated* object creation node. Any additional
20224 // argument lists we see, will become invocation expressions.
20225 //
20226 // Because there are no other places in the grammar now that refer to FunctionExpression
20227 // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
20228 // production.
20229 //
20230 // Because CallExpression and MemberExpression are left recursive, we need to bottom out
20231 // of the recursion immediately. So we parse out a primary expression to start with.
20232 var expression = parsePrimaryExpression();
20233 return parseMemberExpressionRest(expression);
20234 }
20235 function parseSuperExpression() {
20236 var expression = parseTokenNode();
20237 if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
20238 return expression;
20239 }
20240 // If we have seen "super" it must be followed by '(' or '.'.
20241 // If it wasn't then just try to parse out a '.' and report an error.
20242 var node = createNode(189 /* PropertyAccessExpression */, expression.pos);
20243 node.expression = expression;
20244 parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
20245 node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
20246 return finishNode(node);
20247 }
20248 function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
20249 var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
20250 var result;
20251 if (opening.kind === 262 /* JsxOpeningElement */) {
20252 var node = createNode(260 /* JsxElement */, opening.pos);
20253 node.openingElement = opening;
20254 node.children = parseJsxChildren(node.openingElement);
20255 node.closingElement = parseJsxClosingElement(inExpressionContext);
20256 if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
20257 parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName));
20258 }
20259 result = finishNode(node);
20260 }
20261 else if (opening.kind === 265 /* JsxOpeningFragment */) {
20262 var node = createNode(264 /* JsxFragment */, opening.pos);
20263 node.openingFragment = opening;
20264 node.children = parseJsxChildren(node.openingFragment);
20265 node.closingFragment = parseJsxClosingFragment(inExpressionContext);
20266 result = finishNode(node);
20267 }
20268 else {
20269 ts.Debug.assert(opening.kind === 261 /* JsxSelfClosingElement */);
20270 // Nothing else to do for self-closing elements
20271 result = opening;
20272 }
20273 // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
20274 // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag
20275 // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
20276 // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
20277 // does less damage and we can report a better error.
20278 // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
20279 // of one sort or another.
20280 if (inExpressionContext && token() === 28 /* LessThanToken */) {
20281 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
20282 if (invalidElement) {
20283 parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
20284 var badNode = createNode(204 /* BinaryExpression */, result.pos);
20285 badNode.end = invalidElement.end;
20286 badNode.left = result;
20287 badNode.right = invalidElement;
20288 badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217
20289 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
20290 return badNode;
20291 }
20292 }
20293 return result;
20294 }
20295 function parseJsxText() {
20296 var node = createNode(11 /* JsxText */);
20297 node.text = scanner.getTokenValue();
20298 node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
20299 currentToken = scanner.scanJsxToken();
20300 return finishNode(node);
20301 }
20302 function parseJsxChild(openingTag, token) {
20303 switch (token) {
20304 case 1 /* EndOfFileToken */:
20305 // If we hit EOF, issue the error at the tag that lacks the closing element
20306 // rather than at the end of the file (which is useless)
20307 if (ts.isJsxOpeningFragment(openingTag)) {
20308 parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
20309 }
20310 else {
20311 parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
20312 }
20313 return undefined;
20314 case 29 /* LessThanSlashToken */:
20315 case 7 /* ConflictMarkerTrivia */:
20316 return undefined;
20317 case 11 /* JsxText */:
20318 case 12 /* JsxTextAllWhiteSpaces */:
20319 return parseJsxText();
20320 case 18 /* OpenBraceToken */:
20321 return parseJsxExpression(/*inExpressionContext*/ false);
20322 case 28 /* LessThanToken */:
20323 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
20324 default:
20325 return ts.Debug.assertNever(token);
20326 }
20327 }
20328 function parseJsxChildren(openingTag) {
20329 var list = [];
20330 var listPos = getNodePos();
20331 var saveParsingContext = parsingContext;
20332 parsingContext |= 1 << 14 /* JsxChildren */;
20333 while (true) {
20334 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
20335 if (!child)
20336 break;
20337 list.push(child);
20338 }
20339 parsingContext = saveParsingContext;
20340 return createNodeArray(list, listPos);
20341 }
20342 function parseJsxAttributes() {
20343 var jsxAttributes = createNode(268 /* JsxAttributes */);
20344 jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
20345 return finishNode(jsxAttributes);
20346 }
20347 function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
20348 var fullStart = scanner.getStartPos();
20349 parseExpected(28 /* LessThanToken */);
20350 if (token() === 30 /* GreaterThanToken */) {
20351 // See below for explanation of scanJsxText
20352 var node_1 = createNode(265 /* JsxOpeningFragment */, fullStart);
20353 scanJsxText();
20354 return finishNode(node_1);
20355 }
20356 var tagName = parseJsxElementName();
20357 var typeArguments = tryParseTypeArguments();
20358 var attributes = parseJsxAttributes();
20359 var node;
20360 if (token() === 30 /* GreaterThanToken */) {
20361 // Closing tag, so scan the immediately-following text with the JSX scanning instead
20362 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
20363 // scanning errors
20364 node = createNode(262 /* JsxOpeningElement */, fullStart);
20365 scanJsxText();
20366 }
20367 else {
20368 parseExpected(42 /* SlashToken */);
20369 if (inExpressionContext) {
20370 parseExpected(30 /* GreaterThanToken */);
20371 }
20372 else {
20373 parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
20374 scanJsxText();
20375 }
20376 node = createNode(261 /* JsxSelfClosingElement */, fullStart);
20377 }
20378 node.tagName = tagName;
20379 node.typeArguments = typeArguments;
20380 node.attributes = attributes;
20381 return finishNode(node);
20382 }
20383 function parseJsxElementName() {
20384 scanJsxIdentifier();
20385 // JsxElement can have name in the form of
20386 // propertyAccessExpression
20387 // primaryExpression in the form of an identifier and "this" keyword
20388 // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
20389 // We only want to consider "this" as a primaryExpression
20390 var expression = token() === 100 /* ThisKeyword */ ?
20391 parseTokenNode() : parseIdentifierName();
20392 while (parseOptional(24 /* DotToken */)) {
20393 var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos);
20394 propertyAccess.expression = expression;
20395 propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
20396 expression = finishNode(propertyAccess);
20397 }
20398 return expression;
20399 }
20400 function parseJsxExpression(inExpressionContext) {
20401 var node = createNode(270 /* JsxExpression */);
20402 if (!parseExpected(18 /* OpenBraceToken */)) {
20403 return undefined;
20404 }
20405 if (token() !== 19 /* CloseBraceToken */) {
20406 node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
20407 node.expression = parseAssignmentExpressionOrHigher();
20408 }
20409 if (inExpressionContext) {
20410 parseExpected(19 /* CloseBraceToken */);
20411 }
20412 else {
20413 parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false);
20414 scanJsxText();
20415 }
20416 return finishNode(node);
20417 }
20418 function parseJsxAttribute() {
20419 if (token() === 18 /* OpenBraceToken */) {
20420 return parseJsxSpreadAttribute();
20421 }
20422 scanJsxIdentifier();
20423 var node = createNode(267 /* JsxAttribute */);
20424 node.name = parseIdentifierName();
20425 if (token() === 59 /* EqualsToken */) {
20426 switch (scanJsxAttributeValue()) {
20427 case 10 /* StringLiteral */:
20428 node.initializer = parseLiteralNode();
20429 break;
20430 default:
20431 node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
20432 break;
20433 }
20434 }
20435 return finishNode(node);
20436 }
20437 function parseJsxSpreadAttribute() {
20438 var node = createNode(269 /* JsxSpreadAttribute */);
20439 parseExpected(18 /* OpenBraceToken */);
20440 parseExpected(25 /* DotDotDotToken */);
20441 node.expression = parseExpression();
20442 parseExpected(19 /* CloseBraceToken */);
20443 return finishNode(node);
20444 }
20445 function parseJsxClosingElement(inExpressionContext) {
20446 var node = createNode(263 /* JsxClosingElement */);
20447 parseExpected(29 /* LessThanSlashToken */);
20448 node.tagName = parseJsxElementName();
20449 if (inExpressionContext) {
20450 parseExpected(30 /* GreaterThanToken */);
20451 }
20452 else {
20453 parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
20454 scanJsxText();
20455 }
20456 return finishNode(node);
20457 }
20458 function parseJsxClosingFragment(inExpressionContext) {
20459 var node = createNode(266 /* JsxClosingFragment */);
20460 parseExpected(29 /* LessThanSlashToken */);
20461 if (ts.tokenIsIdentifierOrKeyword(token())) {
20462 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
20463 }
20464 if (inExpressionContext) {
20465 parseExpected(30 /* GreaterThanToken */);
20466 }
20467 else {
20468 parseExpected(30 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
20469 scanJsxText();
20470 }
20471 return finishNode(node);
20472 }
20473 function parseTypeAssertion() {
20474 var node = createNode(194 /* TypeAssertionExpression */);
20475 parseExpected(28 /* LessThanToken */);
20476 node.type = parseType();
20477 parseExpected(30 /* GreaterThanToken */);
20478 node.expression = parseSimpleUnaryExpression();
20479 return finishNode(node);
20480 }
20481 function parseMemberExpressionRest(expression) {
20482 while (true) {
20483 var dotToken = parseOptionalToken(24 /* DotToken */);
20484 if (dotToken) {
20485 var propertyAccess = createNode(189 /* PropertyAccessExpression */, expression.pos);
20486 propertyAccess.expression = expression;
20487 propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
20488 expression = finishNode(propertyAccess);
20489 continue;
20490 }
20491 if (token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
20492 nextToken();
20493 var nonNullExpression = createNode(213 /* NonNullExpression */, expression.pos);
20494 nonNullExpression.expression = expression;
20495 expression = finishNode(nonNullExpression);
20496 continue;
20497 }
20498 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
20499 if (!inDecoratorContext() && parseOptional(22 /* OpenBracketToken */)) {
20500 var indexedAccess = createNode(190 /* ElementAccessExpression */, expression.pos);
20501 indexedAccess.expression = expression;
20502 if (token() === 23 /* CloseBracketToken */) {
20503 indexedAccess.argumentExpression = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
20504 }
20505 else {
20506 var argument = allowInAnd(parseExpression);
20507 if (ts.isStringOrNumericLiteralLike(argument)) {
20508 argument.text = internIdentifier(argument.text);
20509 }
20510 indexedAccess.argumentExpression = argument;
20511 }
20512 parseExpected(23 /* CloseBracketToken */);
20513 expression = finishNode(indexedAccess);
20514 continue;
20515 }
20516 if (isTemplateStartOfTaggedTemplate()) {
20517 expression = parseTaggedTemplateRest(expression, /*typeArguments*/ undefined);
20518 continue;
20519 }
20520 return expression;
20521 }
20522 }
20523 function isTemplateStartOfTaggedTemplate() {
20524 return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
20525 }
20526 function parseTaggedTemplateRest(tag, typeArguments) {
20527 var tagExpression = createNode(193 /* TaggedTemplateExpression */, tag.pos);
20528 tagExpression.tag = tag;
20529 tagExpression.typeArguments = typeArguments;
20530 tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */
20531 ? parseLiteralNode()
20532 : parseTemplateExpression();
20533 return finishNode(tagExpression);
20534 }
20535 function parseCallExpressionRest(expression) {
20536 while (true) {
20537 expression = parseMemberExpressionRest(expression);
20538 // handle 'foo<<T>()'
20539 if (token() === 28 /* LessThanToken */ || token() === 46 /* LessThanLessThanToken */) {
20540 // See if this is the start of a generic invocation. If so, consume it and
20541 // keep checking for postfix expressions. Otherwise, it's just a '<' that's
20542 // part of an arithmetic expression. Break out so we consume it higher in the
20543 // stack.
20544 var typeArguments = tryParse(parseTypeArgumentsInExpression);
20545 if (!typeArguments) {
20546 return expression;
20547 }
20548 if (isTemplateStartOfTaggedTemplate()) {
20549 expression = parseTaggedTemplateRest(expression, typeArguments);
20550 continue;
20551 }
20552 var callExpr = createNode(191 /* CallExpression */, expression.pos);
20553 callExpr.expression = expression;
20554 callExpr.typeArguments = typeArguments;
20555 callExpr.arguments = parseArgumentList();
20556 expression = finishNode(callExpr);
20557 continue;
20558 }
20559 else if (token() === 20 /* OpenParenToken */) {
20560 var callExpr = createNode(191 /* CallExpression */, expression.pos);
20561 callExpr.expression = expression;
20562 callExpr.arguments = parseArgumentList();
20563 expression = finishNode(callExpr);
20564 continue;
20565 }
20566 return expression;
20567 }
20568 }
20569 function parseArgumentList() {
20570 parseExpected(20 /* OpenParenToken */);
20571 var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
20572 parseExpected(21 /* CloseParenToken */);
20573 return result;
20574 }
20575 function parseTypeArgumentsInExpression() {
20576 if (reScanLessThanToken() !== 28 /* LessThanToken */) {
20577 return undefined;
20578 }
20579 nextToken();
20580 var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
20581 if (!parseExpected(30 /* GreaterThanToken */)) {
20582 // If it doesn't have the closing `>` then it's definitely not an type argument list.
20583 return undefined;
20584 }
20585 // If we have a '<', then only parse this as a argument list if the type arguments
20586 // are complete and we have an open paren. if we don't, rewind and return nothing.
20587 return typeArguments && canFollowTypeArgumentsInExpression()
20588 ? typeArguments
20589 : undefined;
20590 }
20591 function canFollowTypeArgumentsInExpression() {
20592 switch (token()) {
20593 case 20 /* OpenParenToken */: // foo<x>(
20594 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
20595 case 15 /* TemplateHead */: // foo<T> `...${100}...`
20596 // these are the only tokens can legally follow a type argument
20597 // list. So we definitely want to treat them as type arg lists.
20598 case 24 /* DotToken */: // foo<x>.
20599 case 21 /* CloseParenToken */: // foo<x>)
20600 case 23 /* CloseBracketToken */: // foo<x>]
20601 case 57 /* ColonToken */: // foo<x>:
20602 case 26 /* SemicolonToken */: // foo<x>;
20603 case 56 /* QuestionToken */: // foo<x>?
20604 case 33 /* EqualsEqualsToken */: // foo<x> ==
20605 case 35 /* EqualsEqualsEqualsToken */: // foo<x> ===
20606 case 34 /* ExclamationEqualsToken */: // foo<x> !=
20607 case 36 /* ExclamationEqualsEqualsToken */: // foo<x> !==
20608 case 54 /* AmpersandAmpersandToken */: // foo<x> &&
20609 case 55 /* BarBarToken */: // foo<x> ||
20610 case 51 /* CaretToken */: // foo<x> ^
20611 case 49 /* AmpersandToken */: // foo<x> &
20612 case 50 /* BarToken */: // foo<x> |
20613 case 19 /* CloseBraceToken */: // foo<x> }
20614 case 1 /* EndOfFileToken */: // foo<x>
20615 // these cases can't legally follow a type arg list. However, they're not legal
20616 // expressions either. The user is probably in the middle of a generic type. So
20617 // treat it as such.
20618 return true;
20619 case 27 /* CommaToken */: // foo<x>,
20620 case 18 /* OpenBraceToken */: // foo<x> {
20621 // We don't want to treat these as type arguments. Otherwise we'll parse this
20622 // as an invocation expression. Instead, we want to parse out the expression
20623 // in isolation from the type arguments.
20624 default:
20625 // Anything else treat as an expression.
20626 return false;
20627 }
20628 }
20629 function parsePrimaryExpression() {
20630 switch (token()) {
20631 case 8 /* NumericLiteral */:
20632 case 9 /* BigIntLiteral */:
20633 case 10 /* StringLiteral */:
20634 case 14 /* NoSubstitutionTemplateLiteral */:
20635 return parseLiteralNode();
20636 case 100 /* ThisKeyword */:
20637 case 98 /* SuperKeyword */:
20638 case 96 /* NullKeyword */:
20639 case 102 /* TrueKeyword */:
20640 case 87 /* FalseKeyword */:
20641 return parseTokenNode();
20642 case 20 /* OpenParenToken */:
20643 return parseParenthesizedExpression();
20644 case 22 /* OpenBracketToken */:
20645 return parseArrayLiteralExpression();
20646 case 18 /* OpenBraceToken */:
20647 return parseObjectLiteralExpression();
20648 case 121 /* AsyncKeyword */:
20649 // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
20650 // If we encounter `async [no LineTerminator here] function` then this is an async
20651 // function; otherwise, its an identifier.
20652 if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
20653 break;
20654 }
20655 return parseFunctionExpression();
20656 case 76 /* ClassKeyword */:
20657 return parseClassExpression();
20658 case 90 /* FunctionKeyword */:
20659 return parseFunctionExpression();
20660 case 95 /* NewKeyword */:
20661 return parseNewExpressionOrNewDotTarget();
20662 case 42 /* SlashToken */:
20663 case 64 /* SlashEqualsToken */:
20664 if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
20665 return parseLiteralNode();
20666 }
20667 break;
20668 case 15 /* TemplateHead */:
20669 return parseTemplateExpression();
20670 }
20671 return parseIdentifier(ts.Diagnostics.Expression_expected);
20672 }
20673 function parseParenthesizedExpression() {
20674 var node = createNodeWithJSDoc(195 /* ParenthesizedExpression */);
20675 parseExpected(20 /* OpenParenToken */);
20676 node.expression = allowInAnd(parseExpression);
20677 parseExpected(21 /* CloseParenToken */);
20678 return finishNode(node);
20679 }
20680 function parseSpreadElement() {
20681 var node = createNode(208 /* SpreadElement */);
20682 parseExpected(25 /* DotDotDotToken */);
20683 node.expression = parseAssignmentExpressionOrHigher();
20684 return finishNode(node);
20685 }
20686 function parseArgumentOrArrayLiteralElement() {
20687 return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
20688 token() === 27 /* CommaToken */ ? createNode(210 /* OmittedExpression */) :
20689 parseAssignmentExpressionOrHigher();
20690 }
20691 function parseArgumentExpression() {
20692 return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
20693 }
20694 function parseArrayLiteralExpression() {
20695 var node = createNode(187 /* ArrayLiteralExpression */);
20696 parseExpected(22 /* OpenBracketToken */);
20697 if (scanner.hasPrecedingLineBreak()) {
20698 node.multiLine = true;
20699 }
20700 node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
20701 parseExpected(23 /* CloseBracketToken */);
20702 return finishNode(node);
20703 }
20704 function parseObjectLiteralElement() {
20705 var node = createNodeWithJSDoc(0 /* Unknown */);
20706 if (parseOptionalToken(25 /* DotDotDotToken */)) {
20707 node.kind = 277 /* SpreadAssignment */;
20708 node.expression = parseAssignmentExpressionOrHigher();
20709 return finishNode(node);
20710 }
20711 node.decorators = parseDecorators();
20712 node.modifiers = parseModifiers();
20713 if (parseContextualModifier(126 /* GetKeyword */)) {
20714 return parseAccessorDeclaration(node, 158 /* GetAccessor */);
20715 }
20716 if (parseContextualModifier(137 /* SetKeyword */)) {
20717 return parseAccessorDeclaration(node, 159 /* SetAccessor */);
20718 }
20719 var asteriskToken = parseOptionalToken(40 /* AsteriskToken */);
20720 var tokenIsIdentifier = isIdentifier();
20721 node.name = parsePropertyName();
20722 // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
20723 node.questionToken = parseOptionalToken(56 /* QuestionToken */);
20724 node.exclamationToken = parseOptionalToken(52 /* ExclamationToken */);
20725 if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) {
20726 return parseMethodDeclaration(node, asteriskToken);
20727 }
20728 // check if it is short-hand property assignment or normal property assignment
20729 // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
20730 // CoverInitializedName[Yield] :
20731 // IdentifierReference[?Yield] Initializer[In, ?Yield]
20732 // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
20733 var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 57 /* ColonToken */);
20734 if (isShorthandPropertyAssignment) {
20735 node.kind = 276 /* ShorthandPropertyAssignment */;
20736 var equalsToken = parseOptionalToken(59 /* EqualsToken */);
20737 if (equalsToken) {
20738 node.equalsToken = equalsToken;
20739 node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
20740 }
20741 }
20742 else {
20743 node.kind = 275 /* PropertyAssignment */;
20744 parseExpected(57 /* ColonToken */);
20745 node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
20746 }
20747 return finishNode(node);
20748 }
20749 function parseObjectLiteralExpression() {
20750 var node = createNode(188 /* ObjectLiteralExpression */);
20751 parseExpected(18 /* OpenBraceToken */);
20752 if (scanner.hasPrecedingLineBreak()) {
20753 node.multiLine = true;
20754 }
20755 node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
20756 parseExpected(19 /* CloseBraceToken */);
20757 return finishNode(node);
20758 }
20759 function parseFunctionExpression() {
20760 // GeneratorExpression:
20761 // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
20762 //
20763 // FunctionExpression:
20764 // function BindingIdentifier[opt](FormalParameters){ FunctionBody }
20765 var saveDecoratorContext = inDecoratorContext();
20766 if (saveDecoratorContext) {
20767 setDecoratorContext(/*val*/ false);
20768 }
20769 var node = createNodeWithJSDoc(196 /* FunctionExpression */);
20770 node.modifiers = parseModifiers();
20771 parseExpected(90 /* FunctionKeyword */);
20772 node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */);
20773 var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
20774 var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
20775 node.name =
20776 isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
20777 isGenerator ? doInYieldContext(parseOptionalIdentifier) :
20778 isAsync ? doInAwaitContext(parseOptionalIdentifier) :
20779 parseOptionalIdentifier();
20780 fillSignature(57 /* ColonToken */, isGenerator | isAsync, node);
20781 node.body = parseFunctionBlock(isGenerator | isAsync);
20782 if (saveDecoratorContext) {
20783 setDecoratorContext(/*val*/ true);
20784 }
20785 return finishNode(node);
20786 }
20787 function parseOptionalIdentifier() {
20788 return isIdentifier() ? parseIdentifier() : undefined;
20789 }
20790 function parseNewExpressionOrNewDotTarget() {
20791 var fullStart = scanner.getStartPos();
20792 parseExpected(95 /* NewKeyword */);
20793 if (parseOptional(24 /* DotToken */)) {
20794 var node_2 = createNode(214 /* MetaProperty */, fullStart);
20795 node_2.keywordToken = 95 /* NewKeyword */;
20796 node_2.name = parseIdentifierName();
20797 return finishNode(node_2);
20798 }
20799 var expression = parsePrimaryExpression();
20800 var typeArguments;
20801 while (true) {
20802 expression = parseMemberExpressionRest(expression);
20803 typeArguments = tryParse(parseTypeArgumentsInExpression);
20804 if (isTemplateStartOfTaggedTemplate()) {
20805 ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
20806 expression = parseTaggedTemplateRest(expression, typeArguments);
20807 typeArguments = undefined;
20808 }
20809 break;
20810 }
20811 var node = createNode(192 /* NewExpression */, fullStart);
20812 node.expression = expression;
20813 node.typeArguments = typeArguments;
20814 if (node.typeArguments || token() === 20 /* OpenParenToken */) {
20815 node.arguments = parseArgumentList();
20816 }
20817 return finishNode(node);
20818 }
20819 // STATEMENTS
20820 function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
20821 var node = createNode(218 /* Block */);
20822 if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
20823 if (scanner.hasPrecedingLineBreak()) {
20824 node.multiLine = true;
20825 }
20826 node.statements = parseList(1 /* BlockStatements */, parseStatement);
20827 parseExpected(19 /* CloseBraceToken */);
20828 }
20829 else {
20830 node.statements = createMissingList();
20831 }
20832 return finishNode(node);
20833 }
20834 function parseFunctionBlock(flags, diagnosticMessage) {
20835 var savedYieldContext = inYieldContext();
20836 setYieldContext(!!(flags & 1 /* Yield */));
20837 var savedAwaitContext = inAwaitContext();
20838 setAwaitContext(!!(flags & 2 /* Await */));
20839 // We may be in a [Decorator] context when parsing a function expression or
20840 // arrow function. The body of the function is not in [Decorator] context.
20841 var saveDecoratorContext = inDecoratorContext();
20842 if (saveDecoratorContext) {
20843 setDecoratorContext(/*val*/ false);
20844 }
20845 var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
20846 if (saveDecoratorContext) {
20847 setDecoratorContext(/*val*/ true);
20848 }
20849 setYieldContext(savedYieldContext);
20850 setAwaitContext(savedAwaitContext);
20851 return block;
20852 }
20853 function parseEmptyStatement() {
20854 var node = createNode(220 /* EmptyStatement */);
20855 parseExpected(26 /* SemicolonToken */);
20856 return finishNode(node);
20857 }
20858 function parseIfStatement() {
20859 var node = createNode(222 /* IfStatement */);
20860 parseExpected(91 /* IfKeyword */);
20861 parseExpected(20 /* OpenParenToken */);
20862 node.expression = allowInAnd(parseExpression);
20863 parseExpected(21 /* CloseParenToken */);
20864 node.thenStatement = parseStatement();
20865 node.elseStatement = parseOptional(83 /* ElseKeyword */) ? parseStatement() : undefined;
20866 return finishNode(node);
20867 }
20868 function parseDoStatement() {
20869 var node = createNode(223 /* DoStatement */);
20870 parseExpected(82 /* DoKeyword */);
20871 node.statement = parseStatement();
20872 parseExpected(107 /* WhileKeyword */);
20873 parseExpected(20 /* OpenParenToken */);
20874 node.expression = allowInAnd(parseExpression);
20875 parseExpected(21 /* CloseParenToken */);
20876 // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
20877 // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
20878 // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
20879 // do;while(0)x will have a semicolon inserted before x.
20880 parseOptional(26 /* SemicolonToken */);
20881 return finishNode(node);
20882 }
20883 function parseWhileStatement() {
20884 var node = createNode(224 /* WhileStatement */);
20885 parseExpected(107 /* WhileKeyword */);
20886 parseExpected(20 /* OpenParenToken */);
20887 node.expression = allowInAnd(parseExpression);
20888 parseExpected(21 /* CloseParenToken */);
20889 node.statement = parseStatement();
20890 return finishNode(node);
20891 }
20892 function parseForOrForInOrForOfStatement() {
20893 var pos = getNodePos();
20894 parseExpected(89 /* ForKeyword */);
20895 var awaitToken = parseOptionalToken(122 /* AwaitKeyword */);
20896 parseExpected(20 /* OpenParenToken */);
20897 var initializer;
20898 if (token() !== 26 /* SemicolonToken */) {
20899 if (token() === 105 /* VarKeyword */ || token() === 111 /* LetKeyword */ || token() === 77 /* ConstKeyword */) {
20900 initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
20901 }
20902 else {
20903 initializer = disallowInAnd(parseExpression);
20904 }
20905 }
20906 var forOrForInOrForOfStatement;
20907 if (awaitToken ? parseExpected(147 /* OfKeyword */) : parseOptional(147 /* OfKeyword */)) {
20908 var forOfStatement = createNode(227 /* ForOfStatement */, pos);
20909 forOfStatement.awaitModifier = awaitToken;
20910 forOfStatement.initializer = initializer;
20911 forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
20912 parseExpected(21 /* CloseParenToken */);
20913 forOrForInOrForOfStatement = forOfStatement;
20914 }
20915 else if (parseOptional(93 /* InKeyword */)) {
20916 var forInStatement = createNode(226 /* ForInStatement */, pos);
20917 forInStatement.initializer = initializer;
20918 forInStatement.expression = allowInAnd(parseExpression);
20919 parseExpected(21 /* CloseParenToken */);
20920 forOrForInOrForOfStatement = forInStatement;
20921 }
20922 else {
20923 var forStatement = createNode(225 /* ForStatement */, pos);
20924 forStatement.initializer = initializer;
20925 parseExpected(26 /* SemicolonToken */);
20926 if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) {
20927 forStatement.condition = allowInAnd(parseExpression);
20928 }
20929 parseExpected(26 /* SemicolonToken */);
20930 if (token() !== 21 /* CloseParenToken */) {
20931 forStatement.incrementor = allowInAnd(parseExpression);
20932 }
20933 parseExpected(21 /* CloseParenToken */);
20934 forOrForInOrForOfStatement = forStatement;
20935 }
20936 forOrForInOrForOfStatement.statement = parseStatement();
20937 return finishNode(forOrForInOrForOfStatement);
20938 }
20939 function parseBreakOrContinueStatement(kind) {
20940 var node = createNode(kind);
20941 parseExpected(kind === 229 /* BreakStatement */ ? 73 /* BreakKeyword */ : 78 /* ContinueKeyword */);
20942 if (!canParseSemicolon()) {
20943 node.label = parseIdentifier();
20944 }
20945 parseSemicolon();
20946 return finishNode(node);
20947 }
20948 function parseReturnStatement() {
20949 var node = createNode(230 /* ReturnStatement */);
20950 parseExpected(97 /* ReturnKeyword */);
20951 if (!canParseSemicolon()) {
20952 node.expression = allowInAnd(parseExpression);
20953 }
20954 parseSemicolon();
20955 return finishNode(node);
20956 }
20957 function parseWithStatement() {
20958 var node = createNode(231 /* WithStatement */);
20959 parseExpected(108 /* WithKeyword */);
20960 parseExpected(20 /* OpenParenToken */);
20961 node.expression = allowInAnd(parseExpression);
20962 parseExpected(21 /* CloseParenToken */);
20963 node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement);
20964 return finishNode(node);
20965 }
20966 function parseCaseClause() {
20967 var node = createNode(271 /* CaseClause */);
20968 parseExpected(74 /* CaseKeyword */);
20969 node.expression = allowInAnd(parseExpression);
20970 parseExpected(57 /* ColonToken */);
20971 node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
20972 return finishNode(node);
20973 }
20974 function parseDefaultClause() {
20975 var node = createNode(272 /* DefaultClause */);
20976 parseExpected(80 /* DefaultKeyword */);
20977 parseExpected(57 /* ColonToken */);
20978 node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
20979 return finishNode(node);
20980 }
20981 function parseCaseOrDefaultClause() {
20982 return token() === 74 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
20983 }
20984 function parseSwitchStatement() {
20985 var node = createNode(232 /* SwitchStatement */);
20986 parseExpected(99 /* SwitchKeyword */);
20987 parseExpected(20 /* OpenParenToken */);
20988 node.expression = allowInAnd(parseExpression);
20989 parseExpected(21 /* CloseParenToken */);
20990 var caseBlock = createNode(246 /* CaseBlock */);
20991 parseExpected(18 /* OpenBraceToken */);
20992 caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
20993 parseExpected(19 /* CloseBraceToken */);
20994 node.caseBlock = finishNode(caseBlock);
20995 return finishNode(node);
20996 }
20997 function parseThrowStatement() {
20998 // ThrowStatement[Yield] :
20999 // throw [no LineTerminator here]Expression[In, ?Yield];
21000 // Because of automatic semicolon insertion, we need to report error if this
21001 // throw could be terminated with a semicolon. Note: we can't call 'parseExpression'
21002 // directly as that might consume an expression on the following line.
21003 // We just return 'undefined' in that case. The actual error will be reported in the
21004 // grammar walker.
21005 var node = createNode(234 /* ThrowStatement */);
21006 parseExpected(101 /* ThrowKeyword */);
21007 node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
21008 parseSemicolon();
21009 return finishNode(node);
21010 }
21011 // TODO: Review for error recovery
21012 function parseTryStatement() {
21013 var node = createNode(235 /* TryStatement */);
21014 parseExpected(103 /* TryKeyword */);
21015 node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
21016 node.catchClause = token() === 75 /* CatchKeyword */ ? parseCatchClause() : undefined;
21017 // If we don't have a catch clause, then we must have a finally clause. Try to parse
21018 // one out no matter what.
21019 if (!node.catchClause || token() === 88 /* FinallyKeyword */) {
21020 parseExpected(88 /* FinallyKeyword */);
21021 node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
21022 }
21023 return finishNode(node);
21024 }
21025 function parseCatchClause() {
21026 var result = createNode(274 /* CatchClause */);
21027 parseExpected(75 /* CatchKeyword */);
21028 if (parseOptional(20 /* OpenParenToken */)) {
21029 result.variableDeclaration = parseVariableDeclaration();
21030 parseExpected(21 /* CloseParenToken */);
21031 }
21032 else {
21033 // Keep shape of node to avoid degrading performance.
21034 result.variableDeclaration = undefined;
21035 }
21036 result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
21037 return finishNode(result);
21038 }
21039 function parseDebuggerStatement() {
21040 var node = createNode(236 /* DebuggerStatement */);
21041 parseExpected(79 /* DebuggerKeyword */);
21042 parseSemicolon();
21043 return finishNode(node);
21044 }
21045 function parseExpressionOrLabeledStatement() {
21046 // Avoiding having to do the lookahead for a labeled statement by just trying to parse
21047 // out an expression, seeing if it is identifier and then seeing if it is followed by
21048 // a colon.
21049 var node = createNodeWithJSDoc(0 /* Unknown */);
21050 var expression = allowInAnd(parseExpression);
21051 if (expression.kind === 72 /* Identifier */ && parseOptional(57 /* ColonToken */)) {
21052 node.kind = 233 /* LabeledStatement */;
21053 node.label = expression;
21054 node.statement = parseStatement();
21055 }
21056 else {
21057 node.kind = 221 /* ExpressionStatement */;
21058 node.expression = expression;
21059 parseSemicolon();
21060 }
21061 return finishNode(node);
21062 }
21063 function nextTokenIsIdentifierOrKeywordOnSameLine() {
21064 nextToken();
21065 return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
21066 }
21067 function nextTokenIsClassKeywordOnSameLine() {
21068 nextToken();
21069 return token() === 76 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
21070 }
21071 function nextTokenIsFunctionKeywordOnSameLine() {
21072 nextToken();
21073 return token() === 90 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
21074 }
21075 function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
21076 nextToken();
21077 return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
21078 }
21079 function isDeclaration() {
21080 while (true) {
21081 switch (token()) {
21082 case 105 /* VarKeyword */:
21083 case 111 /* LetKeyword */:
21084 case 77 /* ConstKeyword */:
21085 case 90 /* FunctionKeyword */:
21086 case 76 /* ClassKeyword */:
21087 case 84 /* EnumKeyword */:
21088 return true;
21089 // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
21090 // however, an identifier cannot be followed by another identifier on the same line. This is what we
21091 // count on to parse out the respective declarations. For instance, we exploit this to say that
21092 //
21093 // namespace n
21094 //
21095 // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
21096 //
21097 // namespace
21098 // n
21099 //
21100 // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
21101 // We need to look one token ahead to see if it permissible to try parsing a declaration.
21102 //
21103 // *Note*: 'interface' is actually a strict mode reserved word. So while
21104 //
21105 // "use strict"
21106 // interface
21107 // I {}
21108 //
21109 // could be legal, it would add complexity for very little gain.
21110 case 110 /* InterfaceKeyword */:
21111 case 140 /* TypeKeyword */:
21112 return nextTokenIsIdentifierOnSameLine();
21113 case 130 /* ModuleKeyword */:
21114 case 131 /* NamespaceKeyword */:
21115 return nextTokenIsIdentifierOrStringLiteralOnSameLine();
21116 case 118 /* AbstractKeyword */:
21117 case 121 /* AsyncKeyword */:
21118 case 125 /* DeclareKeyword */:
21119 case 113 /* PrivateKeyword */:
21120 case 114 /* ProtectedKeyword */:
21121 case 115 /* PublicKeyword */:
21122 case 133 /* ReadonlyKeyword */:
21123 nextToken();
21124 // ASI takes effect for this modifier.
21125 if (scanner.hasPrecedingLineBreak()) {
21126 return false;
21127 }
21128 continue;
21129 case 145 /* GlobalKeyword */:
21130 nextToken();
21131 return token() === 18 /* OpenBraceToken */ || token() === 72 /* Identifier */ || token() === 85 /* ExportKeyword */;
21132 case 92 /* ImportKeyword */:
21133 nextToken();
21134 return token() === 10 /* StringLiteral */ || token() === 40 /* AsteriskToken */ ||
21135 token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
21136 case 85 /* ExportKeyword */:
21137 nextToken();
21138 if (token() === 59 /* EqualsToken */ || token() === 40 /* AsteriskToken */ ||
21139 token() === 18 /* OpenBraceToken */ || token() === 80 /* DefaultKeyword */ ||
21140 token() === 119 /* AsKeyword */) {
21141 return true;
21142 }
21143 continue;
21144 case 116 /* StaticKeyword */:
21145 nextToken();
21146 continue;
21147 default:
21148 return false;
21149 }
21150 }
21151 }
21152 function isStartOfDeclaration() {
21153 return lookAhead(isDeclaration);
21154 }
21155 function isStartOfStatement() {
21156 switch (token()) {
21157 case 58 /* AtToken */:
21158 case 26 /* SemicolonToken */:
21159 case 18 /* OpenBraceToken */:
21160 case 105 /* VarKeyword */:
21161 case 111 /* LetKeyword */:
21162 case 90 /* FunctionKeyword */:
21163 case 76 /* ClassKeyword */:
21164 case 84 /* EnumKeyword */:
21165 case 91 /* IfKeyword */:
21166 case 82 /* DoKeyword */:
21167 case 107 /* WhileKeyword */:
21168 case 89 /* ForKeyword */:
21169 case 78 /* ContinueKeyword */:
21170 case 73 /* BreakKeyword */:
21171 case 97 /* ReturnKeyword */:
21172 case 108 /* WithKeyword */:
21173 case 99 /* SwitchKeyword */:
21174 case 101 /* ThrowKeyword */:
21175 case 103 /* TryKeyword */:
21176 case 79 /* DebuggerKeyword */:
21177 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
21178 // however, we say they are here so that we may gracefully parse them and error later.
21179 case 75 /* CatchKeyword */:
21180 case 88 /* FinallyKeyword */:
21181 return true;
21182 case 92 /* ImportKeyword */:
21183 return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
21184 case 77 /* ConstKeyword */:
21185 case 85 /* ExportKeyword */:
21186 return isStartOfDeclaration();
21187 case 121 /* AsyncKeyword */:
21188 case 125 /* DeclareKeyword */:
21189 case 110 /* InterfaceKeyword */:
21190 case 130 /* ModuleKeyword */:
21191 case 131 /* NamespaceKeyword */:
21192 case 140 /* TypeKeyword */:
21193 case 145 /* GlobalKeyword */:
21194 // When these don't start a declaration, they're an identifier in an expression statement
21195 return true;
21196 case 115 /* PublicKeyword */:
21197 case 113 /* PrivateKeyword */:
21198 case 114 /* ProtectedKeyword */:
21199 case 116 /* StaticKeyword */:
21200 case 133 /* ReadonlyKeyword */:
21201 // When these don't start a declaration, they may be the start of a class member if an identifier
21202 // immediately follows. Otherwise they're an identifier in an expression statement.
21203 return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
21204 default:
21205 return isStartOfExpression();
21206 }
21207 }
21208 function nextTokenIsIdentifierOrStartOfDestructuring() {
21209 nextToken();
21210 return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
21211 }
21212 function isLetDeclaration() {
21213 // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
21214 // or [.
21215 return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
21216 }
21217 function parseStatement() {
21218 switch (token()) {
21219 case 26 /* SemicolonToken */:
21220 return parseEmptyStatement();
21221 case 18 /* OpenBraceToken */:
21222 return parseBlock(/*ignoreMissingOpenBrace*/ false);
21223 case 105 /* VarKeyword */:
21224 return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */));
21225 case 111 /* LetKeyword */:
21226 if (isLetDeclaration()) {
21227 return parseVariableStatement(createNodeWithJSDoc(237 /* VariableDeclaration */));
21228 }
21229 break;
21230 case 90 /* FunctionKeyword */:
21231 return parseFunctionDeclaration(createNodeWithJSDoc(239 /* FunctionDeclaration */));
21232 case 76 /* ClassKeyword */:
21233 return parseClassDeclaration(createNodeWithJSDoc(240 /* ClassDeclaration */));
21234 case 91 /* IfKeyword */:
21235 return parseIfStatement();
21236 case 82 /* DoKeyword */:
21237 return parseDoStatement();
21238 case 107 /* WhileKeyword */:
21239 return parseWhileStatement();
21240 case 89 /* ForKeyword */:
21241 return parseForOrForInOrForOfStatement();
21242 case 78 /* ContinueKeyword */:
21243 return parseBreakOrContinueStatement(228 /* ContinueStatement */);
21244 case 73 /* BreakKeyword */:
21245 return parseBreakOrContinueStatement(229 /* BreakStatement */);
21246 case 97 /* ReturnKeyword */:
21247 return parseReturnStatement();
21248 case 108 /* WithKeyword */:
21249 return parseWithStatement();
21250 case 99 /* SwitchKeyword */:
21251 return parseSwitchStatement();
21252 case 101 /* ThrowKeyword */:
21253 return parseThrowStatement();
21254 case 103 /* TryKeyword */:
21255 // Include 'catch' and 'finally' for error recovery.
21256 case 75 /* CatchKeyword */:
21257 case 88 /* FinallyKeyword */:
21258 return parseTryStatement();
21259 case 79 /* DebuggerKeyword */:
21260 return parseDebuggerStatement();
21261 case 58 /* AtToken */:
21262 return parseDeclaration();
21263 case 121 /* AsyncKeyword */:
21264 case 110 /* InterfaceKeyword */:
21265 case 140 /* TypeKeyword */:
21266 case 130 /* ModuleKeyword */:
21267 case 131 /* NamespaceKeyword */:
21268 case 125 /* DeclareKeyword */:
21269 case 77 /* ConstKeyword */:
21270 case 84 /* EnumKeyword */:
21271 case 85 /* ExportKeyword */:
21272 case 92 /* ImportKeyword */:
21273 case 113 /* PrivateKeyword */:
21274 case 114 /* ProtectedKeyword */:
21275 case 115 /* PublicKeyword */:
21276 case 118 /* AbstractKeyword */:
21277 case 116 /* StaticKeyword */:
21278 case 133 /* ReadonlyKeyword */:
21279 case 145 /* GlobalKeyword */:
21280 if (isStartOfDeclaration()) {
21281 return parseDeclaration();
21282 }
21283 break;
21284 }
21285 return parseExpressionOrLabeledStatement();
21286 }
21287 function isDeclareModifier(modifier) {
21288 return modifier.kind === 125 /* DeclareKeyword */;
21289 }
21290 function parseDeclaration() {
21291 var node = createNodeWithJSDoc(0 /* Unknown */);
21292 node.decorators = parseDecorators();
21293 node.modifiers = parseModifiers();
21294 if (ts.some(node.modifiers, isDeclareModifier)) {
21295 for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
21296 var m = _a[_i];
21297 m.flags |= 4194304 /* Ambient */;
21298 }
21299 return doInsideOfContext(4194304 /* Ambient */, function () { return parseDeclarationWorker(node); });
21300 }
21301 else {
21302 return parseDeclarationWorker(node);
21303 }
21304 }
21305 function parseDeclarationWorker(node) {
21306 switch (token()) {
21307 case 105 /* VarKeyword */:
21308 case 111 /* LetKeyword */:
21309 case 77 /* ConstKeyword */:
21310 return parseVariableStatement(node);
21311 case 90 /* FunctionKeyword */:
21312 return parseFunctionDeclaration(node);
21313 case 76 /* ClassKeyword */:
21314 return parseClassDeclaration(node);
21315 case 110 /* InterfaceKeyword */:
21316 return parseInterfaceDeclaration(node);
21317 case 140 /* TypeKeyword */:
21318 return parseTypeAliasDeclaration(node);
21319 case 84 /* EnumKeyword */:
21320 return parseEnumDeclaration(node);
21321 case 145 /* GlobalKeyword */:
21322 case 130 /* ModuleKeyword */:
21323 case 131 /* NamespaceKeyword */:
21324 return parseModuleDeclaration(node);
21325 case 92 /* ImportKeyword */:
21326 return parseImportDeclarationOrImportEqualsDeclaration(node);
21327 case 85 /* ExportKeyword */:
21328 nextToken();
21329 switch (token()) {
21330 case 80 /* DefaultKeyword */:
21331 case 59 /* EqualsToken */:
21332 return parseExportAssignment(node);
21333 case 119 /* AsKeyword */:
21334 return parseNamespaceExportDeclaration(node);
21335 default:
21336 return parseExportDeclaration(node);
21337 }
21338 default:
21339 if (node.decorators || node.modifiers) {
21340 // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
21341 // would follow. For recovery and error reporting purposes, return an incomplete declaration.
21342 var missing = createMissingNode(258 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
21343 missing.pos = node.pos;
21344 missing.decorators = node.decorators;
21345 missing.modifiers = node.modifiers;
21346 return finishNode(missing);
21347 }
21348 return undefined; // TODO: GH#18217
21349 }
21350 }
21351 function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
21352 nextToken();
21353 return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
21354 }
21355 function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
21356 if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
21357 parseSemicolon();
21358 return;
21359 }
21360 return parseFunctionBlock(flags, diagnosticMessage);
21361 }
21362 // DECLARATIONS
21363 function parseArrayBindingElement() {
21364 if (token() === 27 /* CommaToken */) {
21365 return createNode(210 /* OmittedExpression */);
21366 }
21367 var node = createNode(186 /* BindingElement */);
21368 node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
21369 node.name = parseIdentifierOrPattern();
21370 node.initializer = parseInitializer();
21371 return finishNode(node);
21372 }
21373 function parseObjectBindingElement() {
21374 var node = createNode(186 /* BindingElement */);
21375 node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
21376 var tokenIsIdentifier = isIdentifier();
21377 var propertyName = parsePropertyName();
21378 if (tokenIsIdentifier && token() !== 57 /* ColonToken */) {
21379 node.name = propertyName;
21380 }
21381 else {
21382 parseExpected(57 /* ColonToken */);
21383 node.propertyName = propertyName;
21384 node.name = parseIdentifierOrPattern();
21385 }
21386 node.initializer = parseInitializer();
21387 return finishNode(node);
21388 }
21389 function parseObjectBindingPattern() {
21390 var node = createNode(184 /* ObjectBindingPattern */);
21391 parseExpected(18 /* OpenBraceToken */);
21392 node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
21393 parseExpected(19 /* CloseBraceToken */);
21394 return finishNode(node);
21395 }
21396 function parseArrayBindingPattern() {
21397 var node = createNode(185 /* ArrayBindingPattern */);
21398 parseExpected(22 /* OpenBracketToken */);
21399 node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
21400 parseExpected(23 /* CloseBracketToken */);
21401 return finishNode(node);
21402 }
21403 function isIdentifierOrPattern() {
21404 return token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */ || isIdentifier();
21405 }
21406 function parseIdentifierOrPattern() {
21407 if (token() === 22 /* OpenBracketToken */) {
21408 return parseArrayBindingPattern();
21409 }
21410 if (token() === 18 /* OpenBraceToken */) {
21411 return parseObjectBindingPattern();
21412 }
21413 return parseIdentifier();
21414 }
21415 function parseVariableDeclarationAllowExclamation() {
21416 return parseVariableDeclaration(/*allowExclamation*/ true);
21417 }
21418 function parseVariableDeclaration(allowExclamation) {
21419 var node = createNode(237 /* VariableDeclaration */);
21420 node.name = parseIdentifierOrPattern();
21421 if (allowExclamation && node.name.kind === 72 /* Identifier */ &&
21422 token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
21423 node.exclamationToken = parseTokenNode();
21424 }
21425 node.type = parseTypeAnnotation();
21426 if (!isInOrOfKeyword(token())) {
21427 node.initializer = parseInitializer();
21428 }
21429 return finishNode(node);
21430 }
21431 function parseVariableDeclarationList(inForStatementInitializer) {
21432 var node = createNode(238 /* VariableDeclarationList */);
21433 switch (token()) {
21434 case 105 /* VarKeyword */:
21435 break;
21436 case 111 /* LetKeyword */:
21437 node.flags |= 1 /* Let */;
21438 break;
21439 case 77 /* ConstKeyword */:
21440 node.flags |= 2 /* Const */;
21441 break;
21442 default:
21443 ts.Debug.fail();
21444 }
21445 nextToken();
21446 // The user may have written the following:
21447 //
21448 // for (let of X) { }
21449 //
21450 // In this case, we want to parse an empty declaration list, and then parse 'of'
21451 // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
21452 // So we need to look ahead to determine if 'of' should be treated as a keyword in
21453 // this context.
21454 // The checker will then give an error that there is an empty declaration list.
21455 if (token() === 147 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
21456 node.declarations = createMissingList();
21457 }
21458 else {
21459 var savedDisallowIn = inDisallowInContext();
21460 setDisallowInContext(inForStatementInitializer);
21461 node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
21462 setDisallowInContext(savedDisallowIn);
21463 }
21464 return finishNode(node);
21465 }
21466 function canFollowContextualOfKeyword() {
21467 return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
21468 }
21469 function parseVariableStatement(node) {
21470 node.kind = 219 /* VariableStatement */;
21471 node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
21472 parseSemicolon();
21473 return finishNode(node);
21474 }
21475 function parseFunctionDeclaration(node) {
21476 node.kind = 239 /* FunctionDeclaration */;
21477 parseExpected(90 /* FunctionKeyword */);
21478 node.asteriskToken = parseOptionalToken(40 /* AsteriskToken */);
21479 node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier();
21480 var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
21481 var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
21482 fillSignature(57 /* ColonToken */, isGenerator | isAsync, node);
21483 node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
21484 return finishNode(node);
21485 }
21486 function parseConstructorDeclaration(node) {
21487 node.kind = 157 /* Constructor */;
21488 parseExpected(124 /* ConstructorKeyword */);
21489 fillSignature(57 /* ColonToken */, 0 /* None */, node);
21490 node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
21491 return finishNode(node);
21492 }
21493 function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
21494 node.kind = 156 /* MethodDeclaration */;
21495 node.asteriskToken = asteriskToken;
21496 var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
21497 var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
21498 fillSignature(57 /* ColonToken */, isGenerator | isAsync, node);
21499 node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
21500 return finishNode(node);
21501 }
21502 function parsePropertyDeclaration(node) {
21503 node.kind = 154 /* PropertyDeclaration */;
21504 if (!node.questionToken && token() === 52 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
21505 node.exclamationToken = parseTokenNode();
21506 }
21507 node.type = parseTypeAnnotation();
21508 // For instance properties specifically, since they are evaluated inside the constructor,
21509 // we do *not * want to parse yield expressions, so we specifically turn the yield context
21510 // off. The grammar would look something like this:
21511 //
21512 // MemberVariableDeclaration[Yield]:
21513 // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In];
21514 // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield];
21515 //
21516 // The checker may still error in the static case to explicitly disallow the yield expression.
21517 node.initializer = ts.hasModifier(node, 32 /* Static */)
21518 ? allowInAnd(parseInitializer)
21519 : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer);
21520 parseSemicolon();
21521 return finishNode(node);
21522 }
21523 function parsePropertyOrMethodDeclaration(node) {
21524 var asteriskToken = parseOptionalToken(40 /* AsteriskToken */);
21525 node.name = parsePropertyName();
21526 // Note: this is not legal as per the grammar. But we allow it in the parser and
21527 // report an error in the grammar checker.
21528 node.questionToken = parseOptionalToken(56 /* QuestionToken */);
21529 if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 28 /* LessThanToken */) {
21530 return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
21531 }
21532 return parsePropertyDeclaration(node);
21533 }
21534 function parseAccessorDeclaration(node, kind) {
21535 node.kind = kind;
21536 node.name = parsePropertyName();
21537 fillSignature(57 /* ColonToken */, 0 /* None */, node);
21538 node.body = parseFunctionBlockOrSemicolon(0 /* None */);
21539 return finishNode(node);
21540 }
21541 function isClassMemberStart() {
21542 var idToken;
21543 if (token() === 58 /* AtToken */) {
21544 return true;
21545 }
21546 // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
21547 while (ts.isModifierKind(token())) {
21548 idToken = token();
21549 // If the idToken is a class modifier (protected, private, public, and static), it is
21550 // certain that we are starting to parse class member. This allows better error recovery
21551 // Example:
21552 // public foo() ... // true
21553 // public @dec blah ... // true; we will then report an error later
21554 // export public ... // true; we will then report an error later
21555 if (ts.isClassMemberModifier(idToken)) {
21556 return true;
21557 }
21558 nextToken();
21559 }
21560 if (token() === 40 /* AsteriskToken */) {
21561 return true;
21562 }
21563 // Try to get the first property-like token following all modifiers.
21564 // This can either be an identifier or the 'get' or 'set' keywords.
21565 if (isLiteralPropertyName()) {
21566 idToken = token();
21567 nextToken();
21568 }
21569 // Index signatures and computed properties are class members; we can parse.
21570 if (token() === 22 /* OpenBracketToken */) {
21571 return true;
21572 }
21573 // If we were able to get any potential identifier...
21574 if (idToken !== undefined) {
21575 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
21576 if (!ts.isKeyword(idToken) || idToken === 137 /* SetKeyword */ || idToken === 126 /* GetKeyword */) {
21577 return true;
21578 }
21579 // If it *is* a keyword, but not an accessor, check a little farther along
21580 // to see if it should actually be parsed as a class member.
21581 switch (token()) {
21582 case 20 /* OpenParenToken */: // Method declaration
21583 case 28 /* LessThanToken */: // Generic Method declaration
21584 case 52 /* ExclamationToken */: // Non-null assertion on property name
21585 case 57 /* ColonToken */: // Type Annotation for declaration
21586 case 59 /* EqualsToken */: // Initializer for declaration
21587 case 56 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
21588 return true;
21589 default:
21590 // Covers
21591 // - Semicolons (declaration termination)
21592 // - Closing braces (end-of-class, must be declaration)
21593 // - End-of-files (not valid, but permitted so that it gets caught later on)
21594 // - Line-breaks (enabling *automatic semicolon insertion*)
21595 return canParseSemicolon();
21596 }
21597 }
21598 return false;
21599 }
21600 function parseDecorators() {
21601 var list;
21602 var listPos = getNodePos();
21603 while (true) {
21604 var decoratorStart = getNodePos();
21605 if (!parseOptional(58 /* AtToken */)) {
21606 break;
21607 }
21608 var decorator = createNode(152 /* Decorator */, decoratorStart);
21609 decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
21610 finishNode(decorator);
21611 (list || (list = [])).push(decorator);
21612 }
21613 return list && createNodeArray(list, listPos);
21614 }
21615 /*
21616 * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
21617 * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
21618 * and turns it into a standalone declaration), then it is better to parse it and report an error later.
21619 *
21620 * In such situations, 'permitInvalidConstAsModifier' should be set to true.
21621 */
21622 function parseModifiers(permitInvalidConstAsModifier) {
21623 var list;
21624 var listPos = getNodePos();
21625 while (true) {
21626 var modifierStart = scanner.getStartPos();
21627 var modifierKind = token();
21628 if (token() === 77 /* ConstKeyword */ && permitInvalidConstAsModifier) {
21629 // We need to ensure that any subsequent modifiers appear on the same line
21630 // so that when 'const' is a standalone declaration, we don't issue an error.
21631 if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
21632 break;
21633 }
21634 }
21635 else {
21636 if (!parseAnyContextualModifier()) {
21637 break;
21638 }
21639 }
21640 var modifier = finishNode(createNode(modifierKind, modifierStart));
21641 (list || (list = [])).push(modifier);
21642 }
21643 return list && createNodeArray(list, listPos);
21644 }
21645 function parseModifiersForArrowFunction() {
21646 var modifiers;
21647 if (token() === 121 /* AsyncKeyword */) {
21648 var modifierStart = scanner.getStartPos();
21649 var modifierKind = token();
21650 nextToken();
21651 var modifier = finishNode(createNode(modifierKind, modifierStart));
21652 modifiers = createNodeArray([modifier], modifierStart);
21653 }
21654 return modifiers;
21655 }
21656 function parseClassElement() {
21657 if (token() === 26 /* SemicolonToken */) {
21658 var result = createNode(217 /* SemicolonClassElement */);
21659 nextToken();
21660 return finishNode(result);
21661 }
21662 var node = createNodeWithJSDoc(0 /* Unknown */);
21663 node.decorators = parseDecorators();
21664 node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
21665 if (parseContextualModifier(126 /* GetKeyword */)) {
21666 return parseAccessorDeclaration(node, 158 /* GetAccessor */);
21667 }
21668 if (parseContextualModifier(137 /* SetKeyword */)) {
21669 return parseAccessorDeclaration(node, 159 /* SetAccessor */);
21670 }
21671 if (token() === 124 /* ConstructorKeyword */) {
21672 return parseConstructorDeclaration(node);
21673 }
21674 if (isIndexSignature()) {
21675 return parseIndexSignatureDeclaration(node);
21676 }
21677 // It is very important that we check this *after* checking indexers because
21678 // the [ token can start an index signature or a computed property name
21679 if (ts.tokenIsIdentifierOrKeyword(token()) ||
21680 token() === 10 /* StringLiteral */ ||
21681 token() === 8 /* NumericLiteral */ ||
21682 token() === 40 /* AsteriskToken */ ||
21683 token() === 22 /* OpenBracketToken */) {
21684 return parsePropertyOrMethodDeclaration(node);
21685 }
21686 if (node.decorators || node.modifiers) {
21687 // treat this as a property declaration with a missing name.
21688 node.name = createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
21689 return parsePropertyDeclaration(node);
21690 }
21691 // 'isClassMemberStart' should have hinted not to attempt parsing.
21692 return ts.Debug.fail("Should not have attempted to parse class member declaration.");
21693 }
21694 function parseClassExpression() {
21695 return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 209 /* ClassExpression */);
21696 }
21697 function parseClassDeclaration(node) {
21698 return parseClassDeclarationOrExpression(node, 240 /* ClassDeclaration */);
21699 }
21700 function parseClassDeclarationOrExpression(node, kind) {
21701 node.kind = kind;
21702 parseExpected(76 /* ClassKeyword */);
21703 node.name = parseNameOfClassDeclarationOrExpression();
21704 node.typeParameters = parseTypeParameters();
21705 node.heritageClauses = parseHeritageClauses();
21706 if (parseExpected(18 /* OpenBraceToken */)) {
21707 // ClassTail[Yield,Await] : (Modified) See 14.5
21708 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
21709 node.members = parseClassMembers();
21710 parseExpected(19 /* CloseBraceToken */);
21711 }
21712 else {
21713 node.members = createMissingList();
21714 }
21715 return finishNode(node);
21716 }
21717 function parseNameOfClassDeclarationOrExpression() {
21718 // implements is a future reserved word so
21719 // 'class implements' might mean either
21720 // - class expression with omitted name, 'implements' starts heritage clause
21721 // - class with name 'implements'
21722 // 'isImplementsClause' helps to disambiguate between these two cases
21723 return isIdentifier() && !isImplementsClause()
21724 ? parseIdentifier()
21725 : undefined;
21726 }
21727 function isImplementsClause() {
21728 return token() === 109 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
21729 }
21730 function parseHeritageClauses() {
21731 // ClassTail[Yield,Await] : (Modified) See 14.5
21732 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
21733 if (isHeritageClause()) {
21734 return parseList(22 /* HeritageClauses */, parseHeritageClause);
21735 }
21736 return undefined;
21737 }
21738 function parseHeritageClause() {
21739 var tok = token();
21740 ts.Debug.assert(tok === 86 /* ExtendsKeyword */ || tok === 109 /* ImplementsKeyword */); // isListElement() should ensure this.
21741 var node = createNode(273 /* HeritageClause */);
21742 node.token = tok;
21743 nextToken();
21744 node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
21745 return finishNode(node);
21746 }
21747 function parseExpressionWithTypeArguments() {
21748 var node = createNode(211 /* ExpressionWithTypeArguments */);
21749 node.expression = parseLeftHandSideExpressionOrHigher();
21750 node.typeArguments = tryParseTypeArguments();
21751 return finishNode(node);
21752 }
21753 function tryParseTypeArguments() {
21754 return token() === 28 /* LessThanToken */
21755 ? parseBracketedList(20 /* TypeArguments */, parseType, 28 /* LessThanToken */, 30 /* GreaterThanToken */)
21756 : undefined;
21757 }
21758 function isHeritageClause() {
21759 return token() === 86 /* ExtendsKeyword */ || token() === 109 /* ImplementsKeyword */;
21760 }
21761 function parseClassMembers() {
21762 return parseList(5 /* ClassMembers */, parseClassElement);
21763 }
21764 function parseInterfaceDeclaration(node) {
21765 node.kind = 241 /* InterfaceDeclaration */;
21766 parseExpected(110 /* InterfaceKeyword */);
21767 node.name = parseIdentifier();
21768 node.typeParameters = parseTypeParameters();
21769 node.heritageClauses = parseHeritageClauses();
21770 node.members = parseObjectTypeMembers();
21771 return finishNode(node);
21772 }
21773 function parseTypeAliasDeclaration(node) {
21774 node.kind = 242 /* TypeAliasDeclaration */;
21775 parseExpected(140 /* TypeKeyword */);
21776 node.name = parseIdentifier();
21777 node.typeParameters = parseTypeParameters();
21778 parseExpected(59 /* EqualsToken */);
21779 node.type = parseType();
21780 parseSemicolon();
21781 return finishNode(node);
21782 }
21783 // In an ambient declaration, the grammar only allows integer literals as initializers.
21784 // In a non-ambient declaration, the grammar allows uninitialized members only in a
21785 // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
21786 // or any time an integer literal initializer is encountered.
21787 function parseEnumMember() {
21788 var node = createNodeWithJSDoc(278 /* EnumMember */);
21789 node.name = parsePropertyName();
21790 node.initializer = allowInAnd(parseInitializer);
21791 return finishNode(node);
21792 }
21793 function parseEnumDeclaration(node) {
21794 node.kind = 243 /* EnumDeclaration */;
21795 parseExpected(84 /* EnumKeyword */);
21796 node.name = parseIdentifier();
21797 if (parseExpected(18 /* OpenBraceToken */)) {
21798 node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember);
21799 parseExpected(19 /* CloseBraceToken */);
21800 }
21801 else {
21802 node.members = createMissingList();
21803 }
21804 return finishNode(node);
21805 }
21806 function parseModuleBlock() {
21807 var node = createNode(245 /* ModuleBlock */);
21808 if (parseExpected(18 /* OpenBraceToken */)) {
21809 node.statements = parseList(1 /* BlockStatements */, parseStatement);
21810 parseExpected(19 /* CloseBraceToken */);
21811 }
21812 else {
21813 node.statements = createMissingList();
21814 }
21815 return finishNode(node);
21816 }
21817 function parseModuleOrNamespaceDeclaration(node, flags) {
21818 node.kind = 244 /* ModuleDeclaration */;
21819 // If we are parsing a dotted namespace name, we want to
21820 // propagate the 'Namespace' flag across the names if set.
21821 var namespaceFlag = flags & 16 /* Namespace */;
21822 node.flags |= flags;
21823 node.name = parseIdentifier();
21824 node.body = parseOptional(24 /* DotToken */)
21825 ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
21826 : parseModuleBlock();
21827 return finishNode(node);
21828 }
21829 function parseAmbientExternalModuleDeclaration(node) {
21830 node.kind = 244 /* ModuleDeclaration */;
21831 if (token() === 145 /* GlobalKeyword */) {
21832 // parse 'global' as name of global scope augmentation
21833 node.name = parseIdentifier();
21834 node.flags |= 512 /* GlobalAugmentation */;
21835 }
21836 else {
21837 node.name = parseLiteralNode();
21838 node.name.text = internIdentifier(node.name.text);
21839 }
21840 if (token() === 18 /* OpenBraceToken */) {
21841 node.body = parseModuleBlock();
21842 }
21843 else {
21844 parseSemicolon();
21845 }
21846 return finishNode(node);
21847 }
21848 function parseModuleDeclaration(node) {
21849 var flags = 0;
21850 if (token() === 145 /* GlobalKeyword */) {
21851 // global augmentation
21852 return parseAmbientExternalModuleDeclaration(node);
21853 }
21854 else if (parseOptional(131 /* NamespaceKeyword */)) {
21855 flags |= 16 /* Namespace */;
21856 }
21857 else {
21858 parseExpected(130 /* ModuleKeyword */);
21859 if (token() === 10 /* StringLiteral */) {
21860 return parseAmbientExternalModuleDeclaration(node);
21861 }
21862 }
21863 return parseModuleOrNamespaceDeclaration(node, flags);
21864 }
21865 function isExternalModuleReference() {
21866 return token() === 134 /* RequireKeyword */ &&
21867 lookAhead(nextTokenIsOpenParen);
21868 }
21869 function nextTokenIsOpenParen() {
21870 return nextToken() === 20 /* OpenParenToken */;
21871 }
21872 function nextTokenIsSlash() {
21873 return nextToken() === 42 /* SlashToken */;
21874 }
21875 function parseNamespaceExportDeclaration(node) {
21876 node.kind = 247 /* NamespaceExportDeclaration */;
21877 parseExpected(119 /* AsKeyword */);
21878 parseExpected(131 /* NamespaceKeyword */);
21879 node.name = parseIdentifier();
21880 parseSemicolon();
21881 return finishNode(node);
21882 }
21883 function parseImportDeclarationOrImportEqualsDeclaration(node) {
21884 parseExpected(92 /* ImportKeyword */);
21885 var afterImportPos = scanner.getStartPos();
21886 var identifier;
21887 if (isIdentifier()) {
21888 identifier = parseIdentifier();
21889 if (token() !== 27 /* CommaToken */ && token() !== 144 /* FromKeyword */) {
21890 return parseImportEqualsDeclaration(node, identifier);
21891 }
21892 }
21893 // Import statement
21894 node.kind = 249 /* ImportDeclaration */;
21895 // ImportDeclaration:
21896 // import ImportClause from ModuleSpecifier ;
21897 // import ModuleSpecifier;
21898 if (identifier || // import id
21899 token() === 40 /* AsteriskToken */ || // import *
21900 token() === 18 /* OpenBraceToken */) { // import {
21901 node.importClause = parseImportClause(identifier, afterImportPos);
21902 parseExpected(144 /* FromKeyword */);
21903 }
21904 node.moduleSpecifier = parseModuleSpecifier();
21905 parseSemicolon();
21906 return finishNode(node);
21907 }
21908 function parseImportEqualsDeclaration(node, identifier) {
21909 node.kind = 248 /* ImportEqualsDeclaration */;
21910 node.name = identifier;
21911 parseExpected(59 /* EqualsToken */);
21912 node.moduleReference = parseModuleReference();
21913 parseSemicolon();
21914 return finishNode(node);
21915 }
21916 function parseImportClause(identifier, fullStart) {
21917 // ImportClause:
21918 // ImportedDefaultBinding
21919 // NameSpaceImport
21920 // NamedImports
21921 // ImportedDefaultBinding, NameSpaceImport
21922 // ImportedDefaultBinding, NamedImports
21923 var importClause = createNode(250 /* ImportClause */, fullStart);
21924 if (identifier) {
21925 // ImportedDefaultBinding:
21926 // ImportedBinding
21927 importClause.name = identifier;
21928 }
21929 // If there was no default import or if there is comma token after default import
21930 // parse namespace or named imports
21931 if (!importClause.name ||
21932 parseOptional(27 /* CommaToken */)) {
21933 importClause.namedBindings = token() === 40 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(252 /* NamedImports */);
21934 }
21935 return finishNode(importClause);
21936 }
21937 function parseModuleReference() {
21938 return isExternalModuleReference()
21939 ? parseExternalModuleReference()
21940 : parseEntityName(/*allowReservedWords*/ false);
21941 }
21942 function parseExternalModuleReference() {
21943 var node = createNode(259 /* ExternalModuleReference */);
21944 parseExpected(134 /* RequireKeyword */);
21945 parseExpected(20 /* OpenParenToken */);
21946 node.expression = parseModuleSpecifier();
21947 parseExpected(21 /* CloseParenToken */);
21948 return finishNode(node);
21949 }
21950 function parseModuleSpecifier() {
21951 if (token() === 10 /* StringLiteral */) {
21952 var result = parseLiteralNode();
21953 result.text = internIdentifier(result.text);
21954 return result;
21955 }
21956 else {
21957 // We allow arbitrary expressions here, even though the grammar only allows string
21958 // literals. We check to ensure that it is only a string literal later in the grammar
21959 // check pass.
21960 return parseExpression();
21961 }
21962 }
21963 function parseNamespaceImport() {
21964 // NameSpaceImport:
21965 // * as ImportedBinding
21966 var namespaceImport = createNode(251 /* NamespaceImport */);
21967 parseExpected(40 /* AsteriskToken */);
21968 parseExpected(119 /* AsKeyword */);
21969 namespaceImport.name = parseIdentifier();
21970 return finishNode(namespaceImport);
21971 }
21972 function parseNamedImportsOrExports(kind) {
21973 var node = createNode(kind);
21974 // NamedImports:
21975 // { }
21976 // { ImportsList }
21977 // { ImportsList, }
21978 // ImportsList:
21979 // ImportSpecifier
21980 // ImportsList, ImportSpecifier
21981 node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 252 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */);
21982 return finishNode(node);
21983 }
21984 function parseExportSpecifier() {
21985 return parseImportOrExportSpecifier(257 /* ExportSpecifier */);
21986 }
21987 function parseImportSpecifier() {
21988 return parseImportOrExportSpecifier(253 /* ImportSpecifier */);
21989 }
21990 function parseImportOrExportSpecifier(kind) {
21991 var node = createNode(kind);
21992 // ImportSpecifier:
21993 // BindingIdentifier
21994 // IdentifierName as BindingIdentifier
21995 // ExportSpecifier:
21996 // IdentifierName
21997 // IdentifierName as IdentifierName
21998 var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
21999 var checkIdentifierStart = scanner.getTokenPos();
22000 var checkIdentifierEnd = scanner.getTextPos();
22001 var identifierName = parseIdentifierName();
22002 if (token() === 119 /* AsKeyword */) {
22003 node.propertyName = identifierName;
22004 parseExpected(119 /* AsKeyword */);
22005 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
22006 checkIdentifierStart = scanner.getTokenPos();
22007 checkIdentifierEnd = scanner.getTextPos();
22008 node.name = parseIdentifierName();
22009 }
22010 else {
22011 node.name = identifierName;
22012 }
22013 if (kind === 253 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
22014 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
22015 }
22016 return finishNode(node);
22017 }
22018 function parseExportDeclaration(node) {
22019 node.kind = 255 /* ExportDeclaration */;
22020 if (parseOptional(40 /* AsteriskToken */)) {
22021 parseExpected(144 /* FromKeyword */);
22022 node.moduleSpecifier = parseModuleSpecifier();
22023 }
22024 else {
22025 node.exportClause = parseNamedImportsOrExports(256 /* NamedExports */);
22026 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
22027 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
22028 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
22029 if (token() === 144 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
22030 parseExpected(144 /* FromKeyword */);
22031 node.moduleSpecifier = parseModuleSpecifier();
22032 }
22033 }
22034 parseSemicolon();
22035 return finishNode(node);
22036 }
22037 function parseExportAssignment(node) {
22038 node.kind = 254 /* ExportAssignment */;
22039 if (parseOptional(59 /* EqualsToken */)) {
22040 node.isExportEquals = true;
22041 }
22042 else {
22043 parseExpected(80 /* DefaultKeyword */);
22044 }
22045 node.expression = parseAssignmentExpressionOrHigher();
22046 parseSemicolon();
22047 return finishNode(node);
22048 }
22049 function setExternalModuleIndicator(sourceFile) {
22050 // Try to use the first top-level import/export when available, then
22051 // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
22052 sourceFile.externalModuleIndicator =
22053 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
22054 getImportMetaIfNecessary(sourceFile);
22055 }
22056 function isAnExternalModuleIndicatorNode(node) {
22057 return ts.hasModifier(node, 1 /* Export */)
22058 || node.kind === 248 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 259 /* ExternalModuleReference */
22059 || node.kind === 249 /* ImportDeclaration */
22060 || node.kind === 254 /* ExportAssignment */
22061 || node.kind === 255 /* ExportDeclaration */
22062 ? node
22063 : undefined;
22064 }
22065 function getImportMetaIfNecessary(sourceFile) {
22066 return sourceFile.flags & 1048576 /* PossiblyContainsImportMeta */ ?
22067 walkTreeForExternalModuleIndicators(sourceFile) :
22068 undefined;
22069 }
22070 function walkTreeForExternalModuleIndicators(node) {
22071 return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
22072 }
22073 function isImportMeta(node) {
22074 return ts.isMetaProperty(node) && node.keywordToken === 92 /* ImportKeyword */ && node.name.escapedText === "meta";
22075 }
22076 var ParsingContext;
22077 (function (ParsingContext) {
22078 ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
22079 ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
22080 ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
22081 ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
22082 ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
22083 ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
22084 ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
22085 ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
22086 ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
22087 ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
22088 ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
22089 ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
22090 ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
22091 ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
22092 ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
22093 ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
22094 ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
22095 ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
22096 ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
22097 ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
22098 ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
22099 ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
22100 ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
22101 ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
22102 ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
22103 })(ParsingContext || (ParsingContext = {}));
22104 var Tristate;
22105 (function (Tristate) {
22106 Tristate[Tristate["False"] = 0] = "False";
22107 Tristate[Tristate["True"] = 1] = "True";
22108 Tristate[Tristate["Unknown"] = 2] = "Unknown";
22109 })(Tristate || (Tristate = {}));
22110 var JSDocParser;
22111 (function (JSDocParser) {
22112 function parseJSDocTypeExpressionForTests(content, start, length) {
22113 initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
22114 sourceFile = createSourceFile("file.js", 7 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
22115 scanner.setText(content, start, length);
22116 currentToken = scanner.scan();
22117 var jsDocTypeExpression = parseJSDocTypeExpression();
22118 var diagnostics = parseDiagnostics;
22119 clearState();
22120 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
22121 }
22122 JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
22123 // Parses out a JSDoc type expression.
22124 function parseJSDocTypeExpression(mayOmitBraces) {
22125 var result = createNode(288 /* JSDocTypeExpression */);
22126 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
22127 result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
22128 if (!mayOmitBraces || hasBrace) {
22129 parseExpected(19 /* CloseBraceToken */);
22130 }
22131 fixupParentReferences(result);
22132 return finishNode(result);
22133 }
22134 JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
22135 function parseIsolatedJSDocComment(content, start, length) {
22136 initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
22137 sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion
22138 var jsDoc = parseJSDocCommentWorker(start, length);
22139 var diagnostics = parseDiagnostics;
22140 clearState();
22141 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
22142 }
22143 JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
22144 function parseJSDocComment(parent, start, length) {
22145 var _a;
22146 var saveToken = currentToken;
22147 var saveParseDiagnosticsLength = parseDiagnostics.length;
22148 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
22149 var comment = parseJSDocCommentWorker(start, length);
22150 if (comment) {
22151 comment.parent = parent;
22152 }
22153 if (contextFlags & 65536 /* JavaScriptFile */) {
22154 if (!sourceFile.jsDocDiagnostics) {
22155 sourceFile.jsDocDiagnostics = [];
22156 }
22157 (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
22158 }
22159 currentToken = saveToken;
22160 parseDiagnostics.length = saveParseDiagnosticsLength;
22161 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
22162 return comment;
22163 }
22164 JSDocParser.parseJSDocComment = parseJSDocComment;
22165 var JSDocState;
22166 (function (JSDocState) {
22167 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
22168 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
22169 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
22170 })(JSDocState || (JSDocState = {}));
22171 var PropertyLikeParse;
22172 (function (PropertyLikeParse) {
22173 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
22174 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
22175 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
22176 })(PropertyLikeParse || (PropertyLikeParse = {}));
22177 function parseJSDocCommentWorker(start, length) {
22178 if (start === void 0) { start = 0; }
22179 var content = sourceText;
22180 var end = length === undefined ? content.length : start + length;
22181 length = end - start;
22182 ts.Debug.assert(start >= 0);
22183 ts.Debug.assert(start <= end);
22184 ts.Debug.assert(end <= content.length);
22185 // Check for /** (JSDoc opening part)
22186 if (!isJSDocLikeText(content, start)) {
22187 return undefined;
22188 }
22189 var tags;
22190 var tagsPos;
22191 var tagsEnd;
22192 var comments = [];
22193 // + 3 for leading /**, - 5 in total for /** */
22194 return scanner.scanRange(start + 3, length - 5, function () {
22195 // Initially we can parse out a tag. We also have seen a starting asterisk.
22196 // This is so that /** * @type */ doesn't parse.
22197 var state = 1 /* SawAsterisk */;
22198 var margin;
22199 // + 4 for leading '/** '
22200 var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
22201 function pushComment(text) {
22202 if (!margin) {
22203 margin = indent;
22204 }
22205 comments.push(text);
22206 indent += text.length;
22207 }
22208 nextJSDocToken();
22209 while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
22210 ;
22211 if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
22212 state = 0 /* BeginningOfLine */;
22213 indent = 0;
22214 }
22215 loop: while (true) {
22216 switch (token()) {
22217 case 58 /* AtToken */:
22218 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
22219 removeTrailingWhitespace(comments);
22220 addTag(parseTag(indent));
22221 // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
22222 // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
22223 // for malformed examples like `/** @param {string} x @returns {number} the length */`
22224 state = 0 /* BeginningOfLine */;
22225 margin = undefined;
22226 indent++;
22227 }
22228 else {
22229 pushComment(scanner.getTokenText());
22230 }
22231 break;
22232 case 4 /* NewLineTrivia */:
22233 comments.push(scanner.getTokenText());
22234 state = 0 /* BeginningOfLine */;
22235 indent = 0;
22236 break;
22237 case 40 /* AsteriskToken */:
22238 var asterisk = scanner.getTokenText();
22239 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
22240 // If we've already seen an asterisk, then we can no longer parse a tag on this line
22241 state = 2 /* SavingComments */;
22242 pushComment(asterisk);
22243 }
22244 else {
22245 // Ignore the first asterisk on a line
22246 state = 1 /* SawAsterisk */;
22247 indent += asterisk.length;
22248 }
22249 break;
22250 case 5 /* WhitespaceTrivia */:
22251 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
22252 var whitespace = scanner.getTokenText();
22253 if (state === 2 /* SavingComments */) {
22254 comments.push(whitespace);
22255 }
22256 else if (margin !== undefined && indent + whitespace.length > margin) {
22257 comments.push(whitespace.slice(margin - indent - 1));
22258 }
22259 indent += whitespace.length;
22260 break;
22261 case 1 /* EndOfFileToken */:
22262 break loop;
22263 default:
22264 // Anything else is doc comment text. We just save it. Because it
22265 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
22266 // line break.
22267 state = 2 /* SavingComments */;
22268 pushComment(scanner.getTokenText());
22269 break;
22270 }
22271 nextJSDocToken();
22272 }
22273 removeLeadingNewlines(comments);
22274 removeTrailingWhitespace(comments);
22275 return createJSDocComment();
22276 });
22277 function removeLeadingNewlines(comments) {
22278 while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
22279 comments.shift();
22280 }
22281 }
22282 function removeTrailingWhitespace(comments) {
22283 while (comments.length && comments[comments.length - 1].trim() === "") {
22284 comments.pop();
22285 }
22286 }
22287 function createJSDocComment() {
22288 var result = createNode(296 /* JSDocComment */, start);
22289 result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
22290 result.comment = comments.length ? comments.join("") : undefined;
22291 return finishNode(result, end);
22292 }
22293 function isNextNonwhitespaceTokenEndOfFile() {
22294 // We must use infinite lookahead, as there could be any number of newlines :(
22295 while (true) {
22296 nextJSDocToken();
22297 if (token() === 1 /* EndOfFileToken */) {
22298 return true;
22299 }
22300 if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
22301 return false;
22302 }
22303 }
22304 }
22305 function skipWhitespace() {
22306 if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
22307 if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
22308 return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
22309 }
22310 }
22311 while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
22312 nextJSDocToken();
22313 }
22314 }
22315 function skipWhitespaceOrAsterisk() {
22316 if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
22317 if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
22318 return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
22319 }
22320 }
22321 var precedingLineBreak = scanner.hasPrecedingLineBreak();
22322 while ((precedingLineBreak && token() === 40 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
22323 if (token() === 4 /* NewLineTrivia */) {
22324 precedingLineBreak = true;
22325 }
22326 else if (token() === 40 /* AsteriskToken */) {
22327 precedingLineBreak = false;
22328 }
22329 nextJSDocToken();
22330 }
22331 }
22332 function parseTag(indent) {
22333 ts.Debug.assert(token() === 58 /* AtToken */);
22334 var start = scanner.getTokenPos();
22335 nextJSDocToken();
22336 var tagName = parseJSDocIdentifierName(/*message*/ undefined);
22337 skipWhitespaceOrAsterisk();
22338 var tag;
22339 switch (tagName.escapedText) {
22340 case "augments":
22341 case "extends":
22342 tag = parseAugmentsTag(start, tagName);
22343 break;
22344 case "class":
22345 case "constructor":
22346 tag = parseClassTag(start, tagName);
22347 break;
22348 case "this":
22349 tag = parseThisTag(start, tagName);
22350 break;
22351 case "enum":
22352 tag = parseEnumTag(start, tagName);
22353 break;
22354 case "arg":
22355 case "argument":
22356 case "param":
22357 return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, indent);
22358 case "return":
22359 case "returns":
22360 tag = parseReturnTag(start, tagName);
22361 break;
22362 case "template":
22363 tag = parseTemplateTag(start, tagName);
22364 break;
22365 case "type":
22366 tag = parseTypeTag(start, tagName);
22367 break;
22368 case "typedef":
22369 tag = parseTypedefTag(start, tagName, indent);
22370 break;
22371 case "callback":
22372 tag = parseCallbackTag(start, tagName, indent);
22373 break;
22374 default:
22375 tag = parseUnknownTag(start, tagName);
22376 break;
22377 }
22378 if (!tag.comment) {
22379 // some tags, like typedef and callback, have already parsed their comments earlier
22380 tag.comment = parseTagComments(indent + tag.end - tag.pos);
22381 }
22382 return tag;
22383 }
22384 function parseTagComments(indent) {
22385 var comments = [];
22386 var state = 0 /* BeginningOfLine */;
22387 var margin;
22388 function pushComment(text) {
22389 if (!margin) {
22390 margin = indent;
22391 }
22392 comments.push(text);
22393 indent += text.length;
22394 }
22395 var tok = token();
22396 loop: while (true) {
22397 switch (tok) {
22398 case 4 /* NewLineTrivia */:
22399 if (state >= 1 /* SawAsterisk */) {
22400 state = 0 /* BeginningOfLine */;
22401 comments.push(scanner.getTokenText());
22402 }
22403 indent = 0;
22404 break;
22405 case 58 /* AtToken */:
22406 scanner.setTextPos(scanner.getTextPos() - 1);
22407 // falls through
22408 case 1 /* EndOfFileToken */:
22409 // Done
22410 break loop;
22411 case 5 /* WhitespaceTrivia */:
22412 if (state === 2 /* SavingComments */) {
22413 pushComment(scanner.getTokenText());
22414 }
22415 else {
22416 var whitespace = scanner.getTokenText();
22417 // if the whitespace crosses the margin, take only the whitespace that passes the margin
22418 if (margin !== undefined && indent + whitespace.length > margin) {
22419 comments.push(whitespace.slice(margin - indent - 1));
22420 }
22421 indent += whitespace.length;
22422 }
22423 break;
22424 case 18 /* OpenBraceToken */:
22425 state = 2 /* SavingComments */;
22426 if (lookAhead(function () { return nextJSDocToken() === 58 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) {
22427 pushComment(scanner.getTokenText());
22428 nextJSDocToken();
22429 pushComment(scanner.getTokenText());
22430 nextJSDocToken();
22431 }
22432 pushComment(scanner.getTokenText());
22433 break;
22434 case 40 /* AsteriskToken */:
22435 if (state === 0 /* BeginningOfLine */) {
22436 // leading asterisks start recording on the *next* (non-whitespace) token
22437 state = 1 /* SawAsterisk */;
22438 indent += 1;
22439 break;
22440 }
22441 // record the * as a comment
22442 // falls through
22443 default:
22444 state = 2 /* SavingComments */; // leading identifiers start recording as well
22445 pushComment(scanner.getTokenText());
22446 break;
22447 }
22448 tok = nextJSDocToken();
22449 }
22450 removeLeadingNewlines(comments);
22451 removeTrailingWhitespace(comments);
22452 return comments.length === 0 ? undefined : comments.join("");
22453 }
22454 function parseUnknownTag(start, tagName) {
22455 var result = createNode(299 /* JSDocTag */, start);
22456 result.tagName = tagName;
22457 return finishNode(result);
22458 }
22459 function addTag(tag) {
22460 if (!tag) {
22461 return;
22462 }
22463 if (!tags) {
22464 tags = [tag];
22465 tagsPos = tag.pos;
22466 }
22467 else {
22468 tags.push(tag);
22469 }
22470 tagsEnd = tag.end;
22471 }
22472 function tryParseTypeExpression() {
22473 skipWhitespaceOrAsterisk();
22474 return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
22475 }
22476 function parseBracketNameInPropertyAndParamTag() {
22477 if (token() === 14 /* NoSubstitutionTemplateLiteral */) {
22478 // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
22479 return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false };
22480 }
22481 // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
22482 var isBracketed = parseOptional(22 /* OpenBracketToken */);
22483 var name = parseJSDocEntityName();
22484 if (isBracketed) {
22485 skipWhitespace();
22486 // May have an optional default, e.g. '[foo = 42]'
22487 if (parseOptionalToken(59 /* EqualsToken */)) {
22488 parseExpression();
22489 }
22490 parseExpected(23 /* CloseBracketToken */);
22491 }
22492 return { name: name, isBracketed: isBracketed };
22493 }
22494 function isObjectOrObjectArrayTypeReference(node) {
22495 switch (node.kind) {
22496 case 136 /* ObjectKeyword */:
22497 return true;
22498 case 169 /* ArrayType */:
22499 return isObjectOrObjectArrayTypeReference(node.elementType);
22500 default:
22501 return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object";
22502 }
22503 }
22504 function parseParameterOrPropertyTag(start, tagName, target, indent) {
22505 var typeExpression = tryParseTypeExpression();
22506 var isNameFirst = !typeExpression;
22507 skipWhitespaceOrAsterisk();
22508 var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
22509 skipWhitespace();
22510 if (isNameFirst) {
22511 typeExpression = tryParseTypeExpression();
22512 }
22513 var result = target === 1 /* Property */ ?
22514 createNode(310 /* JSDocPropertyTag */, start) :
22515 createNode(304 /* JSDocParameterTag */, start);
22516 var comment = parseTagComments(indent + scanner.getStartPos() - start);
22517 var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
22518 if (nestedTypeLiteral) {
22519 typeExpression = nestedTypeLiteral;
22520 isNameFirst = true;
22521 }
22522 result.tagName = tagName;
22523 result.typeExpression = typeExpression;
22524 result.name = name;
22525 result.isNameFirst = isNameFirst;
22526 result.isBracketed = isBracketed;
22527 result.comment = comment;
22528 return finishNode(result);
22529 }
22530 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
22531 if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
22532 var typeLiteralExpression = createNode(288 /* JSDocTypeExpression */, scanner.getTokenPos());
22533 var child = void 0;
22534 var jsdocTypeLiteral = void 0;
22535 var start_2 = scanner.getStartPos();
22536 var children = void 0;
22537 while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
22538 if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
22539 children = ts.append(children, child);
22540 }
22541 }
22542 if (children) {
22543 jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
22544 jsdocTypeLiteral.jsDocPropertyTags = children;
22545 if (typeExpression.type.kind === 169 /* ArrayType */) {
22546 jsdocTypeLiteral.isArrayType = true;
22547 }
22548 typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
22549 return finishNode(typeLiteralExpression);
22550 }
22551 }
22552 }
22553 function parseReturnTag(start, tagName) {
22554 if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
22555 parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
22556 }
22557 var result = createNode(305 /* JSDocReturnTag */, start);
22558 result.tagName = tagName;
22559 result.typeExpression = tryParseTypeExpression();
22560 return finishNode(result);
22561 }
22562 function parseTypeTag(start, tagName) {
22563 if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
22564 parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
22565 }
22566 var result = createNode(307 /* JSDocTypeTag */, start);
22567 result.tagName = tagName;
22568 result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
22569 return finishNode(result);
22570 }
22571 function parseAugmentsTag(start, tagName) {
22572 var result = createNode(300 /* JSDocAugmentsTag */, start);
22573 result.tagName = tagName;
22574 result.class = parseExpressionWithTypeArgumentsForAugments();
22575 return finishNode(result);
22576 }
22577 function parseExpressionWithTypeArgumentsForAugments() {
22578 var usedBrace = parseOptional(18 /* OpenBraceToken */);
22579 var node = createNode(211 /* ExpressionWithTypeArguments */);
22580 node.expression = parsePropertyAccessEntityNameExpression();
22581 node.typeArguments = tryParseTypeArguments();
22582 var res = finishNode(node);
22583 if (usedBrace) {
22584 parseExpected(19 /* CloseBraceToken */);
22585 }
22586 return res;
22587 }
22588 function parsePropertyAccessEntityNameExpression() {
22589 var node = parseJSDocIdentifierName();
22590 while (parseOptional(24 /* DotToken */)) {
22591 var prop = createNode(189 /* PropertyAccessExpression */, node.pos);
22592 prop.expression = node;
22593 prop.name = parseJSDocIdentifierName();
22594 node = finishNode(prop);
22595 }
22596 return node;
22597 }
22598 function parseClassTag(start, tagName) {
22599 var tag = createNode(301 /* JSDocClassTag */, start);
22600 tag.tagName = tagName;
22601 return finishNode(tag);
22602 }
22603 function parseThisTag(start, tagName) {
22604 var tag = createNode(306 /* JSDocThisTag */, start);
22605 tag.tagName = tagName;
22606 tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
22607 skipWhitespace();
22608 return finishNode(tag);
22609 }
22610 function parseEnumTag(start, tagName) {
22611 var tag = createNode(303 /* JSDocEnumTag */, start);
22612 tag.tagName = tagName;
22613 tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
22614 skipWhitespace();
22615 return finishNode(tag);
22616 }
22617 function parseTypedefTag(start, tagName, indent) {
22618 var typeExpression = tryParseTypeExpression();
22619 skipWhitespaceOrAsterisk();
22620 var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
22621 typedefTag.tagName = tagName;
22622 typedefTag.fullName = parseJSDocTypeNameWithNamespace();
22623 typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
22624 skipWhitespace();
22625 typedefTag.comment = parseTagComments(indent);
22626 typedefTag.typeExpression = typeExpression;
22627 var end;
22628 if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
22629 var child = void 0;
22630 var jsdocTypeLiteral = void 0;
22631 var childTypeTag = void 0;
22632 while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
22633 if (!jsdocTypeLiteral) {
22634 jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
22635 }
22636 if (child.kind === 307 /* JSDocTypeTag */) {
22637 if (childTypeTag) {
22638 break;
22639 }
22640 else {
22641 childTypeTag = child;
22642 }
22643 }
22644 else {
22645 jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
22646 }
22647 }
22648 if (jsdocTypeLiteral) {
22649 if (typeExpression && typeExpression.type.kind === 169 /* ArrayType */) {
22650 jsdocTypeLiteral.isArrayType = true;
22651 }
22652 typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
22653 childTypeTag.typeExpression :
22654 finishNode(jsdocTypeLiteral);
22655 end = typedefTag.typeExpression.end;
22656 }
22657 }
22658 // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
22659 return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
22660 }
22661 function parseJSDocTypeNameWithNamespace(nested) {
22662 var pos = scanner.getTokenPos();
22663 if (!ts.tokenIsIdentifierOrKeyword(token())) {
22664 return undefined;
22665 }
22666 var typeNameOrNamespaceName = parseJSDocIdentifierName();
22667 if (parseOptional(24 /* DotToken */)) {
22668 var jsDocNamespaceNode = createNode(244 /* ModuleDeclaration */, pos);
22669 if (nested) {
22670 jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
22671 }
22672 jsDocNamespaceNode.name = typeNameOrNamespaceName;
22673 jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
22674 return finishNode(jsDocNamespaceNode);
22675 }
22676 if (nested) {
22677 typeNameOrNamespaceName.isInJSDocNamespace = true;
22678 }
22679 return typeNameOrNamespaceName;
22680 }
22681 function parseCallbackTag(start, tagName, indent) {
22682 var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
22683 callbackTag.tagName = tagName;
22684 callbackTag.fullName = parseJSDocTypeNameWithNamespace();
22685 callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
22686 skipWhitespace();
22687 callbackTag.comment = parseTagComments(indent);
22688 var child;
22689 var jsdocSignature = createNode(298 /* JSDocSignature */, start);
22690 jsdocSignature.parameters = [];
22691 while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
22692 jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
22693 }
22694 var returnTag = tryParse(function () {
22695 if (parseOptionalJsdoc(58 /* AtToken */)) {
22696 var tag = parseTag(indent);
22697 if (tag && tag.kind === 305 /* JSDocReturnTag */) {
22698 return tag;
22699 }
22700 }
22701 });
22702 if (returnTag) {
22703 jsdocSignature.type = returnTag;
22704 }
22705 callbackTag.typeExpression = finishNode(jsdocSignature);
22706 return finishNode(callbackTag);
22707 }
22708 function getJSDocTypeAliasName(fullName) {
22709 if (fullName) {
22710 var rightNode = fullName;
22711 while (true) {
22712 if (ts.isIdentifier(rightNode) || !rightNode.body) {
22713 return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
22714 }
22715 rightNode = rightNode.body;
22716 }
22717 }
22718 }
22719 function escapedTextsEqual(a, b) {
22720 while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
22721 if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
22722 a = a.left;
22723 b = b.left;
22724 }
22725 else {
22726 return false;
22727 }
22728 }
22729 return a.escapedText === b.escapedText;
22730 }
22731 function parseChildPropertyTag(indent) {
22732 return parseChildParameterOrPropertyTag(1 /* Property */, indent);
22733 }
22734 function parseChildParameterOrPropertyTag(target, indent, name) {
22735 var canParseTag = true;
22736 var seenAsterisk = false;
22737 while (true) {
22738 switch (nextJSDocToken()) {
22739 case 58 /* AtToken */:
22740 if (canParseTag) {
22741 var child = tryParseChildTag(target, indent);
22742 if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
22743 target !== 4 /* CallbackParameter */ &&
22744 name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
22745 return false;
22746 }
22747 return child;
22748 }
22749 seenAsterisk = false;
22750 break;
22751 case 4 /* NewLineTrivia */:
22752 canParseTag = true;
22753 seenAsterisk = false;
22754 break;
22755 case 40 /* AsteriskToken */:
22756 if (seenAsterisk) {
22757 canParseTag = false;
22758 }
22759 seenAsterisk = true;
22760 break;
22761 case 72 /* Identifier */:
22762 canParseTag = false;
22763 break;
22764 case 1 /* EndOfFileToken */:
22765 return false;
22766 }
22767 }
22768 }
22769 function tryParseChildTag(target, indent) {
22770 ts.Debug.assert(token() === 58 /* AtToken */);
22771 var start = scanner.getStartPos();
22772 nextJSDocToken();
22773 var tagName = parseJSDocIdentifierName();
22774 skipWhitespace();
22775 var t;
22776 switch (tagName.escapedText) {
22777 case "type":
22778 return target === 1 /* Property */ && parseTypeTag(start, tagName);
22779 case "prop":
22780 case "property":
22781 t = 1 /* Property */;
22782 break;
22783 case "arg":
22784 case "argument":
22785 case "param":
22786 t = 2 /* Parameter */ | 4 /* CallbackParameter */;
22787 break;
22788 default:
22789 return false;
22790 }
22791 if (!(target & t)) {
22792 return false;
22793 }
22794 return parseParameterOrPropertyTag(start, tagName, target, indent);
22795 }
22796 function parseTemplateTag(start, tagName) {
22797 // the template tag looks like '@template {Constraint} T,U,V'
22798 var constraint;
22799 if (token() === 18 /* OpenBraceToken */) {
22800 constraint = parseJSDocTypeExpression();
22801 }
22802 var typeParameters = [];
22803 var typeParametersPos = getNodePos();
22804 do {
22805 skipWhitespace();
22806 var typeParameter = createNode(150 /* TypeParameter */);
22807 typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
22808 finishNode(typeParameter);
22809 skipWhitespace();
22810 typeParameters.push(typeParameter);
22811 } while (parseOptionalJsdoc(27 /* CommaToken */));
22812 var result = createNode(308 /* JSDocTemplateTag */, start);
22813 result.tagName = tagName;
22814 result.constraint = constraint;
22815 result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
22816 finishNode(result);
22817 return result;
22818 }
22819 function nextJSDocToken() {
22820 return currentToken = scanner.scanJSDocToken();
22821 }
22822 function parseOptionalJsdoc(t) {
22823 if (token() === t) {
22824 nextJSDocToken();
22825 return true;
22826 }
22827 return false;
22828 }
22829 function parseJSDocEntityName() {
22830 var entity = parseJSDocIdentifierName();
22831 if (parseOptional(22 /* OpenBracketToken */)) {
22832 parseExpected(23 /* CloseBracketToken */);
22833 // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
22834 // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
22835 // but it's not worth it to enforce that restriction.
22836 }
22837 while (parseOptional(24 /* DotToken */)) {
22838 var name = parseJSDocIdentifierName();
22839 if (parseOptional(22 /* OpenBracketToken */)) {
22840 parseExpected(23 /* CloseBracketToken */);
22841 }
22842 entity = createQualifiedName(entity, name);
22843 }
22844 return entity;
22845 }
22846 function parseJSDocIdentifierName(message) {
22847 if (!ts.tokenIsIdentifierOrKeyword(token())) {
22848 return createMissingNode(72 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
22849 }
22850 var pos = scanner.getTokenPos();
22851 var end = scanner.getTextPos();
22852 var result = createNode(72 /* Identifier */, pos);
22853 result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText());
22854 finishNode(result, end);
22855 nextJSDocToken();
22856 return result;
22857 }
22858 }
22859 JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker;
22860 })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
22861 })(Parser || (Parser = {}));
22862 var IncrementalParser;
22863 (function (IncrementalParser) {
22864 function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
22865 aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
22866 checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
22867 if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
22868 // if the text didn't change, then we can just return our current source file as-is.
22869 return sourceFile;
22870 }
22871 if (sourceFile.statements.length === 0) {
22872 // If we don't have any statements in the current source file, then there's no real
22873 // way to incrementally parse. So just do a full parse instead.
22874 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
22875 }
22876 // Make sure we're not trying to incrementally update a source file more than once. Once
22877 // we do an update the original source file is considered unusable from that point onwards.
22878 //
22879 // This is because we do incremental parsing in-place. i.e. we take nodes from the old
22880 // tree and give them new positions and parents. From that point on, trusting the old
22881 // tree at all is not possible as far too much of it may violate invariants.
22882 var incrementalSourceFile = sourceFile;
22883 ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
22884 incrementalSourceFile.hasBeenIncrementallyParsed = true;
22885 var oldText = sourceFile.text;
22886 var syntaxCursor = createSyntaxCursor(sourceFile);
22887 // Make the actual change larger so that we know to reparse anything whose lookahead
22888 // might have intersected the change.
22889 var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
22890 checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
22891 // Ensure that extending the affected range only moved the start of the change range
22892 // earlier in the file.
22893 ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
22894 ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
22895 ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
22896 // The is the amount the nodes after the edit range need to be adjusted. It can be
22897 // positive (if the edit added characters), negative (if the edit deleted characters)
22898 // or zero (if this was a pure overwrite with nothing added/removed).
22899 var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
22900 // If we added or removed characters during the edit, then we need to go and adjust all
22901 // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they
22902 // may move backward (if we deleted chars).
22903 //
22904 // Doing this helps us out in two ways. First, it means that any nodes/tokens we want
22905 // to reuse are already at the appropriate position in the new text. That way when we
22906 // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes
22907 // it very easy to determine if we can reuse a node. If the node's position is at where
22908 // we are in the text, then we can reuse it. Otherwise we can't. If the node's position
22909 // is ahead of us, then we'll need to rescan tokens. If the node's position is behind
22910 // us, then we'll need to skip it or crumble it as appropriate
22911 //
22912 // We will also adjust the positions of nodes that intersect the change range as well.
22913 // By doing this, we ensure that all the positions in the old tree are consistent, not
22914 // just the positions of nodes entirely before/after the change range. By being
22915 // consistent, we can then easily map from positions to nodes in the old tree easily.
22916 //
22917 // Also, mark any syntax elements that intersect the changed span. We know, up front,
22918 // that we cannot reuse these elements.
22919 updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
22920 // Now that we've set up our internal incremental state just proceed and parse the
22921 // source file in the normal fashion. When possible the parser will retrieve and
22922 // reuse nodes from the old tree.
22923 //
22924 // Note: passing in 'true' for setNodeParents is very important. When incrementally
22925 // parsing, we will be reusing nodes from the old tree, and placing it into new
22926 // parents. If we don't set the parents now, we'll end up with an observably
22927 // inconsistent tree. Setting the parents on the new tree should be very fast. We
22928 // will immediately bail out of walking any subtrees when we can see that their parents
22929 // are already correct.
22930 var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
22931 return result;
22932 }
22933 IncrementalParser.updateSourceFile = updateSourceFile;
22934 function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
22935 if (isArray) {
22936 visitArray(element);
22937 }
22938 else {
22939 visitNode(element);
22940 }
22941 return;
22942 function visitNode(node) {
22943 var text = "";
22944 if (aggressiveChecks && shouldCheckNode(node)) {
22945 text = oldText.substring(node.pos, node.end);
22946 }
22947 // Ditch any existing LS children we may have created. This way we can avoid
22948 // moving them forward.
22949 if (node._children) {
22950 node._children = undefined;
22951 }
22952 node.pos += delta;
22953 node.end += delta;
22954 if (aggressiveChecks && shouldCheckNode(node)) {
22955 ts.Debug.assert(text === newText.substring(node.pos, node.end));
22956 }
22957 forEachChild(node, visitNode, visitArray);
22958 if (ts.hasJSDocNodes(node)) {
22959 for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
22960 var jsDocComment = _a[_i];
22961 visitNode(jsDocComment);
22962 }
22963 }
22964 checkNodePositions(node, aggressiveChecks);
22965 }
22966 function visitArray(array) {
22967 array._children = undefined;
22968 array.pos += delta;
22969 array.end += delta;
22970 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
22971 var node = array_8[_i];
22972 visitNode(node);
22973 }
22974 }
22975 }
22976 function shouldCheckNode(node) {
22977 switch (node.kind) {
22978 case 10 /* StringLiteral */:
22979 case 8 /* NumericLiteral */:
22980 case 72 /* Identifier */:
22981 return true;
22982 }
22983 return false;
22984 }
22985 function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
22986 ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
22987 ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
22988 ts.Debug.assert(element.pos <= element.end);
22989 // We have an element that intersects the change range in some way. It may have its
22990 // start, or its end (or both) in the changed range. We want to adjust any part
22991 // that intersects such that the final tree is in a consistent state. i.e. all
22992 // children have spans within the span of their parent, and all siblings are ordered
22993 // properly.
22994 // We may need to update both the 'pos' and the 'end' of the element.
22995 // If the 'pos' is before the start of the change, then we don't need to touch it.
22996 // If it isn't, then the 'pos' must be inside the change. How we update it will
22997 // depend if delta is positive or negative. If delta is positive then we have
22998 // something like:
22999 //
23000 // -------------------AAA-----------------
23001 // -------------------BBBCCCCCCC-----------------
23002 //
23003 // In this case, we consider any node that started in the change range to still be
23004 // starting at the same position.
23005 //
23006 // however, if the delta is negative, then we instead have something like this:
23007 //
23008 // -------------------XXXYYYYYYY-----------------
23009 // -------------------ZZZ-----------------
23010 //
23011 // In this case, any element that started in the 'X' range will keep its position.
23012 // However any element that started after that will have their pos adjusted to be
23013 // at the end of the new range. i.e. any node that started in the 'Y' range will
23014 // be adjusted to have their start at the end of the 'Z' range.
23015 //
23016 // The element will keep its position if possible. Or Move backward to the new-end
23017 // if it's in the 'Y' range.
23018 element.pos = Math.min(element.pos, changeRangeNewEnd);
23019 // If the 'end' is after the change range, then we always adjust it by the delta
23020 // amount. However, if the end is in the change range, then how we adjust it
23021 // will depend on if delta is positive or negative. If delta is positive then we
23022 // have something like:
23023 //
23024 // -------------------AAA-----------------
23025 // -------------------BBBCCCCCCC-----------------
23026 //
23027 // In this case, we consider any node that ended inside the change range to keep its
23028 // end position.
23029 //
23030 // however, if the delta is negative, then we instead have something like this:
23031 //
23032 // -------------------XXXYYYYYYY-----------------
23033 // -------------------ZZZ-----------------
23034 //
23035 // In this case, any element that ended in the 'X' range will keep its position.
23036 // However any element that ended after that will have their pos adjusted to be
23037 // at the end of the new range. i.e. any node that ended in the 'Y' range will
23038 // be adjusted to have their end at the end of the 'Z' range.
23039 if (element.end >= changeRangeOldEnd) {
23040 // Element ends after the change range. Always adjust the end pos.
23041 element.end += delta;
23042 }
23043 else {
23044 // Element ends in the change range. The element will keep its position if
23045 // possible. Or Move backward to the new-end if it's in the 'Y' range.
23046 element.end = Math.min(element.end, changeRangeNewEnd);
23047 }
23048 ts.Debug.assert(element.pos <= element.end);
23049 if (element.parent) {
23050 ts.Debug.assert(element.pos >= element.parent.pos);
23051 ts.Debug.assert(element.end <= element.parent.end);
23052 }
23053 }
23054 function checkNodePositions(node, aggressiveChecks) {
23055 if (aggressiveChecks) {
23056 var pos_2 = node.pos;
23057 var visitNode_1 = function (child) {
23058 ts.Debug.assert(child.pos >= pos_2);
23059 pos_2 = child.end;
23060 };
23061 if (ts.hasJSDocNodes(node)) {
23062 for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
23063 var jsDocComment = _a[_i];
23064 visitNode_1(jsDocComment);
23065 }
23066 }
23067 forEachChild(node, visitNode_1);
23068 ts.Debug.assert(pos_2 <= node.end);
23069 }
23070 }
23071 function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
23072 visitNode(sourceFile);
23073 return;
23074 function visitNode(child) {
23075 ts.Debug.assert(child.pos <= child.end);
23076 if (child.pos > changeRangeOldEnd) {
23077 // Node is entirely past the change range. We need to move both its pos and
23078 // end, forward or backward appropriately.
23079 moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
23080 return;
23081 }
23082 // Check if the element intersects the change range. If it does, then it is not
23083 // reusable. Also, we'll need to recurse to see what constituent portions we may
23084 // be able to use.
23085 var fullEnd = child.end;
23086 if (fullEnd >= changeStart) {
23087 child.intersectsChange = true;
23088 child._children = undefined;
23089 // Adjust the pos or end (or both) of the intersecting element accordingly.
23090 adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
23091 forEachChild(child, visitNode, visitArray);
23092 if (ts.hasJSDocNodes(child)) {
23093 for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
23094 var jsDocComment = _a[_i];
23095 visitNode(jsDocComment);
23096 }
23097 }
23098 checkNodePositions(child, aggressiveChecks);
23099 return;
23100 }
23101 // Otherwise, the node is entirely before the change range. No need to do anything with it.
23102 ts.Debug.assert(fullEnd < changeStart);
23103 }
23104 function visitArray(array) {
23105 ts.Debug.assert(array.pos <= array.end);
23106 if (array.pos > changeRangeOldEnd) {
23107 // Array is entirely after the change range. We need to move it, and move any of
23108 // its children.
23109 moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
23110 return;
23111 }
23112 // Check if the element intersects the change range. If it does, then it is not
23113 // reusable. Also, we'll need to recurse to see what constituent portions we may
23114 // be able to use.
23115 var fullEnd = array.end;
23116 if (fullEnd >= changeStart) {
23117 array.intersectsChange = true;
23118 array._children = undefined;
23119 // Adjust the pos or end (or both) of the intersecting array accordingly.
23120 adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
23121 for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
23122 var node = array_9[_i];
23123 visitNode(node);
23124 }
23125 return;
23126 }
23127 // Otherwise, the array is entirely before the change range. No need to do anything with it.
23128 ts.Debug.assert(fullEnd < changeStart);
23129 }
23130 }
23131 function extendToAffectedRange(sourceFile, changeRange) {
23132 // Consider the following code:
23133 // void foo() { /; }
23134 //
23135 // If the text changes with an insertion of / just before the semicolon then we end up with:
23136 // void foo() { //; }
23137 //
23138 // If we were to just use the changeRange a is, then we would not rescan the { token
23139 // (as it does not intersect the actual original change range). Because an edit may
23140 // change the token touching it, we actually need to look back *at least* one token so
23141 // that the prior token sees that change.
23142 var maxLookahead = 1;
23143 var start = changeRange.span.start;
23144 // the first iteration aligns us with the change start. subsequent iteration move us to
23145 // the left by maxLookahead tokens. We only need to do this as long as we're not at the
23146 // start of the tree.
23147 for (var i = 0; start > 0 && i <= maxLookahead; i++) {
23148 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
23149 ts.Debug.assert(nearestNode.pos <= start);
23150 var position = nearestNode.pos;
23151 start = Math.max(0, position - 1);
23152 }
23153 var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
23154 var finalLength = changeRange.newLength + (changeRange.span.start - start);
23155 return ts.createTextChangeRange(finalSpan, finalLength);
23156 }
23157 function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
23158 var bestResult = sourceFile;
23159 var lastNodeEntirelyBeforePosition;
23160 forEachChild(sourceFile, visit);
23161 if (lastNodeEntirelyBeforePosition) {
23162 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
23163 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
23164 bestResult = lastChildOfLastEntireNodeBeforePosition;
23165 }
23166 }
23167 return bestResult;
23168 function getLastDescendant(node) {
23169 while (true) {
23170 var lastChild = ts.getLastChild(node);
23171 if (lastChild) {
23172 node = lastChild;
23173 }
23174 else {
23175 return node;
23176 }
23177 }
23178 }
23179 function visit(child) {
23180 if (ts.nodeIsMissing(child)) {
23181 // Missing nodes are effectively invisible to us. We never even consider them
23182 // When trying to find the nearest node before us.
23183 return;
23184 }
23185 // If the child intersects this position, then this node is currently the nearest
23186 // node that starts before the position.
23187 if (child.pos <= position) {
23188 if (child.pos >= bestResult.pos) {
23189 // This node starts before the position, and is closer to the position than
23190 // the previous best node we found. It is now the new best node.
23191 bestResult = child;
23192 }
23193 // Now, the node may overlap the position, or it may end entirely before the
23194 // position. If it overlaps with the position, then either it, or one of its
23195 // children must be the nearest node before the position. So we can just
23196 // recurse into this child to see if we can find something better.
23197 if (position < child.end) {
23198 // The nearest node is either this child, or one of the children inside
23199 // of it. We've already marked this child as the best so far. Recurse
23200 // in case one of the children is better.
23201 forEachChild(child, visit);
23202 // Once we look at the children of this node, then there's no need to
23203 // continue any further.
23204 return true;
23205 }
23206 else {
23207 ts.Debug.assert(child.end <= position);
23208 // The child ends entirely before this position. Say you have the following
23209 // (where $ is the position)
23210 //
23211 // <complex expr 1> ? <complex expr 2> $ : <...> <...>
23212 //
23213 // We would want to find the nearest preceding node in "complex expr 2".
23214 // To support that, we keep track of this node, and once we're done searching
23215 // for a best node, we recurse down this node to see if we can find a good
23216 // result in it.
23217 //
23218 // This approach allows us to quickly skip over nodes that are entirely
23219 // before the position, while still allowing us to find any nodes in the
23220 // last one that might be what we want.
23221 lastNodeEntirelyBeforePosition = child;
23222 }
23223 }
23224 else {
23225 ts.Debug.assert(child.pos > position);
23226 // We're now at a node that is entirely past the position we're searching for.
23227 // This node (and all following nodes) could never contribute to the result,
23228 // so just skip them by returning 'true' here.
23229 return true;
23230 }
23231 }
23232 }
23233 function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
23234 var oldText = sourceFile.text;
23235 if (textChangeRange) {
23236 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
23237 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
23238 var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
23239 var newTextPrefix = newText.substr(0, textChangeRange.span.start);
23240 ts.Debug.assert(oldTextPrefix === newTextPrefix);
23241 var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
23242 var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
23243 ts.Debug.assert(oldTextSuffix === newTextSuffix);
23244 }
23245 }
23246 }
23247 function createSyntaxCursor(sourceFile) {
23248 var currentArray = sourceFile.statements;
23249 var currentArrayIndex = 0;
23250 ts.Debug.assert(currentArrayIndex < currentArray.length);
23251 var current = currentArray[currentArrayIndex];
23252 var lastQueriedPosition = -1 /* Value */;
23253 return {
23254 currentNode: function (position) {
23255 // Only compute the current node if the position is different than the last time
23256 // we were asked. The parser commonly asks for the node at the same position
23257 // twice. Once to know if can read an appropriate list element at a certain point,
23258 // and then to actually read and consume the node.
23259 if (position !== lastQueriedPosition) {
23260 // Much of the time the parser will need the very next node in the array that
23261 // we just returned a node from.So just simply check for that case and move
23262 // forward in the array instead of searching for the node again.
23263 if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
23264 currentArrayIndex++;
23265 current = currentArray[currentArrayIndex];
23266 }
23267 // If we don't have a node, or the node we have isn't in the right position,
23268 // then try to find a viable node at the position requested.
23269 if (!current || current.pos !== position) {
23270 findHighestListElementThatStartsAtPosition(position);
23271 }
23272 }
23273 // Cache this query so that we don't do any extra work if the parser calls back
23274 // into us. Note: this is very common as the parser will make pairs of calls like
23275 // 'isListElement -> parseListElement'. If we were unable to find a node when
23276 // called with 'isListElement', we don't want to redo the work when parseListElement
23277 // is called immediately after.
23278 lastQueriedPosition = position;
23279 // Either we don'd have a node, or we have a node at the position being asked for.
23280 ts.Debug.assert(!current || current.pos === position);
23281 return current;
23282 }
23283 };
23284 // Finds the highest element in the tree we can find that starts at the provided position.
23285 // The element must be a direct child of some node list in the tree. This way after we
23286 // return it, we can easily return its next sibling in the list.
23287 function findHighestListElementThatStartsAtPosition(position) {
23288 // Clear out any cached state about the last node we found.
23289 currentArray = undefined;
23290 currentArrayIndex = -1 /* Value */;
23291 current = undefined;
23292 // Recurse into the source file to find the highest node at this position.
23293 forEachChild(sourceFile, visitNode, visitArray);
23294 return;
23295 function visitNode(node) {
23296 if (position >= node.pos && position < node.end) {
23297 // Position was within this node. Keep searching deeper to find the node.
23298 forEachChild(node, visitNode, visitArray);
23299 // don't proceed any further in the search.
23300 return true;
23301 }
23302 // position wasn't in this node, have to keep searching.
23303 return false;
23304 }
23305 function visitArray(array) {
23306 if (position >= array.pos && position < array.end) {
23307 // position was in this array. Search through this array to see if we find a
23308 // viable element.
23309 for (var i = 0; i < array.length; i++) {
23310 var child = array[i];
23311 if (child) {
23312 if (child.pos === position) {
23313 // Found the right node. We're done.
23314 currentArray = array;
23315 currentArrayIndex = i;
23316 current = child;
23317 return true;
23318 }
23319 else {
23320 if (child.pos < position && position < child.end) {
23321 // Position in somewhere within this child. Search in it and
23322 // stop searching in this array.
23323 forEachChild(child, visitNode, visitArray);
23324 return true;
23325 }
23326 }
23327 }
23328 }
23329 }
23330 // position wasn't in this array, have to keep searching.
23331 return false;
23332 }
23333 }
23334 }
23335 var InvalidPosition;
23336 (function (InvalidPosition) {
23337 InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
23338 })(InvalidPosition || (InvalidPosition = {}));
23339 })(IncrementalParser || (IncrementalParser = {}));
23340 /** @internal */
23341 function isDeclarationFileName(fileName) {
23342 return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
23343 }
23344 ts.isDeclarationFileName = isDeclarationFileName;
23345 /*@internal*/
23346 function processCommentPragmas(context, sourceText) {
23347 var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText);
23348 var pragmas = [];
23349 // Keep scanning all the leading trivia in the file until we get to something that
23350 // isn't trivia. Any single line comment will be analyzed to see if it is a
23351 // reference comment.
23352 while (true) {
23353 var kind = triviaScanner.scan();
23354 if (!ts.isTrivia(kind)) {
23355 break;
23356 }
23357 var range = {
23358 kind: triviaScanner.getToken(),
23359 pos: triviaScanner.getTokenPos(),
23360 end: triviaScanner.getTextPos(),
23361 };
23362 var comment = sourceText.substring(range.pos, range.end);
23363 extractPragmas(pragmas, range, comment);
23364 }
23365 context.pragmas = ts.createMap();
23366 for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) {
23367 var pragma = pragmas_1[_i];
23368 if (context.pragmas.has(pragma.name)) { // TODO: GH#18217
23369 var currentValue = context.pragmas.get(pragma.name);
23370 if (currentValue instanceof Array) {
23371 currentValue.push(pragma.args);
23372 }
23373 else {
23374 context.pragmas.set(pragma.name, [currentValue, pragma.args]);
23375 }
23376 continue;
23377 }
23378 context.pragmas.set(pragma.name, pragma.args);
23379 }
23380 }
23381 ts.processCommentPragmas = processCommentPragmas;
23382 /*@internal*/
23383 function processPragmasIntoFields(context, reportDiagnostic) {
23384 context.checkJsDirective = undefined;
23385 context.referencedFiles = [];
23386 context.typeReferenceDirectives = [];
23387 context.libReferenceDirectives = [];
23388 context.amdDependencies = [];
23389 context.hasNoDefaultLib = false;
23390 context.pragmas.forEach(function (entryOrList, key) {
23391 // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
23392 // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
23393 switch (key) {
23394 case "reference": {
23395 var referencedFiles_1 = context.referencedFiles;
23396 var typeReferenceDirectives_1 = context.typeReferenceDirectives;
23397 var libReferenceDirectives_1 = context.libReferenceDirectives;
23398 ts.forEach(ts.toArray(entryOrList), function (arg) {
23399 // TODO: GH#18217
23400 var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
23401 if (arg.arguments["no-default-lib"]) {
23402 context.hasNoDefaultLib = true;
23403 }
23404 else if (types) {
23405 typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
23406 }
23407 else if (lib) {
23408 libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
23409 }
23410 else if (path) {
23411 referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
23412 }
23413 else {
23414 reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
23415 }
23416 });
23417 break;
23418 }
23419 case "amd-dependency": {
23420 context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217
23421 break;
23422 }
23423 case "amd-module": {
23424 if (entryOrList instanceof Array) {
23425 for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
23426 var entry = entryOrList_1[_i];
23427 if (context.moduleName) {
23428 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
23429 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
23430 }
23431 context.moduleName = entry.arguments.name;
23432 }
23433 }
23434 else {
23435 context.moduleName = entryOrList.arguments.name;
23436 }
23437 break;
23438 }
23439 case "ts-nocheck":
23440 case "ts-check": {
23441 // _last_ of either nocheck or check in a file is the "winner"
23442 ts.forEach(ts.toArray(entryOrList), function (entry) {
23443 if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217
23444 context.checkJsDirective = {
23445 enabled: key === "ts-check",
23446 end: entry.range.end,
23447 pos: entry.range.pos
23448 };
23449 }
23450 });
23451 break;
23452 }
23453 case "jsx": return; // Accessed directly
23454 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
23455 }
23456 });
23457 }
23458 ts.processPragmasIntoFields = processPragmasIntoFields;
23459 var namedArgRegExCache = ts.createMap();
23460 function getNamedArgRegEx(name) {
23461 if (namedArgRegExCache.has(name)) {
23462 return namedArgRegExCache.get(name);
23463 }
23464 var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
23465 namedArgRegExCache.set(name, result);
23466 return result;
23467 }
23468 var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
23469 var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
23470 function extractPragmas(pragmas, range, text) {
23471 var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
23472 if (tripleSlash) {
23473 var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
23474 var pragma = ts.commentPragmas[name];
23475 if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
23476 return;
23477 }
23478 if (pragma.args) {
23479 var argument = {};
23480 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
23481 var arg = _a[_i];
23482 var matcher = getNamedArgRegEx(arg.name);
23483 var matchResult = matcher.exec(text);
23484 if (!matchResult && !arg.optional) {
23485 return; // Missing required argument, don't parse
23486 }
23487 else if (matchResult) {
23488 if (arg.captureSpan) {
23489 var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
23490 argument[arg.name] = {
23491 value: matchResult[3],
23492 pos: startPos,
23493 end: startPos + matchResult[3].length
23494 };
23495 }
23496 else {
23497 argument[arg.name] = matchResult[3];
23498 }
23499 }
23500 }
23501 pragmas.push({ name: name, args: { arguments: argument, range: range } });
23502 }
23503 else {
23504 pragmas.push({ name: name, args: { arguments: {}, range: range } });
23505 }
23506 return;
23507 }
23508 var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
23509 if (singleLine) {
23510 return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
23511 }
23512 if (range.kind === 3 /* MultiLineCommentTrivia */) {
23513 var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
23514 var multiLineMatch = void 0;
23515 while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
23516 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
23517 }
23518 }
23519 }
23520 function addPragmaForMatch(pragmas, range, kind, match) {
23521 if (!match)
23522 return;
23523 var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
23524 var pragma = ts.commentPragmas[name];
23525 if (!pragma || !(pragma.kind & kind)) {
23526 return;
23527 }
23528 var args = match[2]; // Split on spaces and match up positionally with definition
23529 var argument = getNamedPragmaArguments(pragma, args);
23530 if (argument === "fail")
23531 return; // Missing required argument, fail to parse it
23532 pragmas.push({ name: name, args: { arguments: argument, range: range } });
23533 return;
23534 }
23535 function getNamedPragmaArguments(pragma, text) {
23536 if (!text)
23537 return {};
23538 if (!pragma.args)
23539 return {};
23540 var args = text.split(/\s+/);
23541 var argMap = {};
23542 for (var i = 0; i < pragma.args.length; i++) {
23543 var argument = pragma.args[i];
23544 if (!args[i] && !argument.optional) {
23545 return "fail";
23546 }
23547 if (argument.captureSpan) {
23548 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
23549 }
23550 argMap[argument.name] = args[i];
23551 }
23552 return argMap;
23553 }
23554 /** @internal */
23555 function tagNamesAreEquivalent(lhs, rhs) {
23556 if (lhs.kind !== rhs.kind) {
23557 return false;
23558 }
23559 if (lhs.kind === 72 /* Identifier */) {
23560 return lhs.escapedText === rhs.escapedText;
23561 }
23562 if (lhs.kind === 100 /* ThisKeyword */) {
23563 return true;
23564 }
23565 // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
23566 // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
23567 // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
23568 return lhs.name.escapedText === rhs.name.escapedText &&
23569 tagNamesAreEquivalent(lhs.expression, rhs.expression);
23570 }
23571 ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
23572})(ts || (ts = {}));
23573var ts;
23574(function (ts) {
23575 /* @internal */
23576 ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
23577 // NOTE: The order here is important to default lib ordering as entries will have the same
23578 // order in the generated program (see `getDefaultLibPriority` in program.ts). This
23579 // order also affects overload resolution when a type declared in one lib is
23580 // augmented in another lib.
23581 var libEntries = [
23582 // JavaScript only
23583 ["es5", "lib.es5.d.ts"],
23584 ["es6", "lib.es2015.d.ts"],
23585 ["es2015", "lib.es2015.d.ts"],
23586 ["es7", "lib.es2016.d.ts"],
23587 ["es2016", "lib.es2016.d.ts"],
23588 ["es2017", "lib.es2017.d.ts"],
23589 ["es2018", "lib.es2018.d.ts"],
23590 ["es2019", "lib.es2019.d.ts"],
23591 ["esnext", "lib.esnext.d.ts"],
23592 // Host only
23593 ["dom", "lib.dom.d.ts"],
23594 ["dom.iterable", "lib.dom.iterable.d.ts"],
23595 ["webworker", "lib.webworker.d.ts"],
23596 ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
23597 ["scripthost", "lib.scripthost.d.ts"],
23598 // ES2015 Or ESNext By-feature options
23599 ["es2015.core", "lib.es2015.core.d.ts"],
23600 ["es2015.collection", "lib.es2015.collection.d.ts"],
23601 ["es2015.generator", "lib.es2015.generator.d.ts"],
23602 ["es2015.iterable", "lib.es2015.iterable.d.ts"],
23603 ["es2015.promise", "lib.es2015.promise.d.ts"],
23604 ["es2015.proxy", "lib.es2015.proxy.d.ts"],
23605 ["es2015.reflect", "lib.es2015.reflect.d.ts"],
23606 ["es2015.symbol", "lib.es2015.symbol.d.ts"],
23607 ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
23608 ["es2016.array.include", "lib.es2016.array.include.d.ts"],
23609 ["es2017.object", "lib.es2017.object.d.ts"],
23610 ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
23611 ["es2017.string", "lib.es2017.string.d.ts"],
23612 ["es2017.intl", "lib.es2017.intl.d.ts"],
23613 ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
23614 ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
23615 ["es2018.intl", "lib.es2018.intl.d.ts"],
23616 ["es2018.promise", "lib.es2018.promise.d.ts"],
23617 ["es2018.regexp", "lib.es2018.regexp.d.ts"],
23618 ["es2019.array", "lib.es2019.array.d.ts"],
23619 ["es2019.string", "lib.es2019.string.d.ts"],
23620 ["es2019.symbol", "lib.es2019.symbol.d.ts"],
23621 ["esnext.array", "lib.es2019.array.d.ts"],
23622 ["esnext.symbol", "lib.es2019.symbol.d.ts"],
23623 ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
23624 ["esnext.intl", "lib.esnext.intl.d.ts"],
23625 ["esnext.bigint", "lib.esnext.bigint.d.ts"]
23626 ];
23627 /**
23628 * An array of supported "lib" reference file names used to determine the order for inclusion
23629 * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
23630 * overload resolution when a type declared in one lib is extended by another.
23631 */
23632 /* @internal */
23633 ts.libs = libEntries.map(function (entry) { return entry[0]; });
23634 /**
23635 * A map of lib names to lib files. This map is used both for parsing the "lib" command line
23636 * option as well as for resolving lib reference directives.
23637 */
23638 /* @internal */
23639 ts.libMap = ts.createMapFromEntries(libEntries);
23640 /* @internal */
23641 ts.commonOptionsWithBuild = [
23642 {
23643 name: "help",
23644 shortName: "h",
23645 type: "boolean",
23646 showInSimplifiedHelpView: true,
23647 category: ts.Diagnostics.Command_line_Options,
23648 description: ts.Diagnostics.Print_this_message,
23649 },
23650 {
23651 name: "help",
23652 shortName: "?",
23653 type: "boolean"
23654 },
23655 {
23656 name: "watch",
23657 shortName: "w",
23658 type: "boolean",
23659 showInSimplifiedHelpView: true,
23660 category: ts.Diagnostics.Command_line_Options,
23661 description: ts.Diagnostics.Watch_input_files,
23662 },
23663 {
23664 name: "preserveWatchOutput",
23665 type: "boolean",
23666 showInSimplifiedHelpView: false,
23667 category: ts.Diagnostics.Command_line_Options,
23668 description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
23669 },
23670 {
23671 name: "listFiles",
23672 type: "boolean",
23673 category: ts.Diagnostics.Advanced_Options,
23674 description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
23675 },
23676 {
23677 name: "listEmittedFiles",
23678 type: "boolean",
23679 category: ts.Diagnostics.Advanced_Options,
23680 description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
23681 },
23682 {
23683 name: "pretty",
23684 type: "boolean",
23685 showInSimplifiedHelpView: true,
23686 category: ts.Diagnostics.Command_line_Options,
23687 description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
23688 },
23689 {
23690 name: "traceResolution",
23691 type: "boolean",
23692 category: ts.Diagnostics.Advanced_Options,
23693 description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
23694 },
23695 {
23696 name: "diagnostics",
23697 type: "boolean",
23698 category: ts.Diagnostics.Advanced_Options,
23699 description: ts.Diagnostics.Show_diagnostic_information
23700 },
23701 {
23702 name: "extendedDiagnostics",
23703 type: "boolean",
23704 category: ts.Diagnostics.Advanced_Options,
23705 description: ts.Diagnostics.Show_verbose_diagnostic_information
23706 },
23707 ];
23708 /* @internal */
23709 ts.optionDeclarations = ts.commonOptionsWithBuild.concat([
23710 {
23711 name: "all",
23712 type: "boolean",
23713 showInSimplifiedHelpView: true,
23714 category: ts.Diagnostics.Command_line_Options,
23715 description: ts.Diagnostics.Show_all_compiler_options,
23716 },
23717 {
23718 name: "version",
23719 shortName: "v",
23720 type: "boolean",
23721 showInSimplifiedHelpView: true,
23722 category: ts.Diagnostics.Command_line_Options,
23723 description: ts.Diagnostics.Print_the_compiler_s_version,
23724 },
23725 {
23726 name: "init",
23727 type: "boolean",
23728 showInSimplifiedHelpView: true,
23729 category: ts.Diagnostics.Command_line_Options,
23730 description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
23731 },
23732 {
23733 name: "project",
23734 shortName: "p",
23735 type: "string",
23736 isFilePath: true,
23737 showInSimplifiedHelpView: true,
23738 category: ts.Diagnostics.Command_line_Options,
23739 paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
23740 description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
23741 },
23742 {
23743 name: "build",
23744 type: "boolean",
23745 shortName: "b",
23746 showInSimplifiedHelpView: true,
23747 category: ts.Diagnostics.Command_line_Options,
23748 description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
23749 },
23750 {
23751 name: "showConfig",
23752 type: "boolean",
23753 category: ts.Diagnostics.Command_line_Options,
23754 isCommandLineOnly: true,
23755 description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
23756 },
23757 // Basic
23758 {
23759 name: "target",
23760 shortName: "t",
23761 type: ts.createMapFromTemplate({
23762 es3: 0 /* ES3 */,
23763 es5: 1 /* ES5 */,
23764 es6: 2 /* ES2015 */,
23765 es2015: 2 /* ES2015 */,
23766 es2016: 3 /* ES2016 */,
23767 es2017: 4 /* ES2017 */,
23768 es2018: 5 /* ES2018 */,
23769 es2019: 6 /* ES2019 */,
23770 esnext: 7 /* ESNext */,
23771 }),
23772 affectsSourceFile: true,
23773 affectsModuleResolution: true,
23774 paramType: ts.Diagnostics.VERSION,
23775 showInSimplifiedHelpView: true,
23776 category: ts.Diagnostics.Basic_Options,
23777 description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT,
23778 },
23779 {
23780 name: "module",
23781 shortName: "m",
23782 type: ts.createMapFromTemplate({
23783 none: ts.ModuleKind.None,
23784 commonjs: ts.ModuleKind.CommonJS,
23785 amd: ts.ModuleKind.AMD,
23786 system: ts.ModuleKind.System,
23787 umd: ts.ModuleKind.UMD,
23788 es6: ts.ModuleKind.ES2015,
23789 es2015: ts.ModuleKind.ES2015,
23790 esnext: ts.ModuleKind.ESNext
23791 }),
23792 affectsModuleResolution: true,
23793 paramType: ts.Diagnostics.KIND,
23794 showInSimplifiedHelpView: true,
23795 category: ts.Diagnostics.Basic_Options,
23796 description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext,
23797 },
23798 {
23799 name: "lib",
23800 type: "list",
23801 element: {
23802 name: "lib",
23803 type: ts.libMap
23804 },
23805 affectsModuleResolution: true,
23806 showInSimplifiedHelpView: true,
23807 category: ts.Diagnostics.Basic_Options,
23808 description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation
23809 },
23810 {
23811 name: "allowJs",
23812 type: "boolean",
23813 affectsModuleResolution: true,
23814 showInSimplifiedHelpView: true,
23815 category: ts.Diagnostics.Basic_Options,
23816 description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
23817 },
23818 {
23819 name: "checkJs",
23820 type: "boolean",
23821 category: ts.Diagnostics.Basic_Options,
23822 description: ts.Diagnostics.Report_errors_in_js_files
23823 },
23824 {
23825 name: "jsx",
23826 type: ts.createMapFromTemplate({
23827 "preserve": 1 /* Preserve */,
23828 "react-native": 3 /* ReactNative */,
23829 "react": 2 /* React */
23830 }),
23831 affectsSourceFile: true,
23832 paramType: ts.Diagnostics.KIND,
23833 showInSimplifiedHelpView: true,
23834 category: ts.Diagnostics.Basic_Options,
23835 description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
23836 },
23837 {
23838 name: "declaration",
23839 shortName: "d",
23840 type: "boolean",
23841 showInSimplifiedHelpView: true,
23842 category: ts.Diagnostics.Basic_Options,
23843 description: ts.Diagnostics.Generates_corresponding_d_ts_file,
23844 },
23845 {
23846 name: "declarationMap",
23847 type: "boolean",
23848 showInSimplifiedHelpView: true,
23849 category: ts.Diagnostics.Basic_Options,
23850 description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
23851 },
23852 {
23853 name: "emitDeclarationOnly",
23854 type: "boolean",
23855 category: ts.Diagnostics.Advanced_Options,
23856 description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
23857 },
23858 {
23859 name: "sourceMap",
23860 type: "boolean",
23861 showInSimplifiedHelpView: true,
23862 category: ts.Diagnostics.Basic_Options,
23863 description: ts.Diagnostics.Generates_corresponding_map_file,
23864 },
23865 {
23866 name: "outFile",
23867 type: "string",
23868 isFilePath: true,
23869 paramType: ts.Diagnostics.FILE,
23870 showInSimplifiedHelpView: true,
23871 category: ts.Diagnostics.Basic_Options,
23872 description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
23873 },
23874 {
23875 name: "outDir",
23876 type: "string",
23877 isFilePath: true,
23878 paramType: ts.Diagnostics.DIRECTORY,
23879 showInSimplifiedHelpView: true,
23880 category: ts.Diagnostics.Basic_Options,
23881 description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
23882 },
23883 {
23884 name: "rootDir",
23885 type: "string",
23886 isFilePath: true,
23887 paramType: ts.Diagnostics.LOCATION,
23888 category: ts.Diagnostics.Basic_Options,
23889 description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
23890 },
23891 {
23892 name: "composite",
23893 type: "boolean",
23894 isTSConfigOnly: true,
23895 category: ts.Diagnostics.Basic_Options,
23896 description: ts.Diagnostics.Enable_project_compilation,
23897 },
23898 {
23899 name: "incremental",
23900 type: "boolean",
23901 isTSConfigOnly: true,
23902 category: ts.Diagnostics.Basic_Options,
23903 description: ts.Diagnostics.Enable_incremental_compilation,
23904 },
23905 {
23906 name: "tsBuildInfoFile",
23907 type: "string",
23908 isFilePath: true,
23909 paramType: ts.Diagnostics.FILE,
23910 isTSConfigOnly: true,
23911 category: ts.Diagnostics.Basic_Options,
23912 description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
23913 },
23914 {
23915 name: "removeComments",
23916 type: "boolean",
23917 showInSimplifiedHelpView: true,
23918 category: ts.Diagnostics.Basic_Options,
23919 description: ts.Diagnostics.Do_not_emit_comments_to_output,
23920 },
23921 {
23922 name: "noEmit",
23923 type: "boolean",
23924 showInSimplifiedHelpView: true,
23925 category: ts.Diagnostics.Basic_Options,
23926 description: ts.Diagnostics.Do_not_emit_outputs,
23927 },
23928 {
23929 name: "importHelpers",
23930 type: "boolean",
23931 category: ts.Diagnostics.Basic_Options,
23932 description: ts.Diagnostics.Import_emit_helpers_from_tslib
23933 },
23934 {
23935 name: "downlevelIteration",
23936 type: "boolean",
23937 category: ts.Diagnostics.Basic_Options,
23938 description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
23939 },
23940 {
23941 name: "isolatedModules",
23942 type: "boolean",
23943 category: ts.Diagnostics.Basic_Options,
23944 description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule
23945 },
23946 // Strict Type Checks
23947 {
23948 name: "strict",
23949 type: "boolean",
23950 showInSimplifiedHelpView: true,
23951 category: ts.Diagnostics.Strict_Type_Checking_Options,
23952 description: ts.Diagnostics.Enable_all_strict_type_checking_options
23953 },
23954 {
23955 name: "noImplicitAny",
23956 type: "boolean",
23957 affectsSemanticDiagnostics: true,
23958 strictFlag: true,
23959 showInSimplifiedHelpView: true,
23960 category: ts.Diagnostics.Strict_Type_Checking_Options,
23961 description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
23962 },
23963 {
23964 name: "strictNullChecks",
23965 type: "boolean",
23966 affectsSemanticDiagnostics: true,
23967 strictFlag: true,
23968 showInSimplifiedHelpView: true,
23969 category: ts.Diagnostics.Strict_Type_Checking_Options,
23970 description: ts.Diagnostics.Enable_strict_null_checks
23971 },
23972 {
23973 name: "strictFunctionTypes",
23974 type: "boolean",
23975 affectsSemanticDiagnostics: true,
23976 strictFlag: true,
23977 showInSimplifiedHelpView: true,
23978 category: ts.Diagnostics.Strict_Type_Checking_Options,
23979 description: ts.Diagnostics.Enable_strict_checking_of_function_types
23980 },
23981 {
23982 name: "strictBindCallApply",
23983 type: "boolean",
23984 strictFlag: true,
23985 showInSimplifiedHelpView: true,
23986 category: ts.Diagnostics.Strict_Type_Checking_Options,
23987 description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
23988 },
23989 {
23990 name: "strictPropertyInitialization",
23991 type: "boolean",
23992 affectsSemanticDiagnostics: true,
23993 strictFlag: true,
23994 showInSimplifiedHelpView: true,
23995 category: ts.Diagnostics.Strict_Type_Checking_Options,
23996 description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
23997 },
23998 {
23999 name: "noImplicitThis",
24000 type: "boolean",
24001 affectsSemanticDiagnostics: true,
24002 strictFlag: true,
24003 showInSimplifiedHelpView: true,
24004 category: ts.Diagnostics.Strict_Type_Checking_Options,
24005 description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
24006 },
24007 {
24008 name: "alwaysStrict",
24009 type: "boolean",
24010 affectsSourceFile: true,
24011 strictFlag: true,
24012 showInSimplifiedHelpView: true,
24013 category: ts.Diagnostics.Strict_Type_Checking_Options,
24014 description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
24015 },
24016 // Additional Checks
24017 {
24018 name: "noUnusedLocals",
24019 type: "boolean",
24020 affectsSemanticDiagnostics: true,
24021 showInSimplifiedHelpView: true,
24022 category: ts.Diagnostics.Additional_Checks,
24023 description: ts.Diagnostics.Report_errors_on_unused_locals,
24024 },
24025 {
24026 name: "noUnusedParameters",
24027 type: "boolean",
24028 affectsSemanticDiagnostics: true,
24029 showInSimplifiedHelpView: true,
24030 category: ts.Diagnostics.Additional_Checks,
24031 description: ts.Diagnostics.Report_errors_on_unused_parameters,
24032 },
24033 {
24034 name: "noImplicitReturns",
24035 type: "boolean",
24036 affectsSemanticDiagnostics: true,
24037 showInSimplifiedHelpView: true,
24038 category: ts.Diagnostics.Additional_Checks,
24039 description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
24040 },
24041 {
24042 name: "noFallthroughCasesInSwitch",
24043 type: "boolean",
24044 affectsBindDiagnostics: true,
24045 affectsSemanticDiagnostics: true,
24046 showInSimplifiedHelpView: true,
24047 category: ts.Diagnostics.Additional_Checks,
24048 description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
24049 },
24050 // Module Resolution
24051 {
24052 name: "moduleResolution",
24053 type: ts.createMapFromTemplate({
24054 node: ts.ModuleResolutionKind.NodeJs,
24055 classic: ts.ModuleResolutionKind.Classic,
24056 }),
24057 affectsModuleResolution: true,
24058 paramType: ts.Diagnostics.STRATEGY,
24059 category: ts.Diagnostics.Module_Resolution_Options,
24060 description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
24061 },
24062 {
24063 name: "baseUrl",
24064 type: "string",
24065 affectsModuleResolution: true,
24066 isFilePath: true,
24067 category: ts.Diagnostics.Module_Resolution_Options,
24068 description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
24069 },
24070 {
24071 // this option can only be specified in tsconfig.json
24072 // use type = object to copy the value as-is
24073 name: "paths",
24074 type: "object",
24075 affectsModuleResolution: true,
24076 isTSConfigOnly: true,
24077 category: ts.Diagnostics.Module_Resolution_Options,
24078 description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl
24079 },
24080 {
24081 // this option can only be specified in tsconfig.json
24082 // use type = object to copy the value as-is
24083 name: "rootDirs",
24084 type: "list",
24085 isTSConfigOnly: true,
24086 element: {
24087 name: "rootDirs",
24088 type: "string",
24089 isFilePath: true
24090 },
24091 affectsModuleResolution: true,
24092 category: ts.Diagnostics.Module_Resolution_Options,
24093 description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime
24094 },
24095 {
24096 name: "typeRoots",
24097 type: "list",
24098 element: {
24099 name: "typeRoots",
24100 type: "string",
24101 isFilePath: true
24102 },
24103 affectsModuleResolution: true,
24104 category: ts.Diagnostics.Module_Resolution_Options,
24105 description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
24106 },
24107 {
24108 name: "types",
24109 type: "list",
24110 element: {
24111 name: "types",
24112 type: "string"
24113 },
24114 affectsModuleResolution: true,
24115 showInSimplifiedHelpView: true,
24116 category: ts.Diagnostics.Module_Resolution_Options,
24117 description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation
24118 },
24119 {
24120 name: "allowSyntheticDefaultImports",
24121 type: "boolean",
24122 affectsSemanticDiagnostics: true,
24123 category: ts.Diagnostics.Module_Resolution_Options,
24124 description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
24125 },
24126 {
24127 name: "esModuleInterop",
24128 type: "boolean",
24129 affectsSemanticDiagnostics: true,
24130 showInSimplifiedHelpView: true,
24131 category: ts.Diagnostics.Module_Resolution_Options,
24132 description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
24133 },
24134 {
24135 name: "preserveSymlinks",
24136 type: "boolean",
24137 category: ts.Diagnostics.Module_Resolution_Options,
24138 description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
24139 },
24140 // Source Maps
24141 {
24142 name: "sourceRoot",
24143 type: "string",
24144 paramType: ts.Diagnostics.LOCATION,
24145 category: ts.Diagnostics.Source_Map_Options,
24146 description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
24147 },
24148 {
24149 name: "mapRoot",
24150 type: "string",
24151 paramType: ts.Diagnostics.LOCATION,
24152 category: ts.Diagnostics.Source_Map_Options,
24153 description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
24154 },
24155 {
24156 name: "inlineSourceMap",
24157 type: "boolean",
24158 category: ts.Diagnostics.Source_Map_Options,
24159 description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
24160 },
24161 {
24162 name: "inlineSources",
24163 type: "boolean",
24164 category: ts.Diagnostics.Source_Map_Options,
24165 description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
24166 },
24167 // Experimental
24168 {
24169 name: "experimentalDecorators",
24170 type: "boolean",
24171 category: ts.Diagnostics.Experimental_Options,
24172 description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
24173 },
24174 {
24175 name: "emitDecoratorMetadata",
24176 type: "boolean",
24177 category: ts.Diagnostics.Experimental_Options,
24178 description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
24179 },
24180 // Advanced
24181 {
24182 name: "jsxFactory",
24183 type: "string",
24184 category: ts.Diagnostics.Advanced_Options,
24185 description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
24186 },
24187 {
24188 name: "resolveJsonModule",
24189 type: "boolean",
24190 category: ts.Diagnostics.Advanced_Options,
24191 description: ts.Diagnostics.Include_modules_imported_with_json_extension
24192 },
24193 {
24194 name: "out",
24195 type: "string",
24196 isFilePath: false,
24197 // for correct behaviour, please use outFile
24198 category: ts.Diagnostics.Advanced_Options,
24199 paramType: ts.Diagnostics.FILE,
24200 description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
24201 },
24202 {
24203 name: "reactNamespace",
24204 type: "string",
24205 category: ts.Diagnostics.Advanced_Options,
24206 description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
24207 },
24208 {
24209 name: "skipDefaultLibCheck",
24210 type: "boolean",
24211 category: ts.Diagnostics.Advanced_Options,
24212 description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
24213 },
24214 {
24215 name: "charset",
24216 type: "string",
24217 category: ts.Diagnostics.Advanced_Options,
24218 description: ts.Diagnostics.The_character_set_of_the_input_files
24219 },
24220 {
24221 name: "emitBOM",
24222 type: "boolean",
24223 category: ts.Diagnostics.Advanced_Options,
24224 description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
24225 },
24226 {
24227 name: "locale",
24228 type: "string",
24229 category: ts.Diagnostics.Advanced_Options,
24230 description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
24231 },
24232 {
24233 name: "newLine",
24234 type: ts.createMapFromTemplate({
24235 crlf: 0 /* CarriageReturnLineFeed */,
24236 lf: 1 /* LineFeed */
24237 }),
24238 paramType: ts.Diagnostics.NEWLINE,
24239 category: ts.Diagnostics.Advanced_Options,
24240 description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
24241 },
24242 {
24243 name: "noErrorTruncation",
24244 type: "boolean",
24245 category: ts.Diagnostics.Advanced_Options,
24246 description: ts.Diagnostics.Do_not_truncate_error_messages
24247 },
24248 {
24249 name: "noLib",
24250 type: "boolean",
24251 affectsModuleResolution: true,
24252 category: ts.Diagnostics.Advanced_Options,
24253 description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts
24254 },
24255 {
24256 name: "noResolve",
24257 type: "boolean",
24258 affectsModuleResolution: true,
24259 category: ts.Diagnostics.Advanced_Options,
24260 description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files
24261 },
24262 {
24263 name: "stripInternal",
24264 type: "boolean",
24265 category: ts.Diagnostics.Advanced_Options,
24266 description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
24267 },
24268 {
24269 name: "disableSizeLimit",
24270 type: "boolean",
24271 affectsSourceFile: true,
24272 category: ts.Diagnostics.Advanced_Options,
24273 description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
24274 },
24275 {
24276 name: "noImplicitUseStrict",
24277 type: "boolean",
24278 affectsSemanticDiagnostics: true,
24279 category: ts.Diagnostics.Advanced_Options,
24280 description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
24281 },
24282 {
24283 name: "noEmitHelpers",
24284 type: "boolean",
24285 category: ts.Diagnostics.Advanced_Options,
24286 description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
24287 },
24288 {
24289 name: "noEmitOnError",
24290 type: "boolean",
24291 category: ts.Diagnostics.Advanced_Options,
24292 description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
24293 },
24294 {
24295 name: "preserveConstEnums",
24296 type: "boolean",
24297 category: ts.Diagnostics.Advanced_Options,
24298 description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
24299 },
24300 {
24301 name: "declarationDir",
24302 type: "string",
24303 isFilePath: true,
24304 paramType: ts.Diagnostics.DIRECTORY,
24305 category: ts.Diagnostics.Advanced_Options,
24306 description: ts.Diagnostics.Output_directory_for_generated_declaration_files
24307 },
24308 {
24309 name: "skipLibCheck",
24310 type: "boolean",
24311 category: ts.Diagnostics.Advanced_Options,
24312 description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
24313 },
24314 {
24315 name: "allowUnusedLabels",
24316 type: "boolean",
24317 affectsBindDiagnostics: true,
24318 affectsSemanticDiagnostics: true,
24319 category: ts.Diagnostics.Advanced_Options,
24320 description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
24321 },
24322 {
24323 name: "allowUnreachableCode",
24324 type: "boolean",
24325 affectsBindDiagnostics: true,
24326 affectsSemanticDiagnostics: true,
24327 category: ts.Diagnostics.Advanced_Options,
24328 description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
24329 },
24330 {
24331 name: "suppressExcessPropertyErrors",
24332 type: "boolean",
24333 affectsSemanticDiagnostics: true,
24334 category: ts.Diagnostics.Advanced_Options,
24335 description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
24336 },
24337 {
24338 name: "suppressImplicitAnyIndexErrors",
24339 type: "boolean",
24340 affectsSemanticDiagnostics: true,
24341 category: ts.Diagnostics.Advanced_Options,
24342 description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
24343 },
24344 {
24345 name: "forceConsistentCasingInFileNames",
24346 type: "boolean",
24347 category: ts.Diagnostics.Advanced_Options,
24348 description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
24349 },
24350 {
24351 name: "maxNodeModuleJsDepth",
24352 type: "number",
24353 affectsModuleResolution: true,
24354 category: ts.Diagnostics.Advanced_Options,
24355 description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
24356 },
24357 {
24358 name: "noStrictGenericChecks",
24359 type: "boolean",
24360 affectsSemanticDiagnostics: true,
24361 category: ts.Diagnostics.Advanced_Options,
24362 description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
24363 },
24364 {
24365 name: "keyofStringsOnly",
24366 type: "boolean",
24367 category: ts.Diagnostics.Advanced_Options,
24368 description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
24369 },
24370 {
24371 // A list of plugins to load in the language service
24372 name: "plugins",
24373 type: "list",
24374 isTSConfigOnly: true,
24375 element: {
24376 name: "plugin",
24377 type: "object"
24378 },
24379 description: ts.Diagnostics.List_of_language_service_plugins
24380 }
24381 ]);
24382 /* @internal */
24383 ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
24384 /* @internal */
24385 ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
24386 /* @internal */
24387 ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
24388 return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
24389 });
24390 /* @internal */
24391 ts.buildOpts = ts.commonOptionsWithBuild.concat([
24392 {
24393 name: "verbose",
24394 shortName: "v",
24395 category: ts.Diagnostics.Command_line_Options,
24396 description: ts.Diagnostics.Enable_verbose_logging,
24397 type: "boolean"
24398 },
24399 {
24400 name: "dry",
24401 shortName: "d",
24402 category: ts.Diagnostics.Command_line_Options,
24403 description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
24404 type: "boolean"
24405 },
24406 {
24407 name: "force",
24408 shortName: "f",
24409 category: ts.Diagnostics.Command_line_Options,
24410 description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
24411 type: "boolean"
24412 },
24413 {
24414 name: "clean",
24415 category: ts.Diagnostics.Command_line_Options,
24416 description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
24417 type: "boolean"
24418 }
24419 ]);
24420 /* @internal */
24421 ts.typeAcquisitionDeclarations = [
24422 {
24423 /* @deprecated typingOptions.enableAutoDiscovery
24424 * Use typeAcquisition.enable instead.
24425 */
24426 name: "enableAutoDiscovery",
24427 type: "boolean",
24428 },
24429 {
24430 name: "enable",
24431 type: "boolean",
24432 },
24433 {
24434 name: "include",
24435 type: "list",
24436 element: {
24437 name: "include",
24438 type: "string"
24439 }
24440 },
24441 {
24442 name: "exclude",
24443 type: "list",
24444 element: {
24445 name: "exclude",
24446 type: "string"
24447 }
24448 }
24449 ];
24450 /* @internal */
24451 ts.defaultInitCompilerOptions = {
24452 module: ts.ModuleKind.CommonJS,
24453 target: 1 /* ES5 */,
24454 strict: true,
24455 esModuleInterop: true
24456 };
24457 var optionNameMapCache;
24458 /* @internal */
24459 function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
24460 // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
24461 if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
24462 return {
24463 enable: typeAcquisition.enableAutoDiscovery,
24464 include: typeAcquisition.include || [],
24465 exclude: typeAcquisition.exclude || []
24466 };
24467 }
24468 return typeAcquisition;
24469 }
24470 ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
24471 function getOptionNameMap() {
24472 return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations));
24473 }
24474 /*@internal*/
24475 function createOptionNameMap(optionDeclarations) {
24476 var optionNameMap = ts.createMap();
24477 var shortOptionNames = ts.createMap();
24478 ts.forEach(optionDeclarations, function (option) {
24479 optionNameMap.set(option.name.toLowerCase(), option);
24480 if (option.shortName) {
24481 shortOptionNames.set(option.shortName, option.name);
24482 }
24483 });
24484 return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames };
24485 }
24486 ts.createOptionNameMap = createOptionNameMap;
24487 /* @internal */
24488 function createCompilerDiagnosticForInvalidCustomType(opt) {
24489 return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
24490 }
24491 ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
24492 function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
24493 var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
24494 return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
24495 }
24496 /* @internal */
24497 function parseCustomTypeOption(opt, value, errors) {
24498 return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
24499 }
24500 ts.parseCustomTypeOption = parseCustomTypeOption;
24501 /* @internal */
24502 function parseListTypeOption(opt, value, errors) {
24503 if (value === void 0) { value = ""; }
24504 value = trimString(value);
24505 if (ts.startsWith(value, "-")) {
24506 return undefined;
24507 }
24508 if (value === "") {
24509 return [];
24510 }
24511 var values = value.split(",");
24512 switch (opt.element.type) {
24513 case "number":
24514 return ts.map(values, parseInt);
24515 case "string":
24516 return ts.map(values, function (v) { return v || ""; });
24517 default:
24518 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
24519 }
24520 }
24521 ts.parseListTypeOption = parseListTypeOption;
24522 function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) {
24523 var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1];
24524 var options = {};
24525 var fileNames = [];
24526 var errors = [];
24527 parseStrings(commandLine);
24528 return {
24529 options: options,
24530 fileNames: fileNames,
24531 errors: errors
24532 };
24533 function parseStrings(args) {
24534 var i = 0;
24535 while (i < args.length) {
24536 var s = args[i];
24537 i++;
24538 if (s.charCodeAt(0) === 64 /* at */) {
24539 parseResponseFile(s.slice(1));
24540 }
24541 else if (s.charCodeAt(0) === 45 /* minus */) {
24542 var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true);
24543 if (opt) {
24544 if (opt.isTSConfigOnly) {
24545 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name));
24546 }
24547 else {
24548 // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
24549 if (!args[i] && opt.type !== "boolean") {
24550 errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name));
24551 }
24552 switch (opt.type) {
24553 case "number":
24554 options[opt.name] = parseInt(args[i]);
24555 i++;
24556 break;
24557 case "boolean":
24558 // boolean flag has optional value true, false, others
24559 var optValue = args[i];
24560 options[opt.name] = optValue !== "false";
24561 // consume next argument as boolean flag value
24562 if (optValue === "false" || optValue === "true") {
24563 i++;
24564 }
24565 break;
24566 case "string":
24567 options[opt.name] = args[i] || "";
24568 i++;
24569 break;
24570 case "list":
24571 var result = parseListTypeOption(opt, args[i], errors);
24572 options[opt.name] = result || [];
24573 if (result) {
24574 i++;
24575 }
24576 break;
24577 // If not a primitive, the possible types are specified in what is effectively a map of options.
24578 default:
24579 options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
24580 i++;
24581 break;
24582 }
24583 }
24584 }
24585 else {
24586 errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s));
24587 }
24588 }
24589 else {
24590 fileNames.push(s);
24591 }
24592 }
24593 }
24594 function parseResponseFile(fileName) {
24595 var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName);
24596 if (!text) {
24597 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName));
24598 return;
24599 }
24600 var args = [];
24601 var pos = 0;
24602 while (true) {
24603 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
24604 pos++;
24605 if (pos >= text.length)
24606 break;
24607 var start = pos;
24608 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
24609 pos++;
24610 while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
24611 pos++;
24612 if (pos < text.length) {
24613 args.push(text.substring(start + 1, pos));
24614 pos++;
24615 }
24616 else {
24617 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
24618 }
24619 }
24620 else {
24621 while (text.charCodeAt(pos) > 32 /* space */)
24622 pos++;
24623 args.push(text.substring(start, pos));
24624 }
24625 }
24626 parseStrings(args);
24627 }
24628 }
24629 function parseCommandLine(commandLine, readFile) {
24630 return parseCommandLineWorker(getOptionNameMap, [
24631 ts.Diagnostics.Unknown_compiler_option_0,
24632 ts.Diagnostics.Compiler_option_0_expects_an_argument
24633 ], commandLine, readFile);
24634 }
24635 ts.parseCommandLine = parseCommandLine;
24636 /** @internal */
24637 function getOptionFromName(optionName, allowShort) {
24638 return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort);
24639 }
24640 ts.getOptionFromName = getOptionFromName;
24641 function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
24642 if (allowShort === void 0) { allowShort = false; }
24643 optionName = optionName.toLowerCase();
24644 var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames;
24645 // Try to translate short option names to their full equivalents.
24646 if (allowShort) {
24647 var short = shortOptionNames.get(optionName);
24648 if (short !== undefined) {
24649 optionName = short;
24650 }
24651 }
24652 return optionNameMap.get(optionName);
24653 }
24654 /*@internal*/
24655 function parseBuildCommand(args) {
24656 var buildOptionNameMap;
24657 var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); };
24658 var _a = parseCommandLineWorker(returnBuildOptionNameMap, [
24659 ts.Diagnostics.Unknown_build_option_0,
24660 ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
24661 ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors;
24662 var buildOptions = options;
24663 if (projects.length === 0) {
24664 // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
24665 projects.push(".");
24666 }
24667 // Nonsensical combinations
24668 if (buildOptions.clean && buildOptions.force) {
24669 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
24670 }
24671 if (buildOptions.clean && buildOptions.verbose) {
24672 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
24673 }
24674 if (buildOptions.clean && buildOptions.watch) {
24675 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
24676 }
24677 if (buildOptions.watch && buildOptions.dry) {
24678 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
24679 }
24680 return { buildOptions: buildOptions, projects: projects, errors: errors };
24681 }
24682 ts.parseBuildCommand = parseBuildCommand;
24683 function getDiagnosticText(_message) {
24684 var _args = [];
24685 for (var _i = 1; _i < arguments.length; _i++) {
24686 _args[_i - 1] = arguments[_i];
24687 }
24688 var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
24689 return diagnostic.messageText;
24690 }
24691 /* @internal */
24692 function printVersion() {
24693 ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine);
24694 }
24695 ts.printVersion = printVersion;
24696 /* @internal */
24697 function printHelp(optionsList, syntaxPrefix) {
24698 if (syntaxPrefix === void 0) { syntaxPrefix = ""; }
24699 var output = [];
24700 // We want to align our "syntax" and "examples" commands to a certain margin.
24701 var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length;
24702 var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length;
24703 var marginLength = Math.max(syntaxLength, examplesLength);
24704 // Build up the syntactic skeleton.
24705 var syntax = makePadding(marginLength - syntaxLength);
24706 syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]";
24707 output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax));
24708 output.push(ts.sys.newLine + ts.sys.newLine);
24709 // Build up the list of examples.
24710 var padding = makePadding(marginLength);
24711 output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine);
24712 output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine);
24713 output.push(padding + "tsc @args.txt" + ts.sys.newLine);
24714 output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine);
24715 output.push(ts.sys.newLine);
24716 output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine);
24717 // We want our descriptions to align at the same column in our output,
24718 // so we keep track of the longest option usage string.
24719 marginLength = 0;
24720 var usageColumn = []; // Things like "-d, --declaration" go in here.
24721 var descriptionColumn = [];
24722 var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind
24723 for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) {
24724 var option = optionsList_1[_i];
24725 // If an option lacks a description,
24726 // it is not officially supported.
24727 if (!option.description) {
24728 continue;
24729 }
24730 var usageText_1 = " ";
24731 if (option.shortName) {
24732 usageText_1 += "-" + option.shortName;
24733 usageText_1 += getParamType(option);
24734 usageText_1 += ", ";
24735 }
24736 usageText_1 += "--" + option.name;
24737 usageText_1 += getParamType(option);
24738 usageColumn.push(usageText_1);
24739 var description = void 0;
24740 if (option.name === "lib") {
24741 description = getDiagnosticText(option.description);
24742 var element = option.element;
24743 var typeMap = element.type;
24744 optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; }));
24745 }
24746 else {
24747 description = getDiagnosticText(option.description);
24748 }
24749 descriptionColumn.push(description);
24750 // Set the new margin for the description column if necessary.
24751 marginLength = Math.max(usageText_1.length, marginLength);
24752 }
24753 // Special case that can't fit in the loop.
24754 var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">";
24755 usageColumn.push(usageText);
24756 descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file));
24757 marginLength = Math.max(usageText.length, marginLength);
24758 // Print out each row, aligning all the descriptions on the same column.
24759 for (var i = 0; i < usageColumn.length; i++) {
24760 var usage = usageColumn[i];
24761 var description = descriptionColumn[i];
24762 var kindsList = optionsDescriptionMap.get(description);
24763 output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine);
24764 if (kindsList) {
24765 output.push(makePadding(marginLength + 4));
24766 for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) {
24767 var kind = kindsList_1[_a];
24768 output.push(kind + " ");
24769 }
24770 output.push(ts.sys.newLine);
24771 }
24772 }
24773 for (var _b = 0, output_1 = output; _b < output_1.length; _b++) {
24774 var line = output_1[_b];
24775 ts.sys.write(line);
24776 }
24777 return;
24778 function getParamType(option) {
24779 if (option.paramType !== undefined) {
24780 return " " + getDiagnosticText(option.paramType);
24781 }
24782 return "";
24783 }
24784 function makePadding(paddingLength) {
24785 return Array(paddingLength + 1).join(" ");
24786 }
24787 }
24788 ts.printHelp = printHelp;
24789 /**
24790 * Reads the config file, reports errors if any and exits if the config file cannot be found
24791 */
24792 function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
24793 var configFileText;
24794 try {
24795 configFileText = host.readFile(configFileName);
24796 }
24797 catch (e) {
24798 var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
24799 host.onUnRecoverableConfigFileDiagnostic(error);
24800 return undefined;
24801 }
24802 if (!configFileText) {
24803 var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
24804 host.onUnRecoverableConfigFileDiagnostic(error);
24805 return undefined;
24806 }
24807 var result = ts.parseJsonText(configFileName, configFileText);
24808 var cwd = host.getCurrentDirectory();
24809 result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
24810 result.resolvedPath = result.path;
24811 result.originalFileName = result.fileName;
24812 return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
24813 }
24814 ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
24815 /**
24816 * Read tsconfig.json file
24817 * @param fileName The path to the config file
24818 */
24819 function readConfigFile(fileName, readFile) {
24820 var textOrDiagnostic = tryReadFile(fileName, readFile);
24821 return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
24822 }
24823 ts.readConfigFile = readConfigFile;
24824 /**
24825 * Parse the text of the tsconfig.json file
24826 * @param fileName The path to the config file
24827 * @param jsonText The text of the config file
24828 */
24829 function parseConfigFileTextToJson(fileName, jsonText) {
24830 var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
24831 return {
24832 config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
24833 error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
24834 };
24835 }
24836 ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
24837 /**
24838 * Read tsconfig.json file
24839 * @param fileName The path to the config file
24840 */
24841 function readJsonConfigFile(fileName, readFile) {
24842 var textOrDiagnostic = tryReadFile(fileName, readFile);
24843 return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
24844 }
24845 ts.readJsonConfigFile = readJsonConfigFile;
24846 function tryReadFile(fileName, readFile) {
24847 var text;
24848 try {
24849 text = readFile(fileName);
24850 }
24851 catch (e) {
24852 return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
24853 }
24854 return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text;
24855 }
24856 function commandLineOptionsToMap(options) {
24857 return ts.arrayToMap(options, function (option) { return option.name; });
24858 }
24859 var _tsconfigRootOptions;
24860 function getTsconfigRootOptionsMap() {
24861 if (_tsconfigRootOptions === undefined) {
24862 _tsconfigRootOptions = {
24863 name: undefined,
24864 type: "object",
24865 elementOptions: commandLineOptionsToMap([
24866 {
24867 name: "compilerOptions",
24868 type: "object",
24869 elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
24870 extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
24871 },
24872 {
24873 name: "typingOptions",
24874 type: "object",
24875 elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
24876 extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
24877 },
24878 {
24879 name: "typeAcquisition",
24880 type: "object",
24881 elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
24882 extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
24883 },
24884 {
24885 name: "extends",
24886 type: "string"
24887 },
24888 {
24889 name: "references",
24890 type: "list",
24891 element: {
24892 name: "references",
24893 type: "object"
24894 }
24895 },
24896 {
24897 name: "files",
24898 type: "list",
24899 element: {
24900 name: "files",
24901 type: "string"
24902 }
24903 },
24904 {
24905 name: "include",
24906 type: "list",
24907 element: {
24908 name: "include",
24909 type: "string"
24910 }
24911 },
24912 {
24913 name: "exclude",
24914 type: "list",
24915 element: {
24916 name: "exclude",
24917 type: "string"
24918 }
24919 },
24920 ts.compileOnSaveCommandLineOption
24921 ])
24922 };
24923 }
24924 return _tsconfigRootOptions;
24925 }
24926 /**
24927 * Convert the json syntax tree into the json value
24928 */
24929 function convertToObject(sourceFile, errors) {
24930 return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
24931 }
24932 ts.convertToObject = convertToObject;
24933 /**
24934 * Convert the json syntax tree into the json value and report errors
24935 * This returns the json value (apart from checking errors) only if returnValue provided is true.
24936 * Otherwise it just checks the errors and returns undefined
24937 */
24938 /*@internal*/
24939 function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
24940 if (!sourceFile.statements.length) {
24941 return returnValue ? {} : undefined;
24942 }
24943 return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
24944 function isRootOptionMap(knownOptions) {
24945 return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
24946 }
24947 function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) {
24948 var result = returnValue ? {} : undefined;
24949 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
24950 var element = _a[_i];
24951 if (element.kind !== 275 /* PropertyAssignment */) {
24952 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
24953 continue;
24954 }
24955 if (element.questionToken) {
24956 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
24957 }
24958 if (!isDoubleQuotedString(element.name)) {
24959 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
24960 }
24961 var textOfKey = ts.getTextOfPropertyName(element.name);
24962 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
24963 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
24964 if (keyText && extraKeyDiagnosticMessage && !option) {
24965 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText));
24966 }
24967 var value = convertPropertyValueToJson(element.initializer, option);
24968 if (typeof keyText !== "undefined") {
24969 if (returnValue) {
24970 result[keyText] = value;
24971 }
24972 // Notify key value set, if user asked for it
24973 if (jsonConversionNotifier &&
24974 // Current callbacks are only on known parent option or if we are setting values in the root
24975 (parentOption || isRootOptionMap(knownOptions))) {
24976 var isValidOptionValue = isCompilerOptionsValue(option, value);
24977 if (parentOption) {
24978 if (isValidOptionValue) {
24979 // Notify option set in the parent if its a valid option value
24980 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
24981 }
24982 }
24983 else if (isRootOptionMap(knownOptions)) {
24984 if (isValidOptionValue) {
24985 // Notify about the valid root key value being set
24986 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
24987 }
24988 else if (!option) {
24989 // Notify about the unknown root key value being set
24990 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
24991 }
24992 }
24993 }
24994 }
24995 }
24996 return result;
24997 }
24998 function convertArrayLiteralExpressionToJson(elements, elementOption) {
24999 if (!returnValue) {
25000 return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
25001 }
25002 // Filter out invalid values
25003 return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
25004 }
25005 function convertPropertyValueToJson(valueExpression, option) {
25006 switch (valueExpression.kind) {
25007 case 102 /* TrueKeyword */:
25008 reportInvalidOptionValue(option && option.type !== "boolean");
25009 return true;
25010 case 87 /* FalseKeyword */:
25011 reportInvalidOptionValue(option && option.type !== "boolean");
25012 return false;
25013 case 96 /* NullKeyword */:
25014 reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
25015 return null; // tslint:disable-line:no-null-keyword
25016 case 10 /* StringLiteral */:
25017 if (!isDoubleQuotedString(valueExpression)) {
25018 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
25019 }
25020 reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
25021 var text = valueExpression.text;
25022 if (option && !ts.isString(option.type)) {
25023 var customOption = option;
25024 // Validate custom option type
25025 if (!customOption.type.has(text.toLowerCase())) {
25026 errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
25027 }
25028 }
25029 return text;
25030 case 8 /* NumericLiteral */:
25031 reportInvalidOptionValue(option && option.type !== "number");
25032 return Number(valueExpression.text);
25033 case 202 /* PrefixUnaryExpression */:
25034 if (valueExpression.operator !== 39 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
25035 break; // not valid JSON syntax
25036 }
25037 reportInvalidOptionValue(option && option.type !== "number");
25038 return -Number(valueExpression.operand.text);
25039 case 188 /* ObjectLiteralExpression */:
25040 reportInvalidOptionValue(option && option.type !== "object");
25041 var objectLiteralExpression = valueExpression;
25042 // Currently having element option declaration in the tsconfig with type "object"
25043 // determines if it needs onSetValidOptionKeyValueInParent callback or not
25044 // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
25045 // that satifies it and need it to modify options set in them (for normalizing file paths)
25046 // vs what we set in the json
25047 // If need arises, we can modify this interface and callbacks as needed
25048 if (option) {
25049 var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name;
25050 return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName);
25051 }
25052 else {
25053 return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined,
25054 /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
25055 }
25056 case 187 /* ArrayLiteralExpression */:
25057 reportInvalidOptionValue(option && option.type !== "list");
25058 return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
25059 }
25060 // Not in expected format
25061 if (option) {
25062 reportInvalidOptionValue(/*isError*/ true);
25063 }
25064 else {
25065 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));
25066 }
25067 return undefined;
25068 function reportInvalidOptionValue(isError) {
25069 if (isError) {
25070 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
25071 }
25072 }
25073 }
25074 function isDoubleQuotedString(node) {
25075 return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
25076 }
25077 }
25078 ts.convertToObjectWorker = convertToObjectWorker;
25079 function getCompilerOptionValueTypeString(option) {
25080 return option.type === "list" ?
25081 "Array" :
25082 ts.isString(option.type) ? option.type : "string";
25083 }
25084 function isCompilerOptionsValue(option, value) {
25085 if (option) {
25086 if (isNullOrUndefined(value))
25087 return true; // All options are undefinable/nullable
25088 if (option.type === "list") {
25089 return ts.isArray(value);
25090 }
25091 var expectedType = ts.isString(option.type) ? option.type : "string";
25092 return typeof value === expectedType;
25093 }
25094 return false;
25095 }
25096 /**
25097 * Generate an uncommented, complete tsconfig for use with "--showConfig"
25098 * @param configParseResult options to be generated into tsconfig.json
25099 * @param configFileName name of the parsed config file - output paths will be generated relative to this
25100 * @param host provides current directory and case sensitivity services
25101 */
25102 /** @internal */
25103 function convertToTSConfig(configParseResult, configFileName, host) {
25104 var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
25105 var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); });
25106 var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
25107 var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
25108 var _a;
25109 return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a)));
25110 }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? {
25111 include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
25112 exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
25113 } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined });
25114 return config;
25115 }
25116 ts.convertToTSConfig = convertToTSConfig;
25117 function filterSameAsDefaultInclude(specs) {
25118 if (!ts.length(specs))
25119 return undefined;
25120 if (ts.length(specs) !== 1)
25121 return specs;
25122 if (specs[0] === "**/*")
25123 return undefined;
25124 return specs;
25125 }
25126 function matchesSpecs(path, includeSpecs, excludeSpecs) {
25127 if (!includeSpecs)
25128 return function (_) { return true; };
25129 var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory());
25130 var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames);
25131 var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames);
25132 if (includeRe) {
25133 if (excludeRe) {
25134 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
25135 }
25136 return function (path) { return !includeRe.test(path); };
25137 }
25138 if (excludeRe) {
25139 return function (path) { return excludeRe.test(path); };
25140 }
25141 return function (_) { return true; };
25142 }
25143 function getCustomTypeMapOfCommandLineOption(optionDefinition) {
25144 if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
25145 // this is of a type CommandLineOptionOfPrimitiveType
25146 return undefined;
25147 }
25148 else if (optionDefinition.type === "list") {
25149 return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
25150 }
25151 else {
25152 return optionDefinition.type;
25153 }
25154 }
25155 function getNameOfCompilerOptionValue(value, customTypeMap) {
25156 // There is a typeMap associated with this command-line option so use it to map value back to its name
25157 return ts.forEachEntry(customTypeMap, function (mapValue, key) {
25158 if (mapValue === value) {
25159 return key;
25160 }
25161 });
25162 }
25163 function serializeCompilerOptions(options, pathOptions) {
25164 var result = ts.createMap();
25165 var optionsNameMap = getOptionNameMap().optionNameMap;
25166 var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
25167 var _loop_3 = function (name) {
25168 if (ts.hasProperty(options, name)) {
25169 // tsconfig only options cannot be specified via command line,
25170 // so we can assume that only types that can appear here string | number | boolean
25171 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
25172 return "continue";
25173 }
25174 var value = options[name];
25175 var optionDefinition = optionsNameMap.get(name.toLowerCase());
25176 if (optionDefinition) {
25177 var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
25178 if (!customTypeMap_1) {
25179 // There is no map associated with this compiler option then use the value as-is
25180 // This is the case if the value is expect to be string, number, boolean or list of string
25181 if (pathOptions && optionDefinition.isFilePath) {
25182 result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
25183 }
25184 else {
25185 result.set(name, value);
25186 }
25187 }
25188 else {
25189 if (optionDefinition.type === "list") {
25190 result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
25191 }
25192 else {
25193 // There is a typeMap associated with this command-line option so use it to map value back to its name
25194 result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
25195 }
25196 }
25197 }
25198 }
25199 };
25200 for (var name in options) {
25201 _loop_3(name);
25202 }
25203 return result;
25204 }
25205 /**
25206 * Generate tsconfig configuration when running command line "--init"
25207 * @param options commandlineOptions to be generated into tsconfig.json
25208 * @param fileNames array of filenames to be generated into tsconfig.json
25209 */
25210 /* @internal */
25211 function generateTSConfig(options, fileNames, newLine) {
25212 var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
25213 var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
25214 return writeConfigurations();
25215 function getDefaultValueForOption(option) {
25216 switch (option.type) {
25217 case "number":
25218 return 1;
25219 case "boolean":
25220 return true;
25221 case "string":
25222 return option.isFilePath ? "./" : "";
25223 case "list":
25224 return [];
25225 case "object":
25226 return {};
25227 default:
25228 return option.type.keys().next().value;
25229 }
25230 }
25231 function makePadding(paddingLength) {
25232 return Array(paddingLength + 1).join(" ");
25233 }
25234 function isAllowedOption(_a) {
25235 var category = _a.category, name = _a.name;
25236 // Skip options which do not have a category or have category `Command_line_Options`
25237 // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
25238 return category !== undefined
25239 && category !== ts.Diagnostics.Command_line_Options
25240 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
25241 }
25242 function writeConfigurations() {
25243 // Filter applicable options to place in the file
25244 var categorizedOptions = ts.createMultiMap();
25245 for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
25246 var option = optionDeclarations_1[_i];
25247 var category = option.category;
25248 if (isAllowedOption(option)) {
25249 categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
25250 }
25251 }
25252 // Serialize all options and their descriptions
25253 var marginLength = 0;
25254 var seenKnownKeys = 0;
25255 var nameColumn = [];
25256 var descriptionColumn = [];
25257 categorizedOptions.forEach(function (options, category) {
25258 if (nameColumn.length !== 0) {
25259 nameColumn.push("");
25260 descriptionColumn.push("");
25261 }
25262 nameColumn.push("/* " + category + " */");
25263 descriptionColumn.push("");
25264 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
25265 var option = options_1[_i];
25266 var optionName = void 0;
25267 if (compilerOptionsMap.has(option.name)) {
25268 optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
25269 }
25270 else {
25271 optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
25272 }
25273 nameColumn.push(optionName);
25274 descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */");
25275 marginLength = Math.max(optionName.length, marginLength);
25276 }
25277 });
25278 // Write the output
25279 var tab = makePadding(2);
25280 var result = [];
25281 result.push("{");
25282 result.push(tab + "\"compilerOptions\": {");
25283 // Print out each row, aligning all the descriptions on the same column.
25284 for (var i = 0; i < nameColumn.length; i++) {
25285 var optionName = nameColumn[i];
25286 var description = descriptionColumn[i];
25287 result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description)));
25288 }
25289 if (fileNames.length) {
25290 result.push(tab + "},");
25291 result.push(tab + "\"files\": [");
25292 for (var i = 0; i < fileNames.length; i++) {
25293 result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
25294 }
25295 result.push(tab + "]");
25296 }
25297 else {
25298 result.push(tab + "}");
25299 }
25300 result.push("}");
25301 return result.join(newLine) + newLine;
25302 }
25303 }
25304 ts.generateTSConfig = generateTSConfig;
25305 /**
25306 * Parse the contents of a config file (tsconfig.json).
25307 * @param json The contents of the config file to parse
25308 * @param host Instance of ParseConfigHost used to enumerate files in folder.
25309 * @param basePath A root directory to resolve relative path entries in the config
25310 * file to. e.g. outDir
25311 */
25312 function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
25313 return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions);
25314 }
25315 ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
25316 /**
25317 * Parse the contents of a config file (tsconfig.json).
25318 * @param jsonNode The contents of the config file to parse
25319 * @param host Instance of ParseConfigHost used to enumerate files in folder.
25320 * @param basePath A root directory to resolve relative path entries in the config
25321 * file to. e.g. outDir
25322 */
25323 function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
25324 return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions);
25325 }
25326 ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
25327 /*@internal*/
25328 function setConfigFileInOptions(options, configFile) {
25329 if (configFile) {
25330 Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
25331 }
25332 }
25333 ts.setConfigFileInOptions = setConfigFileInOptions;
25334 function isNullOrUndefined(x) {
25335 // tslint:disable-next-line:no-null-keyword
25336 return x === undefined || x === null;
25337 }
25338 function directoryOfCombinedPath(fileName, basePath) {
25339 // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
25340 // until consistent casing errors are reported
25341 return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
25342 }
25343 /**
25344 * Parse the contents of a config file from json or json source file (tsconfig.json).
25345 * @param json The contents of the config file to parse
25346 * @param sourceFile sourceFile corresponding to the Json
25347 * @param host Instance of ParseConfigHost used to enumerate files in folder.
25348 * @param basePath A root directory to resolve relative path entries in the config
25349 * file to. e.g. outDir
25350 * @param resolutionStack Only present for backwards-compatibility. Should be empty.
25351 */
25352 function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
25353 if (existingOptions === void 0) { existingOptions = {}; }
25354 if (resolutionStack === void 0) { resolutionStack = []; }
25355 if (extraFileExtensions === void 0) { extraFileExtensions = []; }
25356 ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
25357 var errors = [];
25358 var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors);
25359 var raw = parsedConfig.raw;
25360 var options = ts.extend(existingOptions, parsedConfig.options || {});
25361 options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
25362 setConfigFileInOptions(options, sourceFile);
25363 var projectReferences;
25364 var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
25365 return {
25366 options: options,
25367 fileNames: fileNames,
25368 projectReferences: projectReferences,
25369 typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
25370 raw: raw,
25371 errors: errors,
25372 wildcardDirectories: wildcardDirectories,
25373 compileOnSave: !!raw.compileOnSave,
25374 configFileSpecs: spec
25375 };
25376 function getFileNames() {
25377 var filesSpecs;
25378 if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
25379 if (ts.isArray(raw.files)) {
25380 filesSpecs = raw.files;
25381 var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references);
25382 var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0;
25383 var hasExtends = ts.hasProperty(raw, "extends");
25384 if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
25385 if (sourceFile) {
25386 var fileName = configFileName || "tsconfig.json";
25387 var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
25388 var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
25389 var error = nodeValue
25390 ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
25391 : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
25392 errors.push(error);
25393 }
25394 else {
25395 createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
25396 }
25397 }
25398 }
25399 else {
25400 createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array");
25401 }
25402 }
25403 var includeSpecs;
25404 if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
25405 if (ts.isArray(raw.include)) {
25406 includeSpecs = raw.include;
25407 }
25408 else {
25409 createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array");
25410 }
25411 }
25412 var excludeSpecs;
25413 if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
25414 if (ts.isArray(raw.exclude)) {
25415 excludeSpecs = raw.exclude;
25416 }
25417 else {
25418 createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
25419 }
25420 }
25421 else if (raw.compilerOptions) {
25422 var outDir = raw.compilerOptions.outDir;
25423 var declarationDir = raw.compilerOptions.declarationDir;
25424 if (outDir || declarationDir) {
25425 excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
25426 }
25427 }
25428 if (filesSpecs === undefined && includeSpecs === undefined) {
25429 includeSpecs = ["**/*"];
25430 }
25431 var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
25432 if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) {
25433 errors.push(getErrorForNoInputFiles(result.spec, configFileName));
25434 }
25435 if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
25436 if (ts.isArray(raw.references)) {
25437 for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
25438 var ref = _a[_i];
25439 if (typeof ref.path !== "string") {
25440 createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
25441 }
25442 else {
25443 (projectReferences || (projectReferences = [])).push({
25444 path: ts.getNormalizedAbsolutePath(ref.path, basePath),
25445 originalPath: ref.path,
25446 prepend: ref.prepend,
25447 circular: ref.circular
25448 });
25449 }
25450 }
25451 }
25452 else {
25453 createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
25454 }
25455 }
25456 return result;
25457 }
25458 function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
25459 if (!sourceFile) {
25460 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
25461 }
25462 }
25463 }
25464 function isErrorNoInputFiles(error) {
25465 return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
25466 }
25467 function getErrorForNoInputFiles(_a, configFileName) {
25468 var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
25469 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 || []));
25470 }
25471 function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
25472 return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
25473 }
25474 /*@internal*/
25475 function canJsonReportNoInutFiles(raw) {
25476 return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
25477 }
25478 ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles;
25479 /*@internal*/
25480 function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
25481 var existingErrors = configParseDiagnostics.length;
25482 if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
25483 configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
25484 }
25485 else {
25486 ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
25487 }
25488 return existingErrors !== configParseDiagnostics.length;
25489 }
25490 ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
25491 function isSuccessfulParsedTsconfig(value) {
25492 return !!value.options;
25493 }
25494 /**
25495 * This *just* extracts options/include/exclude/files out of a config file.
25496 * It does *not* resolve the included files.
25497 */
25498 function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) {
25499 basePath = ts.normalizeSlashes(basePath);
25500 var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
25501 if (resolutionStack.indexOf(resolvedPath) >= 0) {
25502 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> ")));
25503 return { raw: json || convertToObject(sourceFile, errors) };
25504 }
25505 var ownConfig = json ?
25506 parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
25507 parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
25508 if (ownConfig.extendedConfigPath) {
25509 // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
25510 resolutionStack = resolutionStack.concat([resolvedPath]);
25511 var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors);
25512 if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
25513 var baseRaw_1 = extendedConfig.raw;
25514 var raw_1 = ownConfig.raw;
25515 var setPropertyInRawIfNotUndefined = function (propertyName) {
25516 var value = raw_1[propertyName] || baseRaw_1[propertyName];
25517 if (value) {
25518 raw_1[propertyName] = value;
25519 }
25520 };
25521 setPropertyInRawIfNotUndefined("include");
25522 setPropertyInRawIfNotUndefined("exclude");
25523 setPropertyInRawIfNotUndefined("files");
25524 if (raw_1.compileOnSave === undefined) {
25525 raw_1.compileOnSave = baseRaw_1.compileOnSave;
25526 }
25527 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
25528 // TODO extend type typeAcquisition
25529 }
25530 }
25531 return ownConfig;
25532 }
25533 function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
25534 if (ts.hasProperty(json, "excludes")) {
25535 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
25536 }
25537 var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
25538 // typingOptions has been deprecated and is only supported for backward compatibility purposes.
25539 // It should be removed in future releases - use typeAcquisition instead.
25540 var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
25541 json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
25542 var extendedConfigPath;
25543 if (json.extends) {
25544 if (!ts.isString(json.extends)) {
25545 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
25546 }
25547 else {
25548 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
25549 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
25550 }
25551 }
25552 return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
25553 }
25554 function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
25555 var options = getDefaultCompilerOptions(configFileName);
25556 var typeAcquisition, typingOptionstypeAcquisition;
25557 var extendedConfigPath;
25558 var optionsIterator = {
25559 onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
25560 ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions");
25561 var currentOption = parentOption === "compilerOptions" ?
25562 options :
25563 parentOption === "typeAcquisition" ?
25564 (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) :
25565 (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
25566 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
25567 },
25568 onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
25569 switch (key) {
25570 case "extends":
25571 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
25572 extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
25573 return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
25574 });
25575 return;
25576 }
25577 },
25578 onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
25579 if (key === "excludes") {
25580 errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
25581 }
25582 }
25583 };
25584 var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
25585 if (!typeAcquisition) {
25586 if (typingOptionstypeAcquisition) {
25587 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
25588 {
25589 enable: typingOptionstypeAcquisition.enableAutoDiscovery,
25590 include: typingOptionstypeAcquisition.include,
25591 exclude: typingOptionstypeAcquisition.exclude
25592 } :
25593 typingOptionstypeAcquisition;
25594 }
25595 else {
25596 typeAcquisition = getDefaultTypeAcquisition(configFileName);
25597 }
25598 }
25599 return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
25600 }
25601 function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
25602 extendedConfig = ts.normalizeSlashes(extendedConfig);
25603 if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
25604 var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
25605 if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
25606 extendedConfigPath = extendedConfigPath + ".json";
25607 if (!host.fileExists(extendedConfigPath)) {
25608 errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig));
25609 return undefined;
25610 }
25611 }
25612 return extendedConfigPath;
25613 }
25614 // If the path isn't a rooted or relative path, resolve like a module
25615 var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
25616 if (resolved.resolvedModule) {
25617 return resolved.resolvedModule.resolvedFileName;
25618 }
25619 errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig));
25620 return undefined;
25621 }
25622 function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) {
25623 var _a;
25624 var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
25625 if (sourceFile) {
25626 sourceFile.extendedSourceFiles = [extendedResult.fileName];
25627 }
25628 if (extendedResult.parseDiagnostics.length) {
25629 errors.push.apply(errors, extendedResult.parseDiagnostics);
25630 return undefined;
25631 }
25632 var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
25633 var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors);
25634 if (sourceFile && extendedResult.extendedSourceFiles) {
25635 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
25636 }
25637 if (isSuccessfulParsedTsconfig(extendedConfig)) {
25638 // Update the paths to reflect base path
25639 var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
25640 var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
25641 var mapPropertiesInRawIfNotUndefined = function (propertyName) {
25642 if (raw_2[propertyName]) {
25643 raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
25644 }
25645 };
25646 var raw_2 = extendedConfig.raw;
25647 mapPropertiesInRawIfNotUndefined("include");
25648 mapPropertiesInRawIfNotUndefined("exclude");
25649 mapPropertiesInRawIfNotUndefined("files");
25650 }
25651 return extendedConfig;
25652 }
25653 function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
25654 if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
25655 return false;
25656 }
25657 var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
25658 return typeof result === "boolean" && result;
25659 }
25660 function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
25661 var errors = [];
25662 var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
25663 return { options: options, errors: errors };
25664 }
25665 ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
25666 function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
25667 var errors = [];
25668 var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
25669 return { options: options, errors: errors };
25670 }
25671 ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
25672 function getDefaultCompilerOptions(configFileName) {
25673 var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
25674 ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
25675 : {};
25676 return options;
25677 }
25678 function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
25679 var options = getDefaultCompilerOptions(configFileName);
25680 convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
25681 if (configFileName) {
25682 options.configFilePath = ts.normalizeSlashes(configFileName);
25683 }
25684 return options;
25685 }
25686 function getDefaultTypeAcquisition(configFileName) {
25687 return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
25688 }
25689 function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
25690 var options = getDefaultTypeAcquisition(configFileName);
25691 var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
25692 convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors);
25693 return options;
25694 }
25695 function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) {
25696 if (!jsonOptions) {
25697 return;
25698 }
25699 var optionNameMap = commandLineOptionsToMap(optionDeclarations);
25700 for (var id in jsonOptions) {
25701 var opt = optionNameMap.get(id);
25702 if (opt) {
25703 defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
25704 }
25705 else {
25706 errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id));
25707 }
25708 }
25709 }
25710 function convertJsonOption(opt, value, basePath, errors) {
25711 if (isCompilerOptionsValue(opt, value)) {
25712 var optType = opt.type;
25713 if (optType === "list" && ts.isArray(value)) {
25714 return convertJsonOptionOfListType(opt, value, basePath, errors);
25715 }
25716 else if (!ts.isString(optType)) {
25717 return convertJsonOptionOfCustomType(opt, value, errors);
25718 }
25719 return normalizeNonListOptionValue(opt, basePath, value);
25720 }
25721 else {
25722 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
25723 }
25724 }
25725 function normalizeOptionValue(option, basePath, value) {
25726 if (isNullOrUndefined(value))
25727 return undefined;
25728 if (option.type === "list") {
25729 var listOption_1 = option;
25730 if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
25731 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
25732 }
25733 return value;
25734 }
25735 else if (!ts.isString(option.type)) {
25736 return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
25737 }
25738 return normalizeNonListOptionValue(option, basePath, value);
25739 }
25740 function normalizeNonListOptionValue(option, basePath, value) {
25741 if (option.isFilePath) {
25742 value = ts.normalizePath(ts.combinePaths(basePath, value));
25743 if (value === "") {
25744 value = ".";
25745 }
25746 }
25747 return value;
25748 }
25749 function convertJsonOptionOfCustomType(opt, value, errors) {
25750 if (isNullOrUndefined(value))
25751 return undefined;
25752 var key = value.toLowerCase();
25753 var val = opt.type.get(key);
25754 if (val !== undefined) {
25755 return val;
25756 }
25757 else {
25758 errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
25759 }
25760 }
25761 function convertJsonOptionOfListType(option, values, basePath, errors) {
25762 return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
25763 }
25764 function trimString(s) {
25765 return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
25766 }
25767 /**
25768 * Tests for a path that ends in a recursive directory wildcard.
25769 * Matches **, \**, **\, and \**\, but not a**b.
25770 *
25771 * NOTE: used \ in place of / above to avoid issues with multiline comments.
25772 *
25773 * Breakdown:
25774 * (^|\/) # matches either the beginning of the string or a directory separator.
25775 * \*\* # matches the recursive directory wildcard "**".
25776 * \/?$ # matches an optional trailing directory separator at the end of the string.
25777 */
25778 var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
25779 /**
25780 * Tests for a path where .. appears after a recursive directory wildcard.
25781 * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
25782 *
25783 * NOTE: used \ in place of / above to avoid issues with multiline comments.
25784 *
25785 * Breakdown:
25786 * (^|\/) # matches either the beginning of the string or a directory separator.
25787 * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator.
25788 * (.*\/)? # optionally matches any number of characters followed by a directory separator.
25789 * \.\. # matches a parent directory path component ".."
25790 * ($|\/) # matches either the end of the string or a directory separator.
25791 */
25792 var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
25793 /**
25794 * Tests for a path containing a wildcard character in a directory component of the path.
25795 * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
25796 *
25797 * NOTE: used \ in place of / above to avoid issues with multiline comments.
25798 *
25799 * Breakdown:
25800 * \/ # matches a directory separator.
25801 * [^/]*? # matches any number of characters excluding directory separators (non-greedy).
25802 * [*?] # matches either a wildcard character (* or ?)
25803 * [^/]* # matches any number of characters excluding directory separators (greedy).
25804 * \/ # matches a directory separator.
25805 */
25806 var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
25807 /**
25808 * Matches the portion of a wildcard path that does not contain wildcards.
25809 * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
25810 *
25811 * NOTE: used \ in place of / above to avoid issues with multiline comments.
25812 *
25813 * Breakdown:
25814 * ^ # matches the beginning of the string
25815 * [^*?]* # matches any number of non-wildcard characters
25816 * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by
25817 * # a path component that contains at least one wildcard character (* or ?).
25818 */
25819 var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
25820 /**
25821 * Expands an array of file specifications.
25822 *
25823 * @param filesSpecs The literal file names to include.
25824 * @param includeSpecs The wildcard file specifications to include.
25825 * @param excludeSpecs The wildcard file specifications to exclude.
25826 * @param basePath The base path for any relative file specifications.
25827 * @param options Compiler options.
25828 * @param host The host used to resolve files and directories.
25829 * @param errors An array for diagnostic reporting.
25830 */
25831 function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
25832 basePath = ts.normalizePath(basePath);
25833 var validatedIncludeSpecs, validatedExcludeSpecs;
25834 // The exclude spec list is converted into a regular expression, which allows us to quickly
25835 // test whether a file or directory should be excluded before recursively traversing the
25836 // file system.
25837 if (includeSpecs) {
25838 validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
25839 }
25840 if (excludeSpecs) {
25841 validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
25842 }
25843 // Wildcard directories (provided as part of a wildcard path) are stored in a
25844 // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
25845 // or a recursive directory. This information is used by filesystem watchers to monitor for
25846 // new entries in these paths.
25847 var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
25848 var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
25849 return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
25850 }
25851 /**
25852 * Gets the file names from the provided config file specs that contain, files, include, exclude and
25853 * other properties needed to resolve the file names
25854 * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
25855 * @param basePath The base path for any relative file specifications.
25856 * @param options Compiler options.
25857 * @param host The host used to resolve files and directories.
25858 * @param extraFileExtensions optionaly file extra file extension information from host
25859 */
25860 /* @internal */
25861 function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
25862 if (extraFileExtensions === void 0) { extraFileExtensions = []; }
25863 basePath = ts.normalizePath(basePath);
25864 var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase;
25865 // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
25866 // file map with a possibly case insensitive key. We use this map later when when including
25867 // wildcard paths.
25868 var literalFileMap = ts.createMap();
25869 // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
25870 // file map with a possibly case insensitive key. We use this map to store paths matched
25871 // via wildcard, and to handle extension priority.
25872 var wildcardFileMap = ts.createMap();
25873 // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
25874 // file map with a possibly case insensitive key. We use this map to store paths matched
25875 // via wildcard of *.json kind
25876 var wildCardJsonFileMap = ts.createMap();
25877 var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
25878 // Rather than requery this for each file and filespec, we query the supported extensions
25879 // once and store it on the expansion context.
25880 var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
25881 var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
25882 // Literal files are always included verbatim. An "include" or "exclude" specification cannot
25883 // remove a literal file.
25884 if (filesSpecs) {
25885 for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
25886 var fileName = filesSpecs_1[_i];
25887 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
25888 literalFileMap.set(keyMapper(file), file);
25889 }
25890 }
25891 var jsonOnlyIncludeRegexes;
25892 if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
25893 var _loop_4 = function (file) {
25894 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
25895 // Valid only if *.json specified
25896 if (!jsonOnlyIncludeRegexes) {
25897 var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
25898 var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
25899 jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
25900 }
25901 var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
25902 if (includeIndex !== -1) {
25903 var key_1 = keyMapper(file);
25904 if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
25905 wildCardJsonFileMap.set(key_1, file);
25906 }
25907 }
25908 return "continue";
25909 }
25910 // If we have already included a literal or wildcard path with a
25911 // higher priority extension, we should skip this file.
25912 //
25913 // This handles cases where we may encounter both <file>.ts and
25914 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
25915 // directory when they are compilation outputs.
25916 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
25917 return "continue";
25918 }
25919 // We may have included a wildcard path with a lower priority
25920 // extension due to the user-defined order of entries in the
25921 // "include" array. If there is a lower priority extension in the
25922 // same directory, we should remove it.
25923 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
25924 var key = keyMapper(file);
25925 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
25926 wildcardFileMap.set(key, file);
25927 }
25928 };
25929 for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
25930 var file = _b[_a];
25931 _loop_4(file);
25932 }
25933 }
25934 var literalFiles = ts.arrayFrom(literalFileMap.values());
25935 var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
25936 return {
25937 fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
25938 wildcardDirectories: wildcardDirectories,
25939 spec: spec
25940 };
25941 }
25942 ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
25943 function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
25944 return specs.filter(function (spec) {
25945 var diag = specToDiagnostic(spec, allowTrailingRecursion);
25946 if (diag !== undefined) {
25947 errors.push(createDiagnostic(diag, spec));
25948 }
25949 return diag === undefined;
25950 });
25951 function createDiagnostic(message, spec) {
25952 var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
25953 return element ?
25954 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
25955 ts.createCompilerDiagnostic(message, spec);
25956 }
25957 }
25958 function specToDiagnostic(spec, allowTrailingRecursion) {
25959 if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
25960 return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
25961 }
25962 else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
25963 return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
25964 }
25965 }
25966 /**
25967 * Gets directories in a set of include patterns that should be watched for changes.
25968 */
25969 function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
25970 // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
25971 // of the pattern:
25972 //
25973 // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively
25974 // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
25975 // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler
25976 //
25977 // We watch a directory without recursion if it contains a wildcard in the file segment of
25978 // the pattern:
25979 //
25980 // /a/b/* - Watch /a/b directly to catch any new file
25981 // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z
25982 var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
25983 var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
25984 var wildcardDirectories = {};
25985 if (include !== undefined) {
25986 var recursiveKeys = [];
25987 for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
25988 var file = include_1[_i];
25989 var spec = ts.normalizePath(ts.combinePaths(path, file));
25990 if (excludeRegex && excludeRegex.test(spec)) {
25991 continue;
25992 }
25993 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
25994 if (match) {
25995 var key = match.key, flags = match.flags;
25996 var existingFlags = wildcardDirectories[key];
25997 if (existingFlags === undefined || existingFlags < flags) {
25998 wildcardDirectories[key] = flags;
25999 if (flags === 1 /* Recursive */) {
26000 recursiveKeys.push(key);
26001 }
26002 }
26003 }
26004 }
26005 // Remove any subpaths under an existing recursively watched directory.
26006 for (var key in wildcardDirectories) {
26007 if (ts.hasProperty(wildcardDirectories, key)) {
26008 for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
26009 var recursiveKey = recursiveKeys_1[_a];
26010 if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
26011 delete wildcardDirectories[key];
26012 }
26013 }
26014 }
26015 }
26016 }
26017 return wildcardDirectories;
26018 }
26019 function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
26020 var match = wildcardDirectoryPattern.exec(spec);
26021 if (match) {
26022 return {
26023 key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(),
26024 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
26025 };
26026 }
26027 if (ts.isImplicitGlob(spec)) {
26028 return { key: spec, flags: 1 /* Recursive */ };
26029 }
26030 return undefined;
26031 }
26032 /**
26033 * Determines whether a literal or wildcard file has already been included that has a higher
26034 * extension priority.
26035 *
26036 * @param file The path to the file.
26037 * @param extensionPriority The priority of the extension.
26038 * @param context The expansion context.
26039 */
26040 function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
26041 var extensionPriority = ts.getExtensionPriority(file, extensions);
26042 var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
26043 for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
26044 var higherPriorityExtension = extensions[i];
26045 var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
26046 if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
26047 return true;
26048 }
26049 }
26050 return false;
26051 }
26052 /**
26053 * Removes files included via wildcard expansion with a lower extension priority that have
26054 * already been included.
26055 *
26056 * @param file The path to the file.
26057 * @param extensionPriority The priority of the extension.
26058 * @param context The expansion context.
26059 */
26060 function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
26061 var extensionPriority = ts.getExtensionPriority(file, extensions);
26062 var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
26063 for (var i = nextExtensionPriority; i < extensions.length; i++) {
26064 var lowerPriorityExtension = extensions[i];
26065 var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
26066 wildcardFiles.delete(lowerPriorityPath);
26067 }
26068 }
26069 /**
26070 * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
26071 * Also converts enum values back to strings.
26072 */
26073 /* @internal */
26074 function convertCompilerOptionsForTelemetry(opts) {
26075 var out = {};
26076 for (var key in opts) {
26077 if (opts.hasOwnProperty(key)) {
26078 var type = getOptionFromName(key);
26079 if (type !== undefined) { // Ignore unknown options
26080 out[key] = getOptionValueWithEmptyStrings(opts[key], type);
26081 }
26082 }
26083 }
26084 return out;
26085 }
26086 ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
26087 function getOptionValueWithEmptyStrings(value, option) {
26088 switch (option.type) {
26089 case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
26090 return "";
26091 case "string": // Could be any arbitrary string -- use empty string instead.
26092 return "";
26093 case "number": // Allow numbers, but be sure to check it's actually a number.
26094 return typeof value === "number" ? value : "";
26095 case "boolean":
26096 return typeof value === "boolean" ? value : "";
26097 case "list":
26098 var elementType_1 = option.element;
26099 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
26100 default:
26101 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
26102 if (optionEnumValue === value) {
26103 return optionStringValue;
26104 }
26105 }); // TODO: GH#18217
26106 }
26107 }
26108})(ts || (ts = {}));
26109var ts;
26110(function (ts) {
26111 function trace(host) {
26112 host.trace(ts.formatMessage.apply(undefined, arguments));
26113 }
26114 ts.trace = trace;
26115 /* @internal */
26116 function isTraceEnabled(compilerOptions, host) {
26117 return !!compilerOptions.traceResolution && host.trace !== undefined;
26118 }
26119 ts.isTraceEnabled = isTraceEnabled;
26120 function withPackageId(packageId, r) {
26121 return r && { path: r.path, extension: r.ext, packageId: packageId };
26122 }
26123 function noPackageId(r) {
26124 return withPackageId(/*packageId*/ undefined, r);
26125 }
26126 function removeIgnoredPackageId(r) {
26127 if (r) {
26128 ts.Debug.assert(r.packageId === undefined);
26129 return { path: r.path, ext: r.extension };
26130 }
26131 }
26132 /**
26133 * Kinds of file that we are currently looking for.
26134 * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
26135 */
26136 var Extensions;
26137 (function (Extensions) {
26138 Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
26139 Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
26140 Extensions[Extensions["Json"] = 2] = "Json";
26141 Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
26142 Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
26143 })(Extensions || (Extensions = {}));
26144 /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
26145 function resolvedTypeScriptOnly(resolved) {
26146 if (!resolved) {
26147 return undefined;
26148 }
26149 ts.Debug.assert(ts.extensionIsTS(resolved.extension));
26150 return { fileName: resolved.path, packageId: resolved.packageId };
26151 }
26152 function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) {
26153 return {
26154 resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
26155 failedLookupLocations: failedLookupLocations
26156 };
26157 }
26158 function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
26159 if (!ts.hasProperty(jsonContent, fieldName)) {
26160 if (state.traceEnabled) {
26161 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
26162 }
26163 return;
26164 }
26165 var value = jsonContent[fieldName];
26166 if (typeof value !== typeOfTag || value === null) {
26167 if (state.traceEnabled) {
26168 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);
26169 }
26170 return;
26171 }
26172 return value;
26173 }
26174 function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
26175 var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
26176 if (fileName === undefined)
26177 return;
26178 var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
26179 if (state.traceEnabled) {
26180 trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
26181 }
26182 return path;
26183 }
26184 function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
26185 return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
26186 || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
26187 }
26188 function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
26189 return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
26190 }
26191 function readPackageJsonMainField(jsonContent, baseDirectory, state) {
26192 return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
26193 }
26194 function readPackageJsonTypesVersionsField(jsonContent, state) {
26195 var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
26196 if (typesVersions === undefined)
26197 return;
26198 if (state.traceEnabled) {
26199 trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
26200 }
26201 return typesVersions;
26202 }
26203 function readPackageJsonTypesVersionPaths(jsonContent, state) {
26204 var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
26205 if (typesVersions === undefined)
26206 return;
26207 if (state.traceEnabled) {
26208 for (var key in typesVersions) {
26209 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
26210 trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
26211 }
26212 }
26213 }
26214 var result = getPackageJsonTypesVersionsPaths(typesVersions);
26215 if (!result) {
26216 if (state.traceEnabled) {
26217 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
26218 }
26219 return;
26220 }
26221 var bestVersionKey = result.version, bestVersionPaths = result.paths;
26222 if (typeof bestVersionPaths !== "object") {
26223 if (state.traceEnabled) {
26224 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
26225 }
26226 return;
26227 }
26228 return result;
26229 }
26230 var typeScriptVersion;
26231 /* @internal */
26232 function getPackageJsonTypesVersionsPaths(typesVersions) {
26233 if (!typeScriptVersion)
26234 typeScriptVersion = new ts.Version(ts.version);
26235 for (var key in typesVersions) {
26236 if (!ts.hasProperty(typesVersions, key))
26237 continue;
26238 var keyRange = ts.VersionRange.tryParse(key);
26239 if (keyRange === undefined) {
26240 continue;
26241 }
26242 // return the first entry whose range matches the current compiler version.
26243 if (keyRange.test(typeScriptVersion)) {
26244 return { version: key, paths: typesVersions[key] };
26245 }
26246 }
26247 }
26248 ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
26249 function getEffectiveTypeRoots(options, host) {
26250 if (options.typeRoots) {
26251 return options.typeRoots;
26252 }
26253 var currentDirectory;
26254 if (options.configFilePath) {
26255 currentDirectory = ts.getDirectoryPath(options.configFilePath);
26256 }
26257 else if (host.getCurrentDirectory) {
26258 currentDirectory = host.getCurrentDirectory();
26259 }
26260 if (currentDirectory !== undefined) {
26261 return getDefaultTypeRoots(currentDirectory, host);
26262 }
26263 }
26264 ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
26265 /**
26266 * Returns the path to every node_modules/@types directory from some ancestor directory.
26267 * Returns undefined if there are none.
26268 */
26269 function getDefaultTypeRoots(currentDirectory, host) {
26270 if (!host.directoryExists) {
26271 return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
26272 // And if it doesn't exist, tough.
26273 }
26274 var typeRoots;
26275 ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
26276 var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
26277 if (host.directoryExists(atTypes)) {
26278 (typeRoots || (typeRoots = [])).push(atTypes);
26279 }
26280 return undefined;
26281 });
26282 return typeRoots;
26283 }
26284 var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
26285 /**
26286 * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
26287 * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
26288 * is assumed to be the same as root directory of the project.
26289 */
26290 function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
26291 var traceEnabled = isTraceEnabled(options, host);
26292 if (redirectedReference) {
26293 options = redirectedReference.commandLine.options;
26294 }
26295 var failedLookupLocations = [];
26296 var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
26297 var typeRoots = getEffectiveTypeRoots(options, host);
26298 if (traceEnabled) {
26299 if (containingFile === undefined) {
26300 if (typeRoots === undefined) {
26301 trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
26302 }
26303 else {
26304 trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
26305 }
26306 }
26307 else {
26308 if (typeRoots === undefined) {
26309 trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
26310 }
26311 else {
26312 trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
26313 }
26314 }
26315 if (redirectedReference) {
26316 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
26317 }
26318 }
26319 var resolved = primaryLookup();
26320 var primary = true;
26321 if (!resolved) {
26322 resolved = secondaryLookup();
26323 primary = false;
26324 }
26325 var resolvedTypeReferenceDirective;
26326 if (resolved) {
26327 var fileName = resolved.fileName, packageId = resolved.packageId;
26328 var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
26329 if (traceEnabled) {
26330 trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
26331 }
26332 resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
26333 }
26334 return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
26335 function primaryLookup() {
26336 // Check primary library paths
26337 if (typeRoots && typeRoots.length) {
26338 if (traceEnabled) {
26339 trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
26340 }
26341 return ts.firstDefined(typeRoots, function (typeRoot) {
26342 var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
26343 var candidateDirectory = ts.getDirectoryPath(candidate);
26344 var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
26345 if (!directoryExists && traceEnabled) {
26346 trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
26347 }
26348 return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
26349 });
26350 }
26351 else {
26352 if (traceEnabled) {
26353 trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
26354 }
26355 }
26356 }
26357 function secondaryLookup() {
26358 var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
26359 if (initialLocationForSecondaryLookup !== undefined) {
26360 // check secondary locations
26361 if (traceEnabled) {
26362 trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
26363 }
26364 var result = void 0;
26365 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
26366 var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
26367 result = searchResult && searchResult.value;
26368 }
26369 else {
26370 var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
26371 result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
26372 }
26373 var resolvedFile = resolvedTypeScriptOnly(result);
26374 if (!resolvedFile && traceEnabled) {
26375 trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
26376 }
26377 return resolvedFile;
26378 }
26379 else {
26380 if (traceEnabled) {
26381 trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
26382 }
26383 }
26384 }
26385 }
26386 ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
26387 /**
26388 * Given a set of options, returns the set of type directive names
26389 * that should be included for this program automatically.
26390 * This list could either come from the config file,
26391 * or from enumerating the types root + initial secondary types lookup location.
26392 * More type directives might appear in the program later as a result of loading actual source files;
26393 * this list is only the set of defaults that are implicitly included.
26394 */
26395 function getAutomaticTypeDirectiveNames(options, host) {
26396 // Use explicit type list from tsconfig.json
26397 if (options.types) {
26398 return options.types;
26399 }
26400 // Walk the primary type lookup locations
26401 var result = [];
26402 if (host.directoryExists && host.getDirectories) {
26403 var typeRoots = getEffectiveTypeRoots(options, host);
26404 if (typeRoots) {
26405 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
26406 var root = typeRoots_1[_i];
26407 if (host.directoryExists(root)) {
26408 for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
26409 var typeDirectivePath = _b[_a];
26410 var normalized = ts.normalizePath(typeDirectivePath);
26411 var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
26412 // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
26413 // See `createNotNeededPackageJSON` in the types-publisher` repo.
26414 // tslint:disable-next-line:no-null-keyword
26415 var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
26416 if (!isNotNeededPackage) {
26417 var baseFileName = ts.getBaseFileName(normalized);
26418 // At this stage, skip results with leading dot.
26419 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
26420 // Return just the type directive names
26421 result.push(baseFileName);
26422 }
26423 }
26424 }
26425 }
26426 }
26427 }
26428 }
26429 return result;
26430 }
26431 ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
26432 function createModuleResolutionCache(currentDirectory, getCanonicalFileName) {
26433 return createModuleResolutionCacheWithMaps(createCacheWithRedirects(), createCacheWithRedirects(), currentDirectory, getCanonicalFileName);
26434 }
26435 ts.createModuleResolutionCache = createModuleResolutionCache;
26436 /*@internal*/
26437 function createCacheWithRedirects() {
26438 var ownMap = ts.createMap();
26439 var redirectsMap = ts.createMap();
26440 return {
26441 ownMap: ownMap,
26442 redirectsMap: redirectsMap,
26443 getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
26444 clear: clear
26445 };
26446 function getOrCreateMapOfCacheRedirects(redirectedReference) {
26447 if (!redirectedReference) {
26448 return ownMap;
26449 }
26450 var path = redirectedReference.sourceFile.path;
26451 var redirects = redirectsMap.get(path);
26452 if (!redirects) {
26453 redirects = ts.createMap();
26454 redirectsMap.set(path, redirects);
26455 }
26456 return redirects;
26457 }
26458 function clear() {
26459 ownMap.clear();
26460 redirectsMap.clear();
26461 }
26462 }
26463 ts.createCacheWithRedirects = createCacheWithRedirects;
26464 /*@internal*/
26465 function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
26466 return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName };
26467 function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
26468 var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
26469 return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap);
26470 }
26471 function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
26472 ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
26473 return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
26474 }
26475 function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
26476 var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
26477 var result = cache.get(key);
26478 if (!result) {
26479 result = create();
26480 cache.set(key, result);
26481 }
26482 return result;
26483 }
26484 function createPerModuleNameCache() {
26485 var directoryPathMap = ts.createMap();
26486 return { get: get, set: set };
26487 function get(directory) {
26488 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
26489 }
26490 /**
26491 * At first this function add entry directory -> module resolution result to the table.
26492 * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
26493 * and for every parent folder in set it adds entry: parent -> module resolution. .
26494 * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
26495 * Set of parent folders that should have the same result will be:
26496 * [
26497 * /a/b/c/d, /a/b/c, /a/b
26498 * ]
26499 * this means that request for module resolution from file in any of these folder will be immediately found in cache.
26500 */
26501 function set(directory, result) {
26502 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
26503 // if entry is already in cache do nothing
26504 if (directoryPathMap.has(path)) {
26505 return;
26506 }
26507 directoryPathMap.set(path, result);
26508 var resolvedFileName = result.resolvedModule &&
26509 (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
26510 // find common prefix between directory and resolved file name
26511 // this common prefix should be the shortest path that has the same resolution
26512 // directory: /a/b/c/d/e
26513 // resolvedFileName: /a/b/foo.d.ts
26514 // commonPrefix: /a/b
26515 // for failed lookups cache the result for every directory up to root
26516 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
26517 var current = path;
26518 while (current !== commonPrefix) {
26519 var parent = ts.getDirectoryPath(current);
26520 if (parent === current || directoryPathMap.has(parent)) {
26521 break;
26522 }
26523 directoryPathMap.set(parent, result);
26524 current = parent;
26525 }
26526 }
26527 function getCommonPrefix(directory, resolution) {
26528 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
26529 // find first position where directory and resolution differs
26530 var i = 0;
26531 var limit = Math.min(directory.length, resolutionDirectory.length);
26532 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
26533 i++;
26534 }
26535 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
26536 return directory;
26537 }
26538 var rootLength = ts.getRootLength(directory);
26539 if (i < rootLength) {
26540 return undefined;
26541 }
26542 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
26543 if (sep === -1) {
26544 return undefined;
26545 }
26546 return directory.substr(0, Math.max(sep, rootLength));
26547 }
26548 }
26549 }
26550 ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
26551 function resolveModuleNameFromCache(moduleName, containingFile, cache) {
26552 var containingDirectory = ts.getDirectoryPath(containingFile);
26553 var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
26554 return perFolderCache && perFolderCache.get(moduleName);
26555 }
26556 ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
26557 function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
26558 var traceEnabled = isTraceEnabled(compilerOptions, host);
26559 if (redirectedReference) {
26560 compilerOptions = redirectedReference.commandLine.options;
26561 }
26562 if (traceEnabled) {
26563 trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
26564 if (redirectedReference) {
26565 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
26566 }
26567 }
26568 var containingDirectory = ts.getDirectoryPath(containingFile);
26569 var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
26570 var result = perFolderCache && perFolderCache.get(moduleName);
26571 if (result) {
26572 if (traceEnabled) {
26573 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
26574 }
26575 }
26576 else {
26577 var moduleResolution = compilerOptions.moduleResolution;
26578 if (moduleResolution === undefined) {
26579 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
26580 if (traceEnabled) {
26581 trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
26582 }
26583 }
26584 else {
26585 if (traceEnabled) {
26586 trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
26587 }
26588 }
26589 switch (moduleResolution) {
26590 case ts.ModuleResolutionKind.NodeJs:
26591 result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
26592 break;
26593 case ts.ModuleResolutionKind.Classic:
26594 result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
26595 break;
26596 default:
26597 return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
26598 }
26599 if (perFolderCache) {
26600 perFolderCache.set(moduleName, result);
26601 if (!ts.isExternalModuleNameRelative(moduleName)) {
26602 // put result in per-module name cache
26603 cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
26604 }
26605 }
26606 }
26607 if (traceEnabled) {
26608 if (result.resolvedModule) {
26609 trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
26610 }
26611 else {
26612 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
26613 }
26614 }
26615 return result;
26616 }
26617 ts.resolveModuleName = resolveModuleName;
26618 /**
26619 * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
26620 * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
26621 * can be resolved successfully by TypeScript compiler and runtime module loader.
26622 * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
26623 * fallback to standard resolution routine.
26624 *
26625 * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
26626 * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
26627 * be '/a/b/c/d'
26628 * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
26629 * will be resolved based on the content of the module name.
26630 * Structure of 'paths' compiler options
26631 * 'paths': {
26632 * pattern-1: [...substitutions],
26633 * pattern-2: [...substitutions],
26634 * ...
26635 * pattern-n: [...substitutions]
26636 * }
26637 * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
26638 * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
26639 * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
26640 * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
26641 * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
26642 * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
26643 * from the candidate location.
26644 * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
26645 * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
26646 * will be converted to absolute using baseUrl.
26647 * For example:
26648 * baseUrl: /a/b/c
26649 * "paths": {
26650 * // match all module names
26651 * "*": [
26652 * "*", // use matched name as is,
26653 * // <matched name> will be looked as /a/b/c/<matched name>
26654 *
26655 * "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
26656 * // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
26657 * ],
26658 * // match module names that start with 'components/'
26659 * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
26660 * // it is rooted so it will be final candidate location
26661 * }
26662 *
26663 * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
26664 * they were in the same location. For example lets say there are two files
26665 * '/local/src/content/file1.ts'
26666 * '/shared/components/contracts/src/content/protocols/file2.ts'
26667 * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
26668 * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
26669 * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
26670 * root dirs were merged together.
26671 * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
26672 * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
26673 * '/local/src/content/protocols/file2' and try to load it - failure.
26674 * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
26675 * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
26676 * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
26677 */
26678 function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
26679 var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
26680 if (resolved)
26681 return resolved.value;
26682 if (!ts.isExternalModuleNameRelative(moduleName)) {
26683 return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
26684 }
26685 else {
26686 return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
26687 }
26688 }
26689 function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
26690 var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
26691 if (baseUrl && paths && !ts.pathIsRelative(moduleName)) {
26692 if (state.traceEnabled) {
26693 trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
26694 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
26695 }
26696 return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
26697 }
26698 }
26699 function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
26700 if (!state.compilerOptions.rootDirs) {
26701 return undefined;
26702 }
26703 if (state.traceEnabled) {
26704 trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
26705 }
26706 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
26707 var matchedRootDir;
26708 var matchedNormalizedPrefix;
26709 for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
26710 var rootDir = _a[_i];
26711 // rootDirs are expected to be absolute
26712 // in case of tsconfig.json this will happen automatically - compiler will expand relative names
26713 // using location of tsconfig.json as base location
26714 var normalizedRoot = ts.normalizePath(rootDir);
26715 if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
26716 normalizedRoot += ts.directorySeparator;
26717 }
26718 var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
26719 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
26720 if (state.traceEnabled) {
26721 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
26722 }
26723 if (isLongestMatchingPrefix) {
26724 matchedNormalizedPrefix = normalizedRoot;
26725 matchedRootDir = rootDir;
26726 }
26727 }
26728 if (matchedNormalizedPrefix) {
26729 if (state.traceEnabled) {
26730 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
26731 }
26732 var suffix = candidate.substr(matchedNormalizedPrefix.length);
26733 // first - try to load from a initial location
26734 if (state.traceEnabled) {
26735 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
26736 }
26737 var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
26738 if (resolvedFileName) {
26739 return resolvedFileName;
26740 }
26741 if (state.traceEnabled) {
26742 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
26743 }
26744 // then try to resolve using remaining entries in rootDirs
26745 for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
26746 var rootDir = _c[_b];
26747 if (rootDir === matchedRootDir) {
26748 // skip the initially matched entry
26749 continue;
26750 }
26751 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
26752 if (state.traceEnabled) {
26753 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
26754 }
26755 var baseDirectory = ts.getDirectoryPath(candidate_1);
26756 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
26757 if (resolvedFileName_1) {
26758 return resolvedFileName_1;
26759 }
26760 }
26761 if (state.traceEnabled) {
26762 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
26763 }
26764 }
26765 return undefined;
26766 }
26767 function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
26768 var baseUrl = state.compilerOptions.baseUrl;
26769 if (!baseUrl) {
26770 return undefined;
26771 }
26772 if (state.traceEnabled) {
26773 trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
26774 }
26775 var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
26776 if (state.traceEnabled) {
26777 trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
26778 }
26779 return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
26780 }
26781 /**
26782 * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
26783 * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
26784 * Throws an error if the module can't be resolved.
26785 */
26786 /* @internal */
26787 function resolveJSModule(moduleName, initialDir, host) {
26788 var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
26789 if (!resolvedModule) {
26790 throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
26791 }
26792 return resolvedModule.resolvedFileName;
26793 }
26794 ts.resolveJSModule = resolveJSModule;
26795 /* @internal */
26796 function tryResolveJSModule(moduleName, initialDir, host) {
26797 var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
26798 return resolvedModule && resolvedModule.resolvedFileName;
26799 }
26800 ts.tryResolveJSModule = tryResolveJSModule;
26801 var jsOnlyExtensions = [Extensions.JavaScript];
26802 var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
26803 var tsPlusJsonExtensions = tsExtensions.concat([Extensions.Json]);
26804 var tsconfigExtensions = [Extensions.TSConfig];
26805 function tryResolveJSModuleWorker(moduleName, initialDir, host) {
26806 return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
26807 }
26808 function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
26809 return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
26810 }
26811 ts.nodeModuleNameResolver = nodeModuleNameResolver;
26812 function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
26813 var traceEnabled = isTraceEnabled(compilerOptions, host);
26814 var failedLookupLocations = [];
26815 var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
26816 var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
26817 if (result && result.value) {
26818 var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport;
26819 return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations);
26820 }
26821 return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
26822 function tryResolve(extensions) {
26823 var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
26824 var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
26825 if (resolved) {
26826 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
26827 }
26828 if (!ts.isExternalModuleNameRelative(moduleName)) {
26829 if (traceEnabled) {
26830 trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
26831 }
26832 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
26833 if (!resolved_1)
26834 return undefined;
26835 var resolvedValue = resolved_1.value;
26836 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
26837 var path = realPath(resolvedValue.path, host, traceEnabled);
26838 var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
26839 resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath });
26840 }
26841 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
26842 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
26843 }
26844 else {
26845 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
26846 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
26847 // Treat explicit "node_modules" import as an external library import.
26848 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
26849 }
26850 }
26851 }
26852 function realPath(path, host, traceEnabled) {
26853 if (!host.realpath) {
26854 return path;
26855 }
26856 var real = ts.normalizePath(host.realpath(path));
26857 if (traceEnabled) {
26858 trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
26859 }
26860 ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line
26861 return real;
26862 }
26863 function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
26864 if (state.traceEnabled) {
26865 trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
26866 }
26867 if (!ts.hasTrailingDirectorySeparator(candidate)) {
26868 if (!onlyRecordFailures) {
26869 var parentOfCandidate = ts.getDirectoryPath(candidate);
26870 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
26871 if (state.traceEnabled) {
26872 trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
26873 }
26874 onlyRecordFailures = true;
26875 }
26876 }
26877 var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
26878 if (resolvedFromFile) {
26879 var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
26880 var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state);
26881 var packageId = packageInfo && packageInfo.packageId;
26882 return withPackageId(packageId, resolvedFromFile);
26883 }
26884 }
26885 if (!onlyRecordFailures) {
26886 var candidateExists = ts.directoryProbablyExists(candidate, state.host);
26887 if (!candidateExists) {
26888 if (state.traceEnabled) {
26889 trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
26890 }
26891 onlyRecordFailures = true;
26892 }
26893 }
26894 return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
26895 }
26896 /*@internal*/
26897 ts.nodeModulesPathPart = "/node_modules/";
26898 /*@internal*/
26899 function pathContainsNodeModules(path) {
26900 return ts.stringContains(path, ts.nodeModulesPathPart);
26901 }
26902 ts.pathContainsNodeModules = pathContainsNodeModules;
26903 /**
26904 * This will be called on the successfully resolved path from `loadModuleFromFile`.
26905 * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
26906 *
26907 * packageDirectory is the directory of the package itself.
26908 * subModuleName is the path within the package.
26909 * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.)
26910 * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }.
26911 * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }.
26912 * For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }.
26913 */
26914 function parseNodeModuleFromPath(resolved) {
26915 var path = ts.normalizePath(resolved.path);
26916 var idx = path.lastIndexOf(ts.nodeModulesPathPart);
26917 if (idx === -1) {
26918 return undefined;
26919 }
26920 var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
26921 var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
26922 if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
26923 indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
26924 }
26925 var packageDirectory = path.slice(0, indexAfterPackageName);
26926 var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts" /* Dts */;
26927 return { packageDirectory: packageDirectory, subModuleName: subModuleName };
26928 }
26929 function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
26930 var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
26931 return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
26932 }
26933 function addExtensionAndIndex(path) {
26934 if (path === "") {
26935 return "index.d.ts";
26936 }
26937 if (ts.endsWith(path, ".d.ts")) {
26938 return path;
26939 }
26940 if (path === "index" || ts.endsWith(path, "/index")) {
26941 return path + ".d.ts";
26942 }
26943 return path + "/index.d.ts";
26944 }
26945 function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
26946 return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
26947 }
26948 /**
26949 * @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
26950 * 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.
26951 */
26952 function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
26953 if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
26954 var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
26955 return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
26956 }
26957 // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
26958 var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
26959 if (resolvedByAddingExtension) {
26960 return resolvedByAddingExtension;
26961 }
26962 // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
26963 // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
26964 if (ts.hasJSFileExtension(candidate)) {
26965 var extensionless = ts.removeFileExtension(candidate);
26966 if (state.traceEnabled) {
26967 var extension = candidate.substring(extensionless.length);
26968 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
26969 }
26970 return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
26971 }
26972 }
26973 /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
26974 function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
26975 if (!onlyRecordFailures) {
26976 // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
26977 var directory = ts.getDirectoryPath(candidate);
26978 if (directory) {
26979 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
26980 }
26981 }
26982 switch (extensions) {
26983 case Extensions.DtsOnly:
26984 return tryExtension(".d.ts" /* Dts */);
26985 case Extensions.TypeScript:
26986 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
26987 case Extensions.JavaScript:
26988 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
26989 case Extensions.TSConfig:
26990 case Extensions.Json:
26991 return tryExtension(".json" /* Json */);
26992 }
26993 function tryExtension(ext) {
26994 var path = tryFile(candidate + ext, onlyRecordFailures, state);
26995 return path === undefined ? undefined : { path: path, ext: ext };
26996 }
26997 }
26998 /** Return the file if it exists. */
26999 function tryFile(fileName, onlyRecordFailures, state) {
27000 if (!onlyRecordFailures) {
27001 if (state.host.fileExists(fileName)) {
27002 if (state.traceEnabled) {
27003 trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
27004 }
27005 return fileName;
27006 }
27007 else {
27008 if (state.traceEnabled) {
27009 trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
27010 }
27011 }
27012 }
27013 state.failedLookupLocations.push(fileName);
27014 return undefined;
27015 }
27016 function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
27017 if (considerPackageJson === void 0) { considerPackageJson = true; }
27018 var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined;
27019 var packageId = packageInfo && packageInfo.packageId;
27020 var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
27021 var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state);
27022 return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
27023 }
27024 function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) {
27025 var host = state.host, traceEnabled = state.traceEnabled;
27026 var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
27027 var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
27028 if (directoryExists && host.fileExists(packageJsonPath)) {
27029 var packageJsonContent = ts.readJson(packageJsonPath, host);
27030 if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName
27031 var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state);
27032 if (typeof path === "string") {
27033 subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1));
27034 }
27035 else {
27036 var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state);
27037 if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) {
27038 var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1);
27039 subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) {
27040 return ts.tryRemoveExtension(potentialSubModule_1, extension);
27041 }) || potentialSubModule_1) + ".d.ts" /* Dts */;
27042 }
27043 else {
27044 subModuleName = "index.d.ts";
27045 }
27046 }
27047 }
27048 if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) {
27049 subModuleName = addExtensionAndIndex(subModuleName);
27050 }
27051 var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
27052 var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string"
27053 ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version }
27054 : undefined;
27055 if (traceEnabled) {
27056 if (packageId) {
27057 trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId));
27058 }
27059 else {
27060 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
27061 }
27062 }
27063 return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths };
27064 }
27065 else {
27066 if (directoryExists && traceEnabled) {
27067 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
27068 }
27069 // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
27070 state.failedLookupLocations.push(packageJsonPath);
27071 }
27072 }
27073 function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
27074 var packageFile;
27075 if (jsonContent) {
27076 switch (extensions) {
27077 case Extensions.JavaScript:
27078 case Extensions.Json:
27079 packageFile = readPackageJsonMainField(jsonContent, candidate, state);
27080 break;
27081 case Extensions.TypeScript:
27082 // When resolving typescript modules, try resolving using main field as well
27083 packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
27084 break;
27085 case Extensions.DtsOnly:
27086 packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
27087 break;
27088 case Extensions.TSConfig:
27089 packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
27090 break;
27091 default:
27092 return ts.Debug.assertNever(extensions);
27093 }
27094 }
27095 var loader = function (extensions, candidate, onlyRecordFailures, state) {
27096 var fromFile = tryFile(candidate, onlyRecordFailures, state);
27097 if (fromFile) {
27098 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
27099 if (resolved) {
27100 return noPackageId(resolved);
27101 }
27102 if (state.traceEnabled) {
27103 trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
27104 }
27105 }
27106 // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
27107 var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
27108 // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
27109 return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
27110 };
27111 var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
27112 var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
27113 var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
27114 if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
27115 var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
27116 if (state.traceEnabled) {
27117 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);
27118 }
27119 var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
27120 if (result) {
27121 return removeIgnoredPackageId(result.value);
27122 }
27123 }
27124 // It won't have a `packageId` set, because we disabled `considerPackageJson`.
27125 var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
27126 if (packageFileResult)
27127 return packageFileResult;
27128 return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
27129 }
27130 /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
27131 function resolvedIfExtensionMatches(extensions, path) {
27132 var ext = ts.tryGetExtensionFromPath(path);
27133 return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
27134 }
27135 /** True if `extension` is one of the supported `extensions`. */
27136 function extensionIsOk(extensions, extension) {
27137 switch (extensions) {
27138 case Extensions.JavaScript:
27139 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
27140 case Extensions.TSConfig:
27141 case Extensions.Json:
27142 return extension === ".json" /* Json */;
27143 case Extensions.TypeScript:
27144 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
27145 case Extensions.DtsOnly:
27146 return extension === ".d.ts" /* Dts */;
27147 }
27148 }
27149 /* @internal */
27150 function parsePackageName(moduleName) {
27151 var idx = moduleName.indexOf(ts.directorySeparator);
27152 if (moduleName[0] === "@") {
27153 idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
27154 }
27155 return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
27156 }
27157 ts.parsePackageName = parsePackageName;
27158 function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
27159 return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
27160 }
27161 function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
27162 // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
27163 return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
27164 }
27165 function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
27166 var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
27167 return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
27168 if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
27169 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
27170 if (resolutionFromCache) {
27171 return resolutionFromCache;
27172 }
27173 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
27174 }
27175 });
27176 }
27177 function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
27178 var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
27179 var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
27180 if (!nodeModulesFolderExists && state.traceEnabled) {
27181 trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
27182 }
27183 var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
27184 if (packageResult) {
27185 return packageResult;
27186 }
27187 if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
27188 var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
27189 var nodeModulesAtTypesExists = nodeModulesFolderExists;
27190 if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
27191 if (state.traceEnabled) {
27192 trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
27193 }
27194 nodeModulesAtTypesExists = false;
27195 }
27196 return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
27197 }
27198 }
27199 function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
27200 var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
27201 // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
27202 var packageJsonContent;
27203 var packageId;
27204 var versionPaths;
27205 var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state);
27206 if (packageInfo) {
27207 (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths);
27208 var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
27209 if (fromFile) {
27210 return noPackageId(fromFile);
27211 }
27212 var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths);
27213 return withPackageId(packageId, fromDirectory);
27214 }
27215 var loader = function (extensions, candidate, onlyRecordFailures, state) {
27216 var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
27217 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths);
27218 return withPackageId(packageId, pathAndExtension);
27219 };
27220 var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
27221 if (rest !== "") { // If "rest" is empty, we just did this search above.
27222 var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
27223 // 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.
27224 var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state);
27225 if (packageInfo_1)
27226 (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths);
27227 if (versionPaths) {
27228 if (state.traceEnabled) {
27229 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, rest);
27230 }
27231 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
27232 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state);
27233 if (fromPaths) {
27234 return fromPaths.value;
27235 }
27236 }
27237 }
27238 return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
27239 }
27240 function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
27241 var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
27242 if (matchedPattern) {
27243 var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
27244 var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
27245 if (state.traceEnabled) {
27246 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
27247 }
27248 var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
27249 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
27250 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
27251 if (state.traceEnabled) {
27252 trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
27253 }
27254 // A path mapping may have an extension, in contrast to an import, which should omit it.
27255 var extension = ts.tryGetExtensionFromPath(candidate);
27256 if (extension !== undefined) {
27257 var path_1 = tryFile(candidate, onlyRecordFailures, state);
27258 if (path_1 !== undefined) {
27259 return noPackageId({ path: path_1, ext: extension });
27260 }
27261 }
27262 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
27263 });
27264 return { value: resolved };
27265 }
27266 }
27267 /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
27268 var mangledScopedPackageSeparator = "__";
27269 /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
27270 function mangleScopedPackageNameWithTrace(packageName, state) {
27271 var mangled = mangleScopedPackageName(packageName);
27272 if (state.traceEnabled && mangled !== packageName) {
27273 trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
27274 }
27275 return mangled;
27276 }
27277 /* @internal */
27278 function getTypesPackageName(packageName) {
27279 return "@types/" + mangleScopedPackageName(packageName);
27280 }
27281 ts.getTypesPackageName = getTypesPackageName;
27282 /* @internal */
27283 function mangleScopedPackageName(packageName) {
27284 if (ts.startsWith(packageName, "@")) {
27285 var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
27286 if (replaceSlash !== packageName) {
27287 return replaceSlash.slice(1); // Take off the "@"
27288 }
27289 }
27290 return packageName;
27291 }
27292 ts.mangleScopedPackageName = mangleScopedPackageName;
27293 /* @internal */
27294 function getPackageNameFromTypesPackageName(mangledName) {
27295 var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
27296 if (withoutAtTypePrefix !== mangledName) {
27297 return unmangleScopedPackageName(withoutAtTypePrefix);
27298 }
27299 return mangledName;
27300 }
27301 ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
27302 /* @internal */
27303 function unmangleScopedPackageName(typesPackageName) {
27304 return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
27305 "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
27306 typesPackageName;
27307 }
27308 ts.unmangleScopedPackageName = unmangleScopedPackageName;
27309 function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
27310 var _a;
27311 var result = cache && cache.get(containingDirectory);
27312 if (result) {
27313 if (state.traceEnabled) {
27314 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
27315 }
27316 (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations);
27317 return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
27318 }
27319 }
27320 function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
27321 var traceEnabled = isTraceEnabled(compilerOptions, host);
27322 var failedLookupLocations = [];
27323 var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
27324 var containingDirectory = ts.getDirectoryPath(containingFile);
27325 var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
27326 // No originalPath because classic resolution doesn't resolve realPath
27327 return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations);
27328 function tryResolve(extensions) {
27329 var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
27330 if (resolvedUsingSettings) {
27331 return { value: resolvedUsingSettings };
27332 }
27333 if (!ts.isExternalModuleNameRelative(moduleName)) {
27334 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
27335 // Climb up parent directories looking for a module.
27336 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
27337 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
27338 if (resolutionFromCache) {
27339 return resolutionFromCache;
27340 }
27341 var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
27342 return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
27343 });
27344 if (resolved_3) {
27345 return resolved_3;
27346 }
27347 if (extensions === Extensions.TypeScript) {
27348 // If we didn't find the file normally, look it up in @types.
27349 return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
27350 }
27351 }
27352 else {
27353 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
27354 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
27355 }
27356 }
27357 }
27358 ts.classicNameResolver = classicNameResolver;
27359 /**
27360 * LSHost may load a module from a global cache of typings.
27361 * This is the minumum code needed to expose that functionality; the rest is in LSHost.
27362 */
27363 /* @internal */
27364 function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
27365 var traceEnabled = isTraceEnabled(compilerOptions, host);
27366 if (traceEnabled) {
27367 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);
27368 }
27369 var failedLookupLocations = [];
27370 var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
27371 var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
27372 return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations);
27373 }
27374 ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
27375 /**
27376 * Wraps value to SearchResult.
27377 * @returns undefined if value is undefined or { value } otherwise
27378 */
27379 function toSearchResult(value) {
27380 return value !== undefined ? { value: value } : undefined;
27381 }
27382})(ts || (ts = {}));
27383/* @internal */
27384var ts;
27385(function (ts) {
27386 var ModuleInstanceState;
27387 (function (ModuleInstanceState) {
27388 ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
27389 ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
27390 ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
27391 })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
27392 function getModuleInstanceState(node) {
27393 return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */;
27394 }
27395 ts.getModuleInstanceState = getModuleInstanceState;
27396 function getModuleInstanceStateWorker(node) {
27397 // A module is uninstantiated if it contains only
27398 switch (node.kind) {
27399 // 1. interface declarations, type alias declarations
27400 case 241 /* InterfaceDeclaration */:
27401 case 242 /* TypeAliasDeclaration */:
27402 return 0 /* NonInstantiated */;
27403 // 2. const enum declarations
27404 case 243 /* EnumDeclaration */:
27405 if (ts.isEnumConst(node)) {
27406 return 2 /* ConstEnumOnly */;
27407 }
27408 break;
27409 // 3. non-exported import declarations
27410 case 249 /* ImportDeclaration */:
27411 case 248 /* ImportEqualsDeclaration */:
27412 if (!(ts.hasModifier(node, 1 /* Export */))) {
27413 return 0 /* NonInstantiated */;
27414 }
27415 break;
27416 // 4. other uninstantiated module declarations.
27417 case 245 /* ModuleBlock */: {
27418 var state_1 = 0 /* NonInstantiated */;
27419 ts.forEachChild(node, function (n) {
27420 var childState = getModuleInstanceStateWorker(n);
27421 switch (childState) {
27422 case 0 /* NonInstantiated */:
27423 // child is non-instantiated - continue searching
27424 return;
27425 case 2 /* ConstEnumOnly */:
27426 // child is const enum only - record state and continue searching
27427 state_1 = 2 /* ConstEnumOnly */;
27428 return;
27429 case 1 /* Instantiated */:
27430 // child is instantiated - record state and stop
27431 state_1 = 1 /* Instantiated */;
27432 return true;
27433 default:
27434 ts.Debug.assertNever(childState);
27435 }
27436 });
27437 return state_1;
27438 }
27439 case 244 /* ModuleDeclaration */:
27440 return getModuleInstanceState(node);
27441 case 72 /* Identifier */:
27442 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
27443 // be considered the same as type alias
27444 if (node.isInJSDocNamespace) {
27445 return 0 /* NonInstantiated */;
27446 }
27447 }
27448 return 1 /* Instantiated */;
27449 }
27450 var ContainerFlags;
27451 (function (ContainerFlags) {
27452 // The current node is not a container, and no container manipulation should happen before
27453 // recursing into it.
27454 ContainerFlags[ContainerFlags["None"] = 0] = "None";
27455 // The current node is a container. It should be set as the current container (and block-
27456 // container) before recursing into it. The current node does not have locals. Examples:
27457 //
27458 // Classes, ObjectLiterals, TypeLiterals, Interfaces...
27459 ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
27460 // The current node is a block-scoped-container. It should be set as the current block-
27461 // container before recursing into it. Examples:
27462 //
27463 // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
27464 ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
27465 // The current node is the container of a control flow path. The current control flow should
27466 // be saved and restored, and a new control flow initialized within the container.
27467 ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
27468 ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
27469 ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
27470 ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
27471 ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
27472 ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
27473 })(ContainerFlags || (ContainerFlags = {}));
27474 var flowNodeCreated = ts.identity;
27475 var binder = createBinder();
27476 function bindSourceFile(file, options) {
27477 ts.performance.mark("beforeBind");
27478 binder(file, options);
27479 ts.performance.mark("afterBind");
27480 ts.performance.measure("Bind", "beforeBind", "afterBind");
27481 }
27482 ts.bindSourceFile = bindSourceFile;
27483 function createBinder() {
27484 var file;
27485 var options;
27486 var languageVersion;
27487 var parent;
27488 var container;
27489 var thisParentContainer; // Container one level up
27490 var blockScopeContainer;
27491 var lastContainer;
27492 var delayedTypeAliases;
27493 var seenThisKeyword;
27494 // state used by control flow analysis
27495 var currentFlow;
27496 var currentBreakTarget;
27497 var currentContinueTarget;
27498 var currentReturnTarget;
27499 var currentTrueTarget;
27500 var currentFalseTarget;
27501 var preSwitchCaseFlow;
27502 var activeLabels;
27503 var hasExplicitReturn;
27504 // state used for emit helpers
27505 var emitFlags;
27506 // If this file is an external module, then it is automatically in strict-mode according to
27507 // ES6. If it is not an external module, then we'll determine if it is in strict mode or
27508 // not depending on if we see "use strict" in certain places or if we hit a class/namespace
27509 // or if compiler options contain alwaysStrict.
27510 var inStrictMode;
27511 var symbolCount = 0;
27512 var Symbol; // tslint:disable-line variable-name
27513 var classifiableNames;
27514 var unreachableFlow = { flags: 1 /* Unreachable */ };
27515 var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
27516 // state used to aggregate transform flags during bind.
27517 var subtreeTransformFlags = 0 /* None */;
27518 var skipTransformFlagAggregation;
27519 /**
27520 * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
27521 * 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)
27522 * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
27523 */
27524 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
27525 return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
27526 }
27527 function bindSourceFile(f, opts) {
27528 file = f;
27529 options = opts;
27530 languageVersion = ts.getEmitScriptTarget(options);
27531 inStrictMode = bindInStrictMode(file, opts);
27532 classifiableNames = ts.createUnderscoreEscapedMap();
27533 symbolCount = 0;
27534 skipTransformFlagAggregation = file.isDeclarationFile;
27535 Symbol = ts.objectAllocator.getSymbolConstructor();
27536 if (!file.locals) {
27537 bind(file);
27538 file.symbolCount = symbolCount;
27539 file.classifiableNames = classifiableNames;
27540 delayedBindJSDocTypedefTag();
27541 }
27542 file = undefined;
27543 options = undefined;
27544 languageVersion = undefined;
27545 parent = undefined;
27546 container = undefined;
27547 thisParentContainer = undefined;
27548 blockScopeContainer = undefined;
27549 lastContainer = undefined;
27550 delayedTypeAliases = undefined;
27551 seenThisKeyword = false;
27552 currentFlow = undefined;
27553 currentBreakTarget = undefined;
27554 currentContinueTarget = undefined;
27555 currentReturnTarget = undefined;
27556 currentTrueTarget = undefined;
27557 currentFalseTarget = undefined;
27558 activeLabels = undefined;
27559 hasExplicitReturn = false;
27560 emitFlags = 0 /* None */;
27561 subtreeTransformFlags = 0 /* None */;
27562 }
27563 return bindSourceFile;
27564 function bindInStrictMode(file, opts) {
27565 if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
27566 // bind in strict mode source files with alwaysStrict option
27567 return true;
27568 }
27569 else {
27570 return !!file.externalModuleIndicator;
27571 }
27572 }
27573 function createSymbol(flags, name) {
27574 symbolCount++;
27575 return new Symbol(flags, name);
27576 }
27577 function addDeclarationToSymbol(symbol, node, symbolFlags) {
27578 symbol.flags |= symbolFlags;
27579 node.symbol = symbol;
27580 symbol.declarations = ts.append(symbol.declarations, node);
27581 if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
27582 symbol.exports = ts.createSymbolTable();
27583 }
27584 if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
27585 symbol.members = ts.createSymbolTable();
27586 }
27587 // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
27588 if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
27589 symbol.constEnumOnlyModule = false;
27590 }
27591 if (symbolFlags & 67220415 /* Value */) {
27592 setValueDeclaration(symbol, node);
27593 }
27594 }
27595 function setValueDeclaration(symbol, node) {
27596 var valueDeclaration = symbol.valueDeclaration;
27597 if (!valueDeclaration ||
27598 (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) ||
27599 (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) {
27600 // other kinds of value declarations take precedence over modules and assignment declarations
27601 symbol.valueDeclaration = node;
27602 }
27603 }
27604 // Should not be called on a declaration with a computed property name,
27605 // unless it is a well known Symbol.
27606 function getDeclarationName(node) {
27607 if (node.kind === 254 /* ExportAssignment */) {
27608 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
27609 }
27610 var name = ts.getNameOfDeclaration(node);
27611 if (name) {
27612 if (ts.isAmbientModule(node)) {
27613 var moduleName = ts.getTextOfIdentifierOrLiteral(name);
27614 return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
27615 }
27616 if (name.kind === 149 /* ComputedPropertyName */) {
27617 var nameExpression = name.expression;
27618 // treat computed property names where expression is string/numeric literal as just string/numeric literal
27619 if (ts.isStringOrNumericLiteralLike(nameExpression)) {
27620 return ts.escapeLeadingUnderscores(nameExpression.text);
27621 }
27622 ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
27623 return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
27624 }
27625 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
27626 }
27627 switch (node.kind) {
27628 case 157 /* Constructor */:
27629 return "__constructor" /* Constructor */;
27630 case 165 /* FunctionType */:
27631 case 160 /* CallSignature */:
27632 case 298 /* JSDocSignature */:
27633 return "__call" /* Call */;
27634 case 166 /* ConstructorType */:
27635 case 161 /* ConstructSignature */:
27636 return "__new" /* New */;
27637 case 162 /* IndexSignature */:
27638 return "__index" /* Index */;
27639 case 255 /* ExportDeclaration */:
27640 return "__export" /* ExportStar */;
27641 case 284 /* SourceFile */:
27642 // json file should behave as
27643 // module.exports = ...
27644 return "export=" /* ExportEquals */;
27645 case 204 /* BinaryExpression */:
27646 if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
27647 // module.exports = ...
27648 return "export=" /* ExportEquals */;
27649 }
27650 ts.Debug.fail("Unknown binary declaration kind");
27651 break;
27652 case 294 /* JSDocFunctionType */:
27653 return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
27654 case 151 /* Parameter */:
27655 // Parameters with names are handled at the top of this function. Parameters
27656 // without names can only come from JSDocFunctionTypes.
27657 ts.Debug.assert(node.parent.kind === 294 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
27658 var functionType = node.parent;
27659 var index = functionType.parameters.indexOf(node);
27660 return "arg" + index;
27661 }
27662 }
27663 function getDisplayName(node) {
27664 return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node)));
27665 }
27666 /**
27667 * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
27668 * @param symbolTable - The symbol table which node will be added to.
27669 * @param parent - node's parent declaration.
27670 * @param node - The declaration to be added to the symbol table
27671 * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
27672 * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
27673 */
27674 function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
27675 ts.Debug.assert(!ts.hasDynamicName(node));
27676 var isDefaultExport = ts.hasModifier(node, 512 /* Default */);
27677 // The exported symbol for an export default function/class node is always named "default"
27678 var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
27679 var symbol;
27680 if (name === undefined) {
27681 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
27682 }
27683 else {
27684 // Check and see if the symbol table already has a symbol with this name. If not,
27685 // create a new symbol with this name and add it to the table. Note that we don't
27686 // give the new symbol any flags *yet*. This ensures that it will not conflict
27687 // with the 'excludes' flags we pass in.
27688 //
27689 // If we do get an existing symbol, see if it conflicts with the new symbol we're
27690 // creating. For example, a 'var' symbol and a 'class' symbol will conflict within
27691 // the same symbol table. If we have a conflict, report the issue on each
27692 // declaration we have for this symbol, and then create a new symbol for this
27693 // declaration.
27694 //
27695 // Note that when properties declared in Javascript constructors
27696 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
27697 // Always. This allows the common Javascript pattern of overwriting a prototype method
27698 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
27699 //
27700 // If we created a new symbol, either because we didn't have a symbol with this name
27701 // in the symbol table, or we conflicted with an existing symbol, then just add this
27702 // node as the sole declaration of the new symbol.
27703 //
27704 // Otherwise, we'll be merging into a compatible existing symbol (for example when
27705 // you have multiple 'vars' with the same name in the same container). In this case
27706 // just add this node into the declarations list of the symbol.
27707 symbol = symbolTable.get(name);
27708 if (includes & 2885600 /* Classifiable */) {
27709 classifiableNames.set(name, true);
27710 }
27711 if (!symbol) {
27712 symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
27713 if (isReplaceableByMethod)
27714 symbol.isReplaceableByMethod = true;
27715 }
27716 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
27717 // A symbol already exists, so don't add this as a declaration.
27718 return symbol;
27719 }
27720 else if (symbol.flags & excludes) {
27721 if (symbol.isReplaceableByMethod) {
27722 // Javascript constructor-declared symbols can be discarded in favor of
27723 // prototype symbols like methods.
27724 symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
27725 }
27726 else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
27727 // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
27728 if (ts.isNamedDeclaration(node)) {
27729 node.name.parent = node;
27730 }
27731 // Report errors every position with duplicate declaration
27732 // Report errors on previous encountered declarations
27733 var message_1 = symbol.flags & 2 /* BlockScopedVariable */
27734 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
27735 : ts.Diagnostics.Duplicate_identifier_0;
27736 var messageNeedsName_1 = true;
27737 if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
27738 message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
27739 messageNeedsName_1 = false;
27740 }
27741 var multipleDefaultExports_1 = false;
27742 if (ts.length(symbol.declarations)) {
27743 // If the current node is a default export of some sort, then check if
27744 // there are any other default exports that we need to error on.
27745 // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
27746 if (isDefaultExport) {
27747 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
27748 messageNeedsName_1 = false;
27749 multipleDefaultExports_1 = true;
27750 }
27751 else {
27752 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
27753 // Error on multiple export default in the following case:
27754 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
27755 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
27756 if (symbol.declarations && symbol.declarations.length &&
27757 (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) {
27758 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
27759 messageNeedsName_1 = false;
27760 multipleDefaultExports_1 = true;
27761 }
27762 }
27763 }
27764 var declarationName_1 = ts.getNameOfDeclaration(node) || node;
27765 var relatedInformation_1 = [];
27766 ts.forEach(symbol.declarations, function (declaration, index) {
27767 var decl = ts.getNameOfDeclaration(declaration) || declaration;
27768 var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
27769 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);
27770 if (multipleDefaultExports_1) {
27771 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
27772 }
27773 });
27774 var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
27775 file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInformation_1)) : diag);
27776 symbol = createSymbol(0 /* None */, name);
27777 }
27778 }
27779 }
27780 addDeclarationToSymbol(symbol, node, includes);
27781 if (symbol.parent) {
27782 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
27783 }
27784 else {
27785 symbol.parent = parent;
27786 }
27787 return symbol;
27788 }
27789 function declareModuleMember(node, symbolFlags, symbolExcludes) {
27790 var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
27791 if (symbolFlags & 2097152 /* Alias */) {
27792 if (node.kind === 257 /* ExportSpecifier */ || (node.kind === 248 /* ImportEqualsDeclaration */ && hasExportModifier)) {
27793 return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
27794 }
27795 else {
27796 return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
27797 }
27798 }
27799 else {
27800 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
27801 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
27802 //
27803 // 1. We treat locals and exports of the same name as mutually exclusive within a container.
27804 // That means the binder will issue a Duplicate Identifier error if you mix locals and exports
27805 // with the same name in the same container.
27806 // TODO: Make this a more specific error and decouple it from the exclusion logic.
27807 // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
27808 // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
27809 // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
27810 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
27811 // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
27812 // and this case is specially handled. Module augmentations should only be merged with original module definition
27813 // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
27814 if (ts.isJSDocTypeAlias(node))
27815 ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
27816 if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
27817 if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) {
27818 return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
27819 }
27820 var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0;
27821 var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
27822 local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
27823 node.localSymbol = local;
27824 return local;
27825 }
27826 else {
27827 return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
27828 }
27829 }
27830 }
27831 // All container nodes are kept on a linked list in declaration order. This list is used by
27832 // the getLocalNameOfContainer function in the type checker to validate that the local name
27833 // used for a container is unique.
27834 function bindContainer(node, containerFlags) {
27835 // Before we recurse into a node's children, we first save the existing parent, container
27836 // and block-container. Then after we pop out of processing the children, we restore
27837 // these saved values.
27838 var saveContainer = container;
27839 var saveThisParentContainer = thisParentContainer;
27840 var savedBlockScopeContainer = blockScopeContainer;
27841 // Depending on what kind of node this is, we may have to adjust the current container
27842 // and block-container. If the current node is a container, then it is automatically
27843 // considered the current block-container as well. Also, for containers that we know
27844 // may contain locals, we eagerly initialize the .locals field. We do this because
27845 // it's highly likely that the .locals will be needed to place some child in (for example,
27846 // a parameter, or variable declaration).
27847 //
27848 // However, we do not proactively create the .locals for block-containers because it's
27849 // totally normal and common for block-containers to never actually have a block-scoped
27850 // variable in them. We don't want to end up allocating an object for every 'block' we
27851 // run into when most of them won't be necessary.
27852 //
27853 // Finally, if this is a block-container, then we clear out any existing .locals object
27854 // it may contain within it. This happens in incremental scenarios. Because we can be
27855 // reusing a node from a previous compilation, that node may have had 'locals' created
27856 // for it. We must clear this so we don't accidentally move any stale data forward from
27857 // a previous compilation.
27858 if (containerFlags & 1 /* IsContainer */) {
27859 if (node.kind !== 197 /* ArrowFunction */) {
27860 thisParentContainer = container;
27861 }
27862 container = blockScopeContainer = node;
27863 if (containerFlags & 32 /* HasLocals */) {
27864 container.locals = ts.createSymbolTable();
27865 }
27866 addToContainerChain(container);
27867 }
27868 else if (containerFlags & 2 /* IsBlockScopedContainer */) {
27869 blockScopeContainer = node;
27870 blockScopeContainer.locals = undefined;
27871 }
27872 if (containerFlags & 4 /* IsControlFlowContainer */) {
27873 var saveFlowNodeCreated = flowNodeCreated;
27874 var saveCurrentFlow = currentFlow;
27875 var saveBreakTarget = currentBreakTarget;
27876 var saveContinueTarget = currentContinueTarget;
27877 var saveReturnTarget = currentReturnTarget;
27878 var saveActiveLabels = activeLabels;
27879 var saveHasExplicitReturn = hasExplicitReturn;
27880 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) &&
27881 !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
27882 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
27883 // similarly to break statements that exit to a label just past the statement body.
27884 if (!isIIFE) {
27885 currentFlow = { flags: 2 /* Start */ };
27886 if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
27887 currentFlow.container = node;
27888 }
27889 }
27890 // We create a return control flow graph for IIFEs and constructors. For constructors
27891 // we use the return control flow graph in strict property initialization checks.
27892 currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined;
27893 currentBreakTarget = undefined;
27894 currentContinueTarget = undefined;
27895 activeLabels = undefined;
27896 hasExplicitReturn = false;
27897 flowNodeCreated = ts.identity;
27898 bindChildren(node);
27899 // Reset all reachability check related flags on node (for incremental scenarios)
27900 node.flags &= ~1408 /* ReachabilityAndEmitFlags */;
27901 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
27902 node.flags |= 128 /* HasImplicitReturn */;
27903 if (hasExplicitReturn)
27904 node.flags |= 256 /* HasExplicitReturn */;
27905 }
27906 if (node.kind === 284 /* SourceFile */) {
27907 node.flags |= emitFlags;
27908 }
27909 if (currentReturnTarget) {
27910 addAntecedent(currentReturnTarget, currentFlow);
27911 currentFlow = finishFlowLabel(currentReturnTarget);
27912 if (node.kind === 157 /* Constructor */) {
27913 node.returnFlowNode = currentFlow;
27914 }
27915 }
27916 if (!isIIFE) {
27917 currentFlow = saveCurrentFlow;
27918 }
27919 currentBreakTarget = saveBreakTarget;
27920 currentContinueTarget = saveContinueTarget;
27921 currentReturnTarget = saveReturnTarget;
27922 activeLabels = saveActiveLabels;
27923 hasExplicitReturn = saveHasExplicitReturn;
27924 flowNodeCreated = saveFlowNodeCreated;
27925 }
27926 else if (containerFlags & 64 /* IsInterface */) {
27927 seenThisKeyword = false;
27928 bindChildren(node);
27929 node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */;
27930 }
27931 else {
27932 bindChildren(node);
27933 }
27934 container = saveContainer;
27935 thisParentContainer = saveThisParentContainer;
27936 blockScopeContainer = savedBlockScopeContainer;
27937 }
27938 function bindChildren(node) {
27939 if (skipTransformFlagAggregation) {
27940 bindChildrenWorker(node);
27941 }
27942 else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
27943 skipTransformFlagAggregation = true;
27944 bindChildrenWorker(node);
27945 skipTransformFlagAggregation = false;
27946 subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
27947 }
27948 else {
27949 var savedSubtreeTransformFlags = subtreeTransformFlags;
27950 subtreeTransformFlags = 0;
27951 bindChildrenWorker(node);
27952 subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
27953 }
27954 }
27955 function bindEachFunctionsFirst(nodes) {
27956 bindEach(nodes, function (n) { return n.kind === 239 /* FunctionDeclaration */ ? bind(n) : undefined; });
27957 bindEach(nodes, function (n) { return n.kind !== 239 /* FunctionDeclaration */ ? bind(n) : undefined; });
27958 }
27959 function bindEach(nodes, bindFunction) {
27960 if (bindFunction === void 0) { bindFunction = bind; }
27961 if (nodes === undefined) {
27962 return;
27963 }
27964 if (skipTransformFlagAggregation) {
27965 ts.forEach(nodes, bindFunction);
27966 }
27967 else {
27968 var savedSubtreeTransformFlags = subtreeTransformFlags;
27969 subtreeTransformFlags = 0 /* None */;
27970 var nodeArrayFlags = 0 /* None */;
27971 for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
27972 var node = nodes_2[_i];
27973 bindFunction(node);
27974 nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
27975 }
27976 nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
27977 subtreeTransformFlags |= savedSubtreeTransformFlags;
27978 }
27979 }
27980 function bindEachChild(node) {
27981 ts.forEachChild(node, bind, bindEach);
27982 }
27983 function bindChildrenWorker(node) {
27984 if (checkUnreachable(node)) {
27985 bindEachChild(node);
27986 bindJSDoc(node);
27987 return;
27988 }
27989 switch (node.kind) {
27990 case 224 /* WhileStatement */:
27991 bindWhileStatement(node);
27992 break;
27993 case 223 /* DoStatement */:
27994 bindDoStatement(node);
27995 break;
27996 case 225 /* ForStatement */:
27997 bindForStatement(node);
27998 break;
27999 case 226 /* ForInStatement */:
28000 case 227 /* ForOfStatement */:
28001 bindForInOrForOfStatement(node);
28002 break;
28003 case 222 /* IfStatement */:
28004 bindIfStatement(node);
28005 break;
28006 case 230 /* ReturnStatement */:
28007 case 234 /* ThrowStatement */:
28008 bindReturnOrThrow(node);
28009 break;
28010 case 229 /* BreakStatement */:
28011 case 228 /* ContinueStatement */:
28012 bindBreakOrContinueStatement(node);
28013 break;
28014 case 235 /* TryStatement */:
28015 bindTryStatement(node);
28016 break;
28017 case 232 /* SwitchStatement */:
28018 bindSwitchStatement(node);
28019 break;
28020 case 246 /* CaseBlock */:
28021 bindCaseBlock(node);
28022 break;
28023 case 271 /* CaseClause */:
28024 bindCaseClause(node);
28025 break;
28026 case 233 /* LabeledStatement */:
28027 bindLabeledStatement(node);
28028 break;
28029 case 202 /* PrefixUnaryExpression */:
28030 bindPrefixUnaryExpressionFlow(node);
28031 break;
28032 case 203 /* PostfixUnaryExpression */:
28033 bindPostfixUnaryExpressionFlow(node);
28034 break;
28035 case 204 /* BinaryExpression */:
28036 bindBinaryExpressionFlow(node);
28037 break;
28038 case 198 /* DeleteExpression */:
28039 bindDeleteExpressionFlow(node);
28040 break;
28041 case 205 /* ConditionalExpression */:
28042 bindConditionalExpressionFlow(node);
28043 break;
28044 case 237 /* VariableDeclaration */:
28045 bindVariableDeclarationFlow(node);
28046 break;
28047 case 191 /* CallExpression */:
28048 bindCallExpressionFlow(node);
28049 break;
28050 case 309 /* JSDocTypedefTag */:
28051 case 302 /* JSDocCallbackTag */:
28052 bindJSDocTypeAlias(node);
28053 break;
28054 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
28055 case 284 /* SourceFile */: {
28056 bindEachFunctionsFirst(node.statements);
28057 bind(node.endOfFileToken);
28058 break;
28059 }
28060 case 218 /* Block */:
28061 case 245 /* ModuleBlock */:
28062 bindEachFunctionsFirst(node.statements);
28063 break;
28064 default:
28065 bindEachChild(node);
28066 break;
28067 }
28068 bindJSDoc(node);
28069 }
28070 function isNarrowingExpression(expr) {
28071 switch (expr.kind) {
28072 case 72 /* Identifier */:
28073 case 100 /* ThisKeyword */:
28074 case 189 /* PropertyAccessExpression */:
28075 case 190 /* ElementAccessExpression */:
28076 return isNarrowableReference(expr);
28077 case 191 /* CallExpression */:
28078 return hasNarrowableArgument(expr);
28079 case 195 /* ParenthesizedExpression */:
28080 return isNarrowingExpression(expr.expression);
28081 case 204 /* BinaryExpression */:
28082 return isNarrowingBinaryExpression(expr);
28083 case 202 /* PrefixUnaryExpression */:
28084 return expr.operator === 52 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
28085 case 199 /* TypeOfExpression */:
28086 return isNarrowingExpression(expr.expression);
28087 }
28088 return false;
28089 }
28090 function isNarrowableReference(expr) {
28091 return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ ||
28092 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
28093 ts.isElementAccessExpression(expr) && expr.argumentExpression &&
28094 (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) &&
28095 isNarrowableReference(expr.expression);
28096 }
28097 function hasNarrowableArgument(expr) {
28098 if (expr.arguments) {
28099 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
28100 var argument = _a[_i];
28101 if (isNarrowableReference(argument)) {
28102 return true;
28103 }
28104 }
28105 }
28106 if (expr.expression.kind === 189 /* PropertyAccessExpression */ &&
28107 isNarrowableReference(expr.expression.expression)) {
28108 return true;
28109 }
28110 return false;
28111 }
28112 function isNarrowingTypeofOperands(expr1, expr2) {
28113 return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
28114 }
28115 function isNarrowableInOperands(left, right) {
28116 return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
28117 }
28118 function isNarrowingBinaryExpression(expr) {
28119 switch (expr.operatorToken.kind) {
28120 case 59 /* EqualsToken */:
28121 return isNarrowableReference(expr.left);
28122 case 33 /* EqualsEqualsToken */:
28123 case 34 /* ExclamationEqualsToken */:
28124 case 35 /* EqualsEqualsEqualsToken */:
28125 case 36 /* ExclamationEqualsEqualsToken */:
28126 return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
28127 isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
28128 case 94 /* InstanceOfKeyword */:
28129 return isNarrowableOperand(expr.left);
28130 case 93 /* InKeyword */:
28131 return isNarrowableInOperands(expr.left, expr.right);
28132 case 27 /* CommaToken */:
28133 return isNarrowingExpression(expr.right);
28134 }
28135 return false;
28136 }
28137 function isNarrowableOperand(expr) {
28138 switch (expr.kind) {
28139 case 195 /* ParenthesizedExpression */:
28140 return isNarrowableOperand(expr.expression);
28141 case 204 /* BinaryExpression */:
28142 switch (expr.operatorToken.kind) {
28143 case 59 /* EqualsToken */:
28144 return isNarrowableOperand(expr.left);
28145 case 27 /* CommaToken */:
28146 return isNarrowableOperand(expr.right);
28147 }
28148 }
28149 return isNarrowableReference(expr);
28150 }
28151 function createBranchLabel() {
28152 return {
28153 flags: 4 /* BranchLabel */,
28154 antecedents: undefined
28155 };
28156 }
28157 function createLoopLabel() {
28158 return {
28159 flags: 8 /* LoopLabel */,
28160 antecedents: undefined
28161 };
28162 }
28163 function setFlowNodeReferenced(flow) {
28164 // On first reference we set the Referenced flag, thereafter we set the Shared flag
28165 flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */;
28166 }
28167 function addAntecedent(label, antecedent) {
28168 if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
28169 (label.antecedents || (label.antecedents = [])).push(antecedent);
28170 setFlowNodeReferenced(antecedent);
28171 }
28172 }
28173 function createFlowCondition(flags, antecedent, expression) {
28174 if (antecedent.flags & 1 /* Unreachable */) {
28175 return antecedent;
28176 }
28177 if (!expression) {
28178 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
28179 }
28180 if (expression.kind === 102 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
28181 expression.kind === 87 /* FalseKeyword */ && flags & 32 /* TrueCondition */) {
28182 return unreachableFlow;
28183 }
28184 if (!isNarrowingExpression(expression)) {
28185 return antecedent;
28186 }
28187 setFlowNodeReferenced(antecedent);
28188 return flowNodeCreated({ flags: flags, expression: expression, antecedent: antecedent });
28189 }
28190 function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
28191 if (!isNarrowingExpression(switchStatement.expression)) {
28192 return antecedent;
28193 }
28194 setFlowNodeReferenced(antecedent);
28195 return flowNodeCreated({ flags: 128 /* SwitchClause */, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent });
28196 }
28197 function createFlowAssignment(antecedent, node) {
28198 setFlowNodeReferenced(antecedent);
28199 return flowNodeCreated({ flags: 16 /* Assignment */, antecedent: antecedent, node: node });
28200 }
28201 function createFlowArrayMutation(antecedent, node) {
28202 setFlowNodeReferenced(antecedent);
28203 var res = flowNodeCreated({ flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node });
28204 return res;
28205 }
28206 function finishFlowLabel(flow) {
28207 var antecedents = flow.antecedents;
28208 if (!antecedents) {
28209 return unreachableFlow;
28210 }
28211 if (antecedents.length === 1) {
28212 return antecedents[0];
28213 }
28214 return flow;
28215 }
28216 function isStatementCondition(node) {
28217 var parent = node.parent;
28218 switch (parent.kind) {
28219 case 222 /* IfStatement */:
28220 case 224 /* WhileStatement */:
28221 case 223 /* DoStatement */:
28222 return parent.expression === node;
28223 case 225 /* ForStatement */:
28224 case 205 /* ConditionalExpression */:
28225 return parent.condition === node;
28226 }
28227 return false;
28228 }
28229 function isLogicalExpression(node) {
28230 while (true) {
28231 if (node.kind === 195 /* ParenthesizedExpression */) {
28232 node = node.expression;
28233 }
28234 else if (node.kind === 202 /* PrefixUnaryExpression */ && node.operator === 52 /* ExclamationToken */) {
28235 node = node.operand;
28236 }
28237 else {
28238 return node.kind === 204 /* BinaryExpression */ && (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */ ||
28239 node.operatorToken.kind === 55 /* BarBarToken */);
28240 }
28241 }
28242 }
28243 function isTopLevelLogicalExpression(node) {
28244 while (node.parent.kind === 195 /* ParenthesizedExpression */ ||
28245 node.parent.kind === 202 /* PrefixUnaryExpression */ &&
28246 node.parent.operator === 52 /* ExclamationToken */) {
28247 node = node.parent;
28248 }
28249 return !isStatementCondition(node) && !isLogicalExpression(node.parent);
28250 }
28251 function bindCondition(node, trueTarget, falseTarget) {
28252 var saveTrueTarget = currentTrueTarget;
28253 var saveFalseTarget = currentFalseTarget;
28254 currentTrueTarget = trueTarget;
28255 currentFalseTarget = falseTarget;
28256 bind(node);
28257 currentTrueTarget = saveTrueTarget;
28258 currentFalseTarget = saveFalseTarget;
28259 if (!node || !isLogicalExpression(node)) {
28260 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
28261 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
28262 }
28263 }
28264 function bindIterativeStatement(node, breakTarget, continueTarget) {
28265 var saveBreakTarget = currentBreakTarget;
28266 var saveContinueTarget = currentContinueTarget;
28267 currentBreakTarget = breakTarget;
28268 currentContinueTarget = continueTarget;
28269 bind(node);
28270 currentBreakTarget = saveBreakTarget;
28271 currentContinueTarget = saveContinueTarget;
28272 }
28273 function bindWhileStatement(node) {
28274 var preWhileLabel = createLoopLabel();
28275 var preBodyLabel = createBranchLabel();
28276 var postWhileLabel = createBranchLabel();
28277 addAntecedent(preWhileLabel, currentFlow);
28278 currentFlow = preWhileLabel;
28279 bindCondition(node.expression, preBodyLabel, postWhileLabel);
28280 currentFlow = finishFlowLabel(preBodyLabel);
28281 bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
28282 addAntecedent(preWhileLabel, currentFlow);
28283 currentFlow = finishFlowLabel(postWhileLabel);
28284 }
28285 function bindDoStatement(node) {
28286 var preDoLabel = createLoopLabel();
28287 var enclosingLabeledStatement = node.parent.kind === 233 /* LabeledStatement */
28288 ? ts.lastOrUndefined(activeLabels)
28289 : undefined;
28290 // if do statement is wrapped in labeled statement then target labels for break/continue with or without
28291 // label should be the same
28292 var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel();
28293 var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel();
28294 addAntecedent(preDoLabel, currentFlow);
28295 currentFlow = preDoLabel;
28296 bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
28297 addAntecedent(preConditionLabel, currentFlow);
28298 currentFlow = finishFlowLabel(preConditionLabel);
28299 bindCondition(node.expression, preDoLabel, postDoLabel);
28300 currentFlow = finishFlowLabel(postDoLabel);
28301 }
28302 function bindForStatement(node) {
28303 var preLoopLabel = createLoopLabel();
28304 var preBodyLabel = createBranchLabel();
28305 var postLoopLabel = createBranchLabel();
28306 bind(node.initializer);
28307 addAntecedent(preLoopLabel, currentFlow);
28308 currentFlow = preLoopLabel;
28309 bindCondition(node.condition, preBodyLabel, postLoopLabel);
28310 currentFlow = finishFlowLabel(preBodyLabel);
28311 bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
28312 bind(node.incrementor);
28313 addAntecedent(preLoopLabel, currentFlow);
28314 currentFlow = finishFlowLabel(postLoopLabel);
28315 }
28316 function bindForInOrForOfStatement(node) {
28317 var preLoopLabel = createLoopLabel();
28318 var postLoopLabel = createBranchLabel();
28319 addAntecedent(preLoopLabel, currentFlow);
28320 currentFlow = preLoopLabel;
28321 if (node.kind === 227 /* ForOfStatement */) {
28322 bind(node.awaitModifier);
28323 }
28324 bind(node.expression);
28325 addAntecedent(postLoopLabel, currentFlow);
28326 bind(node.initializer);
28327 if (node.initializer.kind !== 238 /* VariableDeclarationList */) {
28328 bindAssignmentTargetFlow(node.initializer);
28329 }
28330 bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
28331 addAntecedent(preLoopLabel, currentFlow);
28332 currentFlow = finishFlowLabel(postLoopLabel);
28333 }
28334 function bindIfStatement(node) {
28335 var thenLabel = createBranchLabel();
28336 var elseLabel = createBranchLabel();
28337 var postIfLabel = createBranchLabel();
28338 bindCondition(node.expression, thenLabel, elseLabel);
28339 currentFlow = finishFlowLabel(thenLabel);
28340 bind(node.thenStatement);
28341 addAntecedent(postIfLabel, currentFlow);
28342 currentFlow = finishFlowLabel(elseLabel);
28343 bind(node.elseStatement);
28344 addAntecedent(postIfLabel, currentFlow);
28345 currentFlow = finishFlowLabel(postIfLabel);
28346 }
28347 function bindReturnOrThrow(node) {
28348 bind(node.expression);
28349 if (node.kind === 230 /* ReturnStatement */) {
28350 hasExplicitReturn = true;
28351 if (currentReturnTarget) {
28352 addAntecedent(currentReturnTarget, currentFlow);
28353 }
28354 }
28355 currentFlow = unreachableFlow;
28356 }
28357 function findActiveLabel(name) {
28358 if (activeLabels) {
28359 for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) {
28360 var label = activeLabels_1[_i];
28361 if (label.name === name) {
28362 return label;
28363 }
28364 }
28365 }
28366 return undefined;
28367 }
28368 function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
28369 var flowLabel = node.kind === 229 /* BreakStatement */ ? breakTarget : continueTarget;
28370 if (flowLabel) {
28371 addAntecedent(flowLabel, currentFlow);
28372 currentFlow = unreachableFlow;
28373 }
28374 }
28375 function bindBreakOrContinueStatement(node) {
28376 bind(node.label);
28377 if (node.label) {
28378 var activeLabel = findActiveLabel(node.label.escapedText);
28379 if (activeLabel) {
28380 activeLabel.referenced = true;
28381 bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
28382 }
28383 }
28384 else {
28385 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
28386 }
28387 }
28388 function bindTryStatement(node) {
28389 var preFinallyLabel = createBranchLabel();
28390 var preTryFlow = currentFlow;
28391 var tryPriors = [];
28392 var oldFlowNodeCreated = flowNodeCreated;
28393 // We hook the creation of all flow nodes within the `try` scope and store them so we can add _all_ of them
28394 // as possible antecedents of the start of the `catch` or `finally` blocks.
28395 // Don't bother intercepting the call if there's no finally or catch block that needs the information
28396 if (node.catchClause || node.finallyBlock) {
28397 flowNodeCreated = function (node) { return (tryPriors.push(node), node); };
28398 }
28399 bind(node.tryBlock);
28400 flowNodeCreated = oldFlowNodeCreated;
28401 addAntecedent(preFinallyLabel, currentFlow);
28402 var flowAfterTry = currentFlow;
28403 var flowAfterCatch = unreachableFlow;
28404 if (node.catchClause) {
28405 currentFlow = preTryFlow;
28406 if (tryPriors.length) {
28407 var preCatchFlow = createBranchLabel();
28408 addAntecedent(preCatchFlow, currentFlow);
28409 for (var _i = 0, tryPriors_1 = tryPriors; _i < tryPriors_1.length; _i++) {
28410 var p = tryPriors_1[_i];
28411 addAntecedent(preCatchFlow, p);
28412 }
28413 currentFlow = finishFlowLabel(preCatchFlow);
28414 }
28415 bind(node.catchClause);
28416 addAntecedent(preFinallyLabel, currentFlow);
28417 flowAfterCatch = currentFlow;
28418 }
28419 if (node.finallyBlock) {
28420 // We add the nodes within the `try` block to the `finally`'s antecedents if there's no catch block
28421 // (If there is a `catch` block, it will have all these antecedents instead, and the `finally` will
28422 // have the end of the `try` block and the end of the `catch` block)
28423 var preFinallyPrior = preTryFlow;
28424 if (!node.catchClause) {
28425 if (tryPriors.length) {
28426 var preFinallyFlow_1 = createBranchLabel();
28427 addAntecedent(preFinallyFlow_1, preTryFlow);
28428 for (var _a = 0, tryPriors_2 = tryPriors; _a < tryPriors_2.length; _a++) {
28429 var p = tryPriors_2[_a];
28430 addAntecedent(preFinallyFlow_1, p);
28431 }
28432 preFinallyPrior = finishFlowLabel(preFinallyFlow_1);
28433 }
28434 }
28435 // in finally flow is combined from pre-try/flow from try/flow from catch
28436 // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable
28437 // also for finally blocks we inject two extra edges into the flow graph.
28438 // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it
28439 // second -> edge that represents post-finally flow.
28440 // these edges are used in following scenario:
28441 // let a; (1)
28442 // try { a = someOperation(); (2)}
28443 // finally { (3) console.log(a) } (4)
28444 // (5) a
28445 // flow graph for this case looks roughly like this (arrows show ):
28446 // (1-pre-try-flow) <--.. <-- (2-post-try-flow)
28447 // ^ ^
28448 // |*****(3-pre-finally-label) -----|
28449 // ^
28450 // |-- ... <-- (4-post-finally-label) <--- (5)
28451 // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account
28452 // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5)
28453 // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable
28454 // Simply speaking code inside finally block is treated as reachable as pre-try-flow
28455 // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally.
28456 // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from
28457 // final flows of these blocks without taking pre-try flow into account.
28458 //
28459 // extra edges that we inject allows to control this behavior
28460 // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped.
28461 var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preFinallyPrior, lock: {} };
28462 addAntecedent(preFinallyLabel, preFinallyFlow);
28463 currentFlow = finishFlowLabel(preFinallyLabel);
28464 bind(node.finallyBlock);
28465 // if flow after finally is unreachable - keep it
28466 // otherwise check if flows after try and after catch are unreachable
28467 // if yes - convert current flow to unreachable
28468 // i.e.
28469 // try { return "1" } finally { console.log(1); }
28470 // console.log(2); // this line should be unreachable even if flow falls out of finally block
28471 if (!(currentFlow.flags & 1 /* Unreachable */)) {
28472 if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) {
28473 currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow
28474 ? reportedUnreachableFlow
28475 : unreachableFlow;
28476 }
28477 }
28478 if (!(currentFlow.flags & 1 /* Unreachable */)) {
28479 var afterFinallyFlow = flowNodeCreated({ flags: 4096 /* AfterFinally */, antecedent: currentFlow });
28480 preFinallyFlow.lock = afterFinallyFlow;
28481 currentFlow = afterFinallyFlow;
28482 }
28483 }
28484 else {
28485 currentFlow = finishFlowLabel(preFinallyLabel);
28486 }
28487 }
28488 function bindSwitchStatement(node) {
28489 var postSwitchLabel = createBranchLabel();
28490 bind(node.expression);
28491 var saveBreakTarget = currentBreakTarget;
28492 var savePreSwitchCaseFlow = preSwitchCaseFlow;
28493 currentBreakTarget = postSwitchLabel;
28494 preSwitchCaseFlow = currentFlow;
28495 bind(node.caseBlock);
28496 addAntecedent(postSwitchLabel, currentFlow);
28497 var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 272 /* DefaultClause */; });
28498 // We mark a switch statement as possibly exhaustive if it has no default clause and if all
28499 // case clauses have unreachable end points (e.g. they all return).
28500 node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
28501 if (!hasDefault) {
28502 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
28503 }
28504 currentBreakTarget = saveBreakTarget;
28505 preSwitchCaseFlow = savePreSwitchCaseFlow;
28506 currentFlow = finishFlowLabel(postSwitchLabel);
28507 }
28508 function bindCaseBlock(node) {
28509 var savedSubtreeTransformFlags = subtreeTransformFlags;
28510 subtreeTransformFlags = 0;
28511 var clauses = node.clauses;
28512 var fallthroughFlow = unreachableFlow;
28513 for (var i = 0; i < clauses.length; i++) {
28514 var clauseStart = i;
28515 while (!clauses[i].statements.length && i + 1 < clauses.length) {
28516 bind(clauses[i]);
28517 i++;
28518 }
28519 var preCaseLabel = createBranchLabel();
28520 addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1));
28521 addAntecedent(preCaseLabel, fallthroughFlow);
28522 currentFlow = finishFlowLabel(preCaseLabel);
28523 var clause = clauses[i];
28524 bind(clause);
28525 fallthroughFlow = currentFlow;
28526 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
28527 errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch);
28528 }
28529 }
28530 clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */;
28531 subtreeTransformFlags |= savedSubtreeTransformFlags;
28532 }
28533 function bindCaseClause(node) {
28534 var saveCurrentFlow = currentFlow;
28535 currentFlow = preSwitchCaseFlow;
28536 bind(node.expression);
28537 currentFlow = saveCurrentFlow;
28538 bindEach(node.statements);
28539 }
28540 function pushActiveLabel(name, breakTarget, continueTarget) {
28541 var activeLabel = {
28542 name: name,
28543 breakTarget: breakTarget,
28544 continueTarget: continueTarget,
28545 referenced: false
28546 };
28547 (activeLabels || (activeLabels = [])).push(activeLabel);
28548 return activeLabel;
28549 }
28550 function popActiveLabel() {
28551 activeLabels.pop();
28552 }
28553 function bindLabeledStatement(node) {
28554 var preStatementLabel = createLoopLabel();
28555 var postStatementLabel = createBranchLabel();
28556 bind(node.label);
28557 addAntecedent(preStatementLabel, currentFlow);
28558 var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel);
28559 bind(node.statement);
28560 popActiveLabel();
28561 if (!activeLabel.referenced && !options.allowUnusedLabels) {
28562 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
28563 }
28564 if (!node.statement || node.statement.kind !== 223 /* DoStatement */) {
28565 // do statement sets current flow inside bindDoStatement
28566 addAntecedent(postStatementLabel, currentFlow);
28567 currentFlow = finishFlowLabel(postStatementLabel);
28568 }
28569 }
28570 function bindDestructuringTargetFlow(node) {
28571 if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */) {
28572 bindAssignmentTargetFlow(node.left);
28573 }
28574 else {
28575 bindAssignmentTargetFlow(node);
28576 }
28577 }
28578 function bindAssignmentTargetFlow(node) {
28579 if (isNarrowableReference(node)) {
28580 currentFlow = createFlowAssignment(currentFlow, node);
28581 }
28582 else if (node.kind === 187 /* ArrayLiteralExpression */) {
28583 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
28584 var e = _a[_i];
28585 if (e.kind === 208 /* SpreadElement */) {
28586 bindAssignmentTargetFlow(e.expression);
28587 }
28588 else {
28589 bindDestructuringTargetFlow(e);
28590 }
28591 }
28592 }
28593 else if (node.kind === 188 /* ObjectLiteralExpression */) {
28594 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
28595 var p = _c[_b];
28596 if (p.kind === 275 /* PropertyAssignment */) {
28597 bindDestructuringTargetFlow(p.initializer);
28598 }
28599 else if (p.kind === 276 /* ShorthandPropertyAssignment */) {
28600 bindAssignmentTargetFlow(p.name);
28601 }
28602 else if (p.kind === 277 /* SpreadAssignment */) {
28603 bindAssignmentTargetFlow(p.expression);
28604 }
28605 }
28606 }
28607 }
28608 function bindLogicalExpression(node, trueTarget, falseTarget) {
28609 var preRightLabel = createBranchLabel();
28610 if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) {
28611 bindCondition(node.left, preRightLabel, falseTarget);
28612 }
28613 else {
28614 bindCondition(node.left, trueTarget, preRightLabel);
28615 }
28616 currentFlow = finishFlowLabel(preRightLabel);
28617 bind(node.operatorToken);
28618 bindCondition(node.right, trueTarget, falseTarget);
28619 }
28620 function bindPrefixUnaryExpressionFlow(node) {
28621 if (node.operator === 52 /* ExclamationToken */) {
28622 var saveTrueTarget = currentTrueTarget;
28623 currentTrueTarget = currentFalseTarget;
28624 currentFalseTarget = saveTrueTarget;
28625 bindEachChild(node);
28626 currentFalseTarget = currentTrueTarget;
28627 currentTrueTarget = saveTrueTarget;
28628 }
28629 else {
28630 bindEachChild(node);
28631 if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) {
28632 bindAssignmentTargetFlow(node.operand);
28633 }
28634 }
28635 }
28636 function bindPostfixUnaryExpressionFlow(node) {
28637 bindEachChild(node);
28638 if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) {
28639 bindAssignmentTargetFlow(node.operand);
28640 }
28641 }
28642 function bindBinaryExpressionFlow(node) {
28643 var operator = node.operatorToken.kind;
28644 if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) {
28645 if (isTopLevelLogicalExpression(node)) {
28646 var postExpressionLabel = createBranchLabel();
28647 bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
28648 currentFlow = finishFlowLabel(postExpressionLabel);
28649 }
28650 else {
28651 bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
28652 }
28653 }
28654 else {
28655 bindEachChild(node);
28656 if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
28657 bindAssignmentTargetFlow(node.left);
28658 if (operator === 59 /* EqualsToken */ && node.left.kind === 190 /* ElementAccessExpression */) {
28659 var elementAccess = node.left;
28660 if (isNarrowableOperand(elementAccess.expression)) {
28661 currentFlow = createFlowArrayMutation(currentFlow, node);
28662 }
28663 }
28664 }
28665 }
28666 }
28667 function bindDeleteExpressionFlow(node) {
28668 bindEachChild(node);
28669 if (node.expression.kind === 189 /* PropertyAccessExpression */) {
28670 bindAssignmentTargetFlow(node.expression);
28671 }
28672 }
28673 function bindConditionalExpressionFlow(node) {
28674 var trueLabel = createBranchLabel();
28675 var falseLabel = createBranchLabel();
28676 var postExpressionLabel = createBranchLabel();
28677 bindCondition(node.condition, trueLabel, falseLabel);
28678 currentFlow = finishFlowLabel(trueLabel);
28679 bind(node.questionToken);
28680 bind(node.whenTrue);
28681 addAntecedent(postExpressionLabel, currentFlow);
28682 currentFlow = finishFlowLabel(falseLabel);
28683 bind(node.colonToken);
28684 bind(node.whenFalse);
28685 addAntecedent(postExpressionLabel, currentFlow);
28686 currentFlow = finishFlowLabel(postExpressionLabel);
28687 }
28688 function bindInitializedVariableFlow(node) {
28689 var name = !ts.isOmittedExpression(node) ? node.name : undefined;
28690 if (ts.isBindingPattern(name)) {
28691 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
28692 var child = _a[_i];
28693 bindInitializedVariableFlow(child);
28694 }
28695 }
28696 else {
28697 currentFlow = createFlowAssignment(currentFlow, node);
28698 }
28699 }
28700 function bindVariableDeclarationFlow(node) {
28701 bindEachChild(node);
28702 if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
28703 bindInitializedVariableFlow(node);
28704 }
28705 }
28706 function bindJSDocTypeAlias(node) {
28707 node.tagName.parent = node;
28708 if (node.fullName) {
28709 setParentPointers(node, node.fullName);
28710 }
28711 }
28712 function bindCallExpressionFlow(node) {
28713 // If the target of the call expression is a function expression or arrow function we have
28714 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
28715 // the current control flow (which includes evaluation of the IIFE arguments).
28716 var expr = node.expression;
28717 while (expr.kind === 195 /* ParenthesizedExpression */) {
28718 expr = expr.expression;
28719 }
28720 if (expr.kind === 196 /* FunctionExpression */ || expr.kind === 197 /* ArrowFunction */) {
28721 bindEach(node.typeArguments);
28722 bindEach(node.arguments);
28723 bind(node.expression);
28724 }
28725 else {
28726 bindEachChild(node);
28727 }
28728 if (node.expression.kind === 189 /* PropertyAccessExpression */) {
28729 var propertyAccess = node.expression;
28730 if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
28731 currentFlow = createFlowArrayMutation(currentFlow, node);
28732 }
28733 }
28734 }
28735 function getContainerFlags(node) {
28736 switch (node.kind) {
28737 case 209 /* ClassExpression */:
28738 case 240 /* ClassDeclaration */:
28739 case 243 /* EnumDeclaration */:
28740 case 188 /* ObjectLiteralExpression */:
28741 case 168 /* TypeLiteral */:
28742 case 297 /* JSDocTypeLiteral */:
28743 case 268 /* JsxAttributes */:
28744 return 1 /* IsContainer */;
28745 case 241 /* InterfaceDeclaration */:
28746 return 1 /* IsContainer */ | 64 /* IsInterface */;
28747 case 244 /* ModuleDeclaration */:
28748 case 242 /* TypeAliasDeclaration */:
28749 case 181 /* MappedType */:
28750 return 1 /* IsContainer */ | 32 /* HasLocals */;
28751 case 284 /* SourceFile */:
28752 return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
28753 case 156 /* MethodDeclaration */:
28754 if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
28755 return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
28756 }
28757 // falls through
28758 case 157 /* Constructor */:
28759 case 239 /* FunctionDeclaration */:
28760 case 155 /* MethodSignature */:
28761 case 158 /* GetAccessor */:
28762 case 159 /* SetAccessor */:
28763 case 160 /* CallSignature */:
28764 case 298 /* JSDocSignature */:
28765 case 294 /* JSDocFunctionType */:
28766 case 165 /* FunctionType */:
28767 case 161 /* ConstructSignature */:
28768 case 162 /* IndexSignature */:
28769 case 166 /* ConstructorType */:
28770 return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
28771 case 196 /* FunctionExpression */:
28772 case 197 /* ArrowFunction */:
28773 return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
28774 case 245 /* ModuleBlock */:
28775 return 4 /* IsControlFlowContainer */;
28776 case 154 /* PropertyDeclaration */:
28777 return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
28778 case 274 /* CatchClause */:
28779 case 225 /* ForStatement */:
28780 case 226 /* ForInStatement */:
28781 case 227 /* ForOfStatement */:
28782 case 246 /* CaseBlock */:
28783 return 2 /* IsBlockScopedContainer */;
28784 case 218 /* Block */:
28785 // do not treat blocks directly inside a function as a block-scoped-container.
28786 // Locals that reside in this block should go to the function locals. Otherwise 'x'
28787 // would not appear to be a redeclaration of a block scoped local in the following
28788 // example:
28789 //
28790 // function foo() {
28791 // var x;
28792 // let x;
28793 // }
28794 //
28795 // If we placed 'var x' into the function locals and 'let x' into the locals of
28796 // the block, then there would be no collision.
28797 //
28798 // By not creating a new block-scoped-container here, we ensure that both 'var x'
28799 // and 'let x' go into the Function-container's locals, and we do get a collision
28800 // conflict.
28801 return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
28802 }
28803 return 0 /* None */;
28804 }
28805 function addToContainerChain(next) {
28806 if (lastContainer) {
28807 lastContainer.nextContainer = next;
28808 }
28809 lastContainer = next;
28810 }
28811 function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
28812 switch (container.kind) {
28813 // Modules, source files, and classes need specialized handling for how their
28814 // members are declared (for example, a member of a class will go into a specific
28815 // symbol table depending on if it is static or not). We defer to specialized
28816 // handlers to take care of declaring these child members.
28817 case 244 /* ModuleDeclaration */:
28818 return declareModuleMember(node, symbolFlags, symbolExcludes);
28819 case 284 /* SourceFile */:
28820 return declareSourceFileMember(node, symbolFlags, symbolExcludes);
28821 case 209 /* ClassExpression */:
28822 case 240 /* ClassDeclaration */:
28823 return declareClassMember(node, symbolFlags, symbolExcludes);
28824 case 243 /* EnumDeclaration */:
28825 return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
28826 case 168 /* TypeLiteral */:
28827 case 297 /* JSDocTypeLiteral */:
28828 case 188 /* ObjectLiteralExpression */:
28829 case 241 /* InterfaceDeclaration */:
28830 case 268 /* JsxAttributes */:
28831 // Interface/Object-types always have their children added to the 'members' of
28832 // their container. They are only accessible through an instance of their
28833 // container, and are never in scope otherwise (even inside the body of the
28834 // object / type / interface declaring them). An exception is type parameters,
28835 // which are in scope without qualification (similar to 'locals').
28836 return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
28837 case 165 /* FunctionType */:
28838 case 166 /* ConstructorType */:
28839 case 160 /* CallSignature */:
28840 case 161 /* ConstructSignature */:
28841 case 298 /* JSDocSignature */:
28842 case 162 /* IndexSignature */:
28843 case 156 /* MethodDeclaration */:
28844 case 155 /* MethodSignature */:
28845 case 157 /* Constructor */:
28846 case 158 /* GetAccessor */:
28847 case 159 /* SetAccessor */:
28848 case 239 /* FunctionDeclaration */:
28849 case 196 /* FunctionExpression */:
28850 case 197 /* ArrowFunction */:
28851 case 294 /* JSDocFunctionType */:
28852 case 309 /* JSDocTypedefTag */:
28853 case 302 /* JSDocCallbackTag */:
28854 case 242 /* TypeAliasDeclaration */:
28855 case 181 /* MappedType */:
28856 // All the children of these container types are never visible through another
28857 // symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
28858 // they're only accessed 'lexically' (i.e. from code that exists underneath
28859 // their container in the tree). To accomplish this, we simply add their declared
28860 // symbol to the 'locals' of the container. These symbols can then be found as
28861 // the type checker walks up the containers, checking them for matching names.
28862 return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
28863 }
28864 }
28865 function declareClassMember(node, symbolFlags, symbolExcludes) {
28866 return ts.hasModifier(node, 32 /* Static */)
28867 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
28868 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
28869 }
28870 function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
28871 return ts.isExternalModule(file)
28872 ? declareModuleMember(node, symbolFlags, symbolExcludes)
28873 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
28874 }
28875 function hasExportDeclarations(node) {
28876 var body = node.kind === 284 /* SourceFile */ ? node : node.body;
28877 if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
28878 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
28879 var stat = _a[_i];
28880 if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
28881 return true;
28882 }
28883 }
28884 }
28885 return false;
28886 }
28887 function setExportContextFlag(node) {
28888 // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
28889 // declarations with export modifiers) is an export context in which declarations are implicitly exported.
28890 if (node.flags & 4194304 /* Ambient */ && !hasExportDeclarations(node)) {
28891 node.flags |= 32 /* ExportContext */;
28892 }
28893 else {
28894 node.flags &= ~32 /* ExportContext */;
28895 }
28896 }
28897 function bindModuleDeclaration(node) {
28898 setExportContextFlag(node);
28899 if (ts.isAmbientModule(node)) {
28900 if (ts.hasModifier(node, 1 /* Export */)) {
28901 errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
28902 }
28903 if (ts.isModuleAugmentationExternal(node)) {
28904 declareModuleSymbol(node);
28905 }
28906 else {
28907 var pattern = void 0;
28908 if (node.name.kind === 10 /* StringLiteral */) {
28909 var text = node.name.text;
28910 if (ts.hasZeroOrOneAsteriskCharacter(text)) {
28911 pattern = ts.tryParsePattern(text);
28912 }
28913 else {
28914 errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
28915 }
28916 }
28917 var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
28918 file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
28919 }
28920 }
28921 else {
28922 var state = declareModuleSymbol(node);
28923 if (state !== 0 /* NonInstantiated */) {
28924 var symbol = node.symbol;
28925 // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
28926 symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
28927 // Current must be `const enum` only
28928 && state === 2 /* ConstEnumOnly */
28929 // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
28930 && symbol.constEnumOnlyModule !== false;
28931 }
28932 }
28933 }
28934 function declareModuleSymbol(node) {
28935 var state = getModuleInstanceState(node);
28936 var instantiated = state !== 0 /* NonInstantiated */;
28937 declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
28938 return state;
28939 }
28940 function bindFunctionOrConstructorType(node) {
28941 // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
28942 // to the one we would get for: { <...>(...): T }
28943 //
28944 // We do that by making an anonymous type literal symbol, and then setting the function
28945 // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
28946 // from an actual type literal symbol you would have gotten had you used the long form.
28947 var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
28948 addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
28949 var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
28950 addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
28951 typeLiteralSymbol.members = ts.createSymbolTable();
28952 typeLiteralSymbol.members.set(symbol.escapedName, symbol);
28953 }
28954 function bindObjectLiteralExpression(node) {
28955 var ElementKind;
28956 (function (ElementKind) {
28957 ElementKind[ElementKind["Property"] = 1] = "Property";
28958 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
28959 })(ElementKind || (ElementKind = {}));
28960 if (inStrictMode) {
28961 var seen = ts.createUnderscoreEscapedMap();
28962 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
28963 var prop = _a[_i];
28964 if (prop.kind === 277 /* SpreadAssignment */ || prop.name.kind !== 72 /* Identifier */) {
28965 continue;
28966 }
28967 var identifier = prop.name;
28968 // ECMA-262 11.1.5 Object Initializer
28969 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
28970 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
28971 // IsDataDescriptor(propId.descriptor) is true.
28972 // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
28973 // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
28974 // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
28975 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
28976 var currentKind = prop.kind === 275 /* PropertyAssignment */ || prop.kind === 276 /* ShorthandPropertyAssignment */ || prop.kind === 156 /* MethodDeclaration */
28977 ? 1 /* Property */
28978 : 2 /* Accessor */;
28979 var existingKind = seen.get(identifier.escapedText);
28980 if (!existingKind) {
28981 seen.set(identifier.escapedText, currentKind);
28982 continue;
28983 }
28984 if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
28985 var span = ts.getErrorSpanForNode(file, identifier);
28986 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));
28987 }
28988 }
28989 }
28990 return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
28991 }
28992 function bindJsxAttributes(node) {
28993 return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
28994 }
28995 function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
28996 return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
28997 }
28998 function bindAnonymousDeclaration(node, symbolFlags, name) {
28999 var symbol = createSymbol(symbolFlags, name);
29000 if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
29001 symbol.parent = container.symbol;
29002 }
29003 addDeclarationToSymbol(symbol, node, symbolFlags);
29004 return symbol;
29005 }
29006 function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
29007 switch (blockScopeContainer.kind) {
29008 case 244 /* ModuleDeclaration */:
29009 declareModuleMember(node, symbolFlags, symbolExcludes);
29010 break;
29011 case 284 /* SourceFile */:
29012 if (ts.isExternalOrCommonJsModule(container)) {
29013 declareModuleMember(node, symbolFlags, symbolExcludes);
29014 break;
29015 }
29016 // falls through
29017 default:
29018 if (!blockScopeContainer.locals) {
29019 blockScopeContainer.locals = ts.createSymbolTable();
29020 addToContainerChain(blockScopeContainer);
29021 }
29022 declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
29023 }
29024 }
29025 function delayedBindJSDocTypedefTag() {
29026 if (!delayedTypeAliases) {
29027 return;
29028 }
29029 var saveContainer = container;
29030 var saveLastContainer = lastContainer;
29031 var saveBlockScopeContainer = blockScopeContainer;
29032 var saveParent = parent;
29033 var saveCurrentFlow = currentFlow;
29034 for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
29035 var typeAlias = delayedTypeAliases_1[_i];
29036 var host = ts.getJSDocHost(typeAlias);
29037 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
29038 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
29039 currentFlow = { flags: 2 /* Start */ };
29040 parent = typeAlias;
29041 bind(typeAlias.typeExpression);
29042 if (!typeAlias.fullName || typeAlias.fullName.kind === 72 /* Identifier */) {
29043 parent = typeAlias.parent;
29044 bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */);
29045 }
29046 else {
29047 bind(typeAlias.fullName);
29048 }
29049 }
29050 container = saveContainer;
29051 lastContainer = saveLastContainer;
29052 blockScopeContainer = saveBlockScopeContainer;
29053 parent = saveParent;
29054 currentFlow = saveCurrentFlow;
29055 }
29056 // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
29057 // check for reserved words used as identifiers in strict mode code.
29058 function checkStrictModeIdentifier(node) {
29059 if (inStrictMode &&
29060 node.originalKeywordKind >= 109 /* FirstFutureReservedWord */ &&
29061 node.originalKeywordKind <= 117 /* LastFutureReservedWord */ &&
29062 !ts.isIdentifierName(node) &&
29063 !(node.flags & 4194304 /* Ambient */)) {
29064 // Report error only if there are no parse errors in file
29065 if (!file.parseDiagnostics.length) {
29066 file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
29067 }
29068 }
29069 }
29070 function getStrictModeIdentifierMessage(node) {
29071 // Provide specialized messages to help the user understand why we think they're in
29072 // strict mode.
29073 if (ts.getContainingClass(node)) {
29074 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
29075 }
29076 if (file.externalModuleIndicator) {
29077 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
29078 }
29079 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
29080 }
29081 function checkStrictModeBinaryExpression(node) {
29082 if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
29083 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
29084 // Assignment operator(11.13) or of a PostfixExpression(11.3)
29085 checkStrictModeEvalOrArguments(node, node.left);
29086 }
29087 }
29088 function checkStrictModeCatchClause(node) {
29089 // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
29090 // Catch production is eval or arguments
29091 if (inStrictMode && node.variableDeclaration) {
29092 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
29093 }
29094 }
29095 function checkStrictModeDeleteExpression(node) {
29096 // Grammar checking
29097 if (inStrictMode && node.expression.kind === 72 /* Identifier */) {
29098 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
29099 // UnaryExpression is a direct reference to a variable, function argument, or function name
29100 var span = ts.getErrorSpanForNode(file, node.expression);
29101 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
29102 }
29103 }
29104 function isEvalOrArgumentsIdentifier(node) {
29105 return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
29106 }
29107 function checkStrictModeEvalOrArguments(contextNode, name) {
29108 if (name && name.kind === 72 /* Identifier */) {
29109 var identifier = name;
29110 if (isEvalOrArgumentsIdentifier(identifier)) {
29111 // We check first if the name is inside class declaration or class expression; if so give explicit message
29112 // otherwise report generic error message.
29113 var span = ts.getErrorSpanForNode(file, name);
29114 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
29115 }
29116 }
29117 }
29118 function getStrictModeEvalOrArgumentsMessage(node) {
29119 // Provide specialized messages to help the user understand why we think they're in
29120 // strict mode.
29121 if (ts.getContainingClass(node)) {
29122 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
29123 }
29124 if (file.externalModuleIndicator) {
29125 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
29126 }
29127 return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
29128 }
29129 function checkStrictModeFunctionName(node) {
29130 if (inStrictMode) {
29131 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
29132 checkStrictModeEvalOrArguments(node, node.name);
29133 }
29134 }
29135 function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
29136 // Provide specialized messages to help the user understand why we think they're in
29137 // strict mode.
29138 if (ts.getContainingClass(node)) {
29139 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;
29140 }
29141 if (file.externalModuleIndicator) {
29142 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
29143 }
29144 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
29145 }
29146 function checkStrictModeFunctionDeclaration(node) {
29147 if (languageVersion < 2 /* ES2015 */) {
29148 // Report error if function is not top level function declaration
29149 if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
29150 blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
29151 !ts.isFunctionLike(blockScopeContainer)) {
29152 // We check first if the name is inside class declaration or class expression; if so give explicit message
29153 // otherwise report generic error message.
29154 var errorSpan = ts.getErrorSpanForNode(file, node);
29155 file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
29156 }
29157 }
29158 }
29159 function checkStrictModeNumericLiteral(node) {
29160 if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
29161 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
29162 }
29163 }
29164 function checkStrictModePostfixUnaryExpression(node) {
29165 // Grammar checking
29166 // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
29167 // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
29168 // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
29169 if (inStrictMode) {
29170 checkStrictModeEvalOrArguments(node, node.operand);
29171 }
29172 }
29173 function checkStrictModePrefixUnaryExpression(node) {
29174 // Grammar checking
29175 if (inStrictMode) {
29176 if (node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */) {
29177 checkStrictModeEvalOrArguments(node, node.operand);
29178 }
29179 }
29180 }
29181 function checkStrictModeWithStatement(node) {
29182 // Grammar checking for withStatement
29183 if (inStrictMode) {
29184 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
29185 }
29186 }
29187 function checkStrictModeLabeledStatement(node) {
29188 // Grammar checking for labeledStatement
29189 if (inStrictMode && options.target >= 2 /* ES2015 */) {
29190 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
29191 errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
29192 }
29193 }
29194 }
29195 function errorOnFirstToken(node, message, arg0, arg1, arg2) {
29196 var span = ts.getSpanOfTokenAtPosition(file, node.pos);
29197 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
29198 }
29199 function errorOrSuggestionOnNode(isError, node, message) {
29200 errorOrSuggestionOnRange(isError, node, node, message);
29201 }
29202 function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
29203 addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
29204 }
29205 function addErrorOrSuggestionDiagnostic(isError, range, message) {
29206 var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
29207 if (isError) {
29208 file.bindDiagnostics.push(diag);
29209 }
29210 else {
29211 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
29212 }
29213 }
29214 function bind(node) {
29215 if (!node) {
29216 return;
29217 }
29218 node.parent = parent;
29219 var saveInStrictMode = inStrictMode;
29220 // Even though in the AST the jsdoc @typedef node belongs to the current node,
29221 // its symbol might be in the same scope with the current node's symbol. Consider:
29222 //
29223 // /** @typedef {string | number} MyType */
29224 // function foo();
29225 //
29226 // Here the current node is "foo", which is a container, but the scope of "MyType" should
29227 // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
29228 // and skip binding this tag later when binding all the other jsdoc tags.
29229 // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
29230 // and then potentially add the symbol to an appropriate symbol table. Possible
29231 // destination symbol tables are:
29232 //
29233 // 1) The 'exports' table of the current container's symbol.
29234 // 2) The 'members' table of the current container's symbol.
29235 // 3) The 'locals' table of the current container.
29236 //
29237 // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
29238 // (like TypeLiterals for example) will not be put in any table.
29239 bindWorker(node);
29240 // Then we recurse into the children of the node to bind them as well. For certain
29241 // symbols we do specialized work when we recurse. For example, we'll keep track of
29242 // the current 'container' node when it changes. This helps us know which symbol table
29243 // a local should go into for example. Since terminal nodes are known not to have
29244 // children, as an optimization we don't process those.
29245 if (node.kind > 147 /* LastToken */) {
29246 var saveParent = parent;
29247 parent = node;
29248 var containerFlags = getContainerFlags(node);
29249 if (containerFlags === 0 /* None */) {
29250 bindChildren(node);
29251 }
29252 else {
29253 bindContainer(node, containerFlags);
29254 }
29255 parent = saveParent;
29256 }
29257 else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
29258 subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
29259 var saveParent = parent;
29260 if (node.kind === 1 /* EndOfFileToken */)
29261 parent = node;
29262 bindJSDoc(node);
29263 parent = saveParent;
29264 }
29265 inStrictMode = saveInStrictMode;
29266 }
29267 function bindJSDoc(node) {
29268 if (ts.hasJSDocNodes(node)) {
29269 if (ts.isInJSFile(node)) {
29270 for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
29271 var j = _a[_i];
29272 bind(j);
29273 }
29274 }
29275 else {
29276 for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
29277 var j = _c[_b];
29278 setParentPointers(node, j);
29279 }
29280 }
29281 }
29282 }
29283 function updateStrictModeStatementList(statements) {
29284 if (!inStrictMode) {
29285 for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
29286 var statement = statements_1[_i];
29287 if (!ts.isPrologueDirective(statement)) {
29288 return;
29289 }
29290 if (isUseStrictPrologueDirective(statement)) {
29291 inStrictMode = true;
29292 return;
29293 }
29294 }
29295 }
29296 }
29297 /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
29298 function isUseStrictPrologueDirective(node) {
29299 var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
29300 // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
29301 // string to contain unicode escapes (as per ES5).
29302 return nodeText === '"use strict"' || nodeText === "'use strict'";
29303 }
29304 function bindWorker(node) {
29305 switch (node.kind) {
29306 /* Strict mode checks */
29307 case 72 /* Identifier */:
29308 // for typedef type names with namespaces, bind the new jsdoc type symbol here
29309 // because it requires all containing namespaces to be in effect, namely the
29310 // current "blockScopeContainer" needs to be set to its immediate namespace parent.
29311 if (node.isInJSDocNamespace) {
29312 var parentNode = node.parent;
29313 while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
29314 parentNode = parentNode.parent;
29315 }
29316 bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */);
29317 break;
29318 }
29319 // falls through
29320 case 100 /* ThisKeyword */:
29321 if (currentFlow && (ts.isExpression(node) || parent.kind === 276 /* ShorthandPropertyAssignment */)) {
29322 node.flowNode = currentFlow;
29323 }
29324 return checkStrictModeIdentifier(node);
29325 case 189 /* PropertyAccessExpression */:
29326 case 190 /* ElementAccessExpression */:
29327 if (currentFlow && isNarrowableReference(node)) {
29328 node.flowNode = currentFlow;
29329 }
29330 if (ts.isSpecialPropertyDeclaration(node)) {
29331 bindSpecialPropertyDeclaration(node);
29332 }
29333 if (ts.isInJSFile(node) &&
29334 file.commonJsModuleIndicator &&
29335 ts.isModuleExportsPropertyAccessExpression(node) &&
29336 !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
29337 declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */);
29338 }
29339 break;
29340 case 204 /* BinaryExpression */:
29341 var specialKind = ts.getAssignmentDeclarationKind(node);
29342 switch (specialKind) {
29343 case 1 /* ExportsProperty */:
29344 bindExportsPropertyAssignment(node);
29345 break;
29346 case 2 /* ModuleExports */:
29347 bindModuleExportsAssignment(node);
29348 break;
29349 case 3 /* PrototypeProperty */:
29350 bindPrototypePropertyAssignment(node.left, node);
29351 break;
29352 case 6 /* Prototype */:
29353 bindPrototypeAssignment(node);
29354 break;
29355 case 4 /* ThisProperty */:
29356 bindThisPropertyAssignment(node);
29357 break;
29358 case 5 /* Property */:
29359 bindSpecialPropertyAssignment(node);
29360 break;
29361 case 0 /* None */:
29362 // Nothing to do
29363 break;
29364 default:
29365 ts.Debug.fail("Unknown binary expression special property assignment kind");
29366 }
29367 return checkStrictModeBinaryExpression(node);
29368 case 274 /* CatchClause */:
29369 return checkStrictModeCatchClause(node);
29370 case 198 /* DeleteExpression */:
29371 return checkStrictModeDeleteExpression(node);
29372 case 8 /* NumericLiteral */:
29373 return checkStrictModeNumericLiteral(node);
29374 case 203 /* PostfixUnaryExpression */:
29375 return checkStrictModePostfixUnaryExpression(node);
29376 case 202 /* PrefixUnaryExpression */:
29377 return checkStrictModePrefixUnaryExpression(node);
29378 case 231 /* WithStatement */:
29379 return checkStrictModeWithStatement(node);
29380 case 233 /* LabeledStatement */:
29381 return checkStrictModeLabeledStatement(node);
29382 case 178 /* ThisType */:
29383 seenThisKeyword = true;
29384 return;
29385 case 163 /* TypePredicate */:
29386 break; // Binding the children will handle everything
29387 case 150 /* TypeParameter */:
29388 return bindTypeParameter(node);
29389 case 151 /* Parameter */:
29390 return bindParameter(node);
29391 case 237 /* VariableDeclaration */:
29392 return bindVariableDeclarationOrBindingElement(node);
29393 case 186 /* BindingElement */:
29394 node.flowNode = currentFlow;
29395 return bindVariableDeclarationOrBindingElement(node);
29396 case 154 /* PropertyDeclaration */:
29397 case 153 /* PropertySignature */:
29398 return bindPropertyWorker(node);
29399 case 275 /* PropertyAssignment */:
29400 case 276 /* ShorthandPropertyAssignment */:
29401 return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
29402 case 278 /* EnumMember */:
29403 return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */);
29404 case 160 /* CallSignature */:
29405 case 161 /* ConstructSignature */:
29406 case 162 /* IndexSignature */:
29407 return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
29408 case 156 /* MethodDeclaration */:
29409 case 155 /* MethodSignature */:
29410 // If this is an ObjectLiteralExpression method, then it sits in the same space
29411 // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
29412 // so that it will conflict with any other object literal members with the same
29413 // name.
29414 return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */);
29415 case 239 /* FunctionDeclaration */:
29416 return bindFunctionDeclaration(node);
29417 case 157 /* Constructor */:
29418 return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
29419 case 158 /* GetAccessor */:
29420 return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */);
29421 case 159 /* SetAccessor */:
29422 return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
29423 case 165 /* FunctionType */:
29424 case 294 /* JSDocFunctionType */:
29425 case 298 /* JSDocSignature */:
29426 case 166 /* ConstructorType */:
29427 return bindFunctionOrConstructorType(node);
29428 case 168 /* TypeLiteral */:
29429 case 297 /* JSDocTypeLiteral */:
29430 case 181 /* MappedType */:
29431 return bindAnonymousTypeWorker(node);
29432 case 188 /* ObjectLiteralExpression */:
29433 return bindObjectLiteralExpression(node);
29434 case 196 /* FunctionExpression */:
29435 case 197 /* ArrowFunction */:
29436 return bindFunctionExpression(node);
29437 case 191 /* CallExpression */:
29438 var assignmentKind = ts.getAssignmentDeclarationKind(node);
29439 switch (assignmentKind) {
29440 case 7 /* ObjectDefinePropertyValue */:
29441 return bindObjectDefinePropertyAssignment(node);
29442 case 8 /* ObjectDefinePropertyExports */:
29443 return bindObjectDefinePropertyExport(node);
29444 case 9 /* ObjectDefinePrototypeProperty */:
29445 return bindObjectDefinePrototypeProperty(node);
29446 case 0 /* None */:
29447 break; // Nothing to do
29448 default:
29449 return ts.Debug.fail("Unknown call expression assignment declaration kind");
29450 }
29451 if (ts.isInJSFile(node)) {
29452 bindCallExpression(node);
29453 }
29454 break;
29455 // Members of classes, interfaces, and modules
29456 case 209 /* ClassExpression */:
29457 case 240 /* ClassDeclaration */:
29458 // All classes are automatically in strict mode in ES6.
29459 inStrictMode = true;
29460 return bindClassLikeDeclaration(node);
29461 case 241 /* InterfaceDeclaration */:
29462 return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */);
29463 case 242 /* TypeAliasDeclaration */:
29464 return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */);
29465 case 243 /* EnumDeclaration */:
29466 return bindEnumDeclaration(node);
29467 case 244 /* ModuleDeclaration */:
29468 return bindModuleDeclaration(node);
29469 // Jsx-attributes
29470 case 268 /* JsxAttributes */:
29471 return bindJsxAttributes(node);
29472 case 267 /* JsxAttribute */:
29473 return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
29474 // Imports and exports
29475 case 248 /* ImportEqualsDeclaration */:
29476 case 251 /* NamespaceImport */:
29477 case 253 /* ImportSpecifier */:
29478 case 257 /* ExportSpecifier */:
29479 return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
29480 case 247 /* NamespaceExportDeclaration */:
29481 return bindNamespaceExportDeclaration(node);
29482 case 250 /* ImportClause */:
29483 return bindImportClause(node);
29484 case 255 /* ExportDeclaration */:
29485 return bindExportDeclaration(node);
29486 case 254 /* ExportAssignment */:
29487 return bindExportAssignment(node);
29488 case 284 /* SourceFile */:
29489 updateStrictModeStatementList(node.statements);
29490 return bindSourceFileIfExternalModule();
29491 case 218 /* Block */:
29492 if (!ts.isFunctionLike(node.parent)) {
29493 return;
29494 }
29495 // falls through
29496 case 245 /* ModuleBlock */:
29497 return updateStrictModeStatementList(node.statements);
29498 case 304 /* JSDocParameterTag */:
29499 if (node.parent.kind === 298 /* JSDocSignature */) {
29500 return bindParameter(node);
29501 }
29502 if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
29503 break;
29504 }
29505 // falls through
29506 case 310 /* JSDocPropertyTag */:
29507 var propTag = node;
29508 var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
29509 4 /* Property */ | 16777216 /* Optional */ :
29510 4 /* Property */;
29511 return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
29512 case 309 /* JSDocTypedefTag */:
29513 case 302 /* JSDocCallbackTag */:
29514 return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
29515 }
29516 }
29517 function bindPropertyWorker(node) {
29518 return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
29519 }
29520 function bindAnonymousTypeWorker(node) {
29521 return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
29522 }
29523 function bindSourceFileIfExternalModule() {
29524 setExportContextFlag(file);
29525 if (ts.isExternalModule(file)) {
29526 bindSourceFileAsExternalModule();
29527 }
29528 else if (ts.isJsonSourceFile(file)) {
29529 bindSourceFileAsExternalModule();
29530 // Create symbol equivalent for the module.exports = {}
29531 var originalSymbol = file.symbol;
29532 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
29533 file.symbol = originalSymbol;
29534 }
29535 }
29536 function bindSourceFileAsExternalModule() {
29537 bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
29538 }
29539 function bindExportAssignment(node) {
29540 if (!container.symbol || !container.symbol.exports) {
29541 // Export assignment in some sort of block construct
29542 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
29543 }
29544 else {
29545 var flags = ts.exportAssignmentIsAlias(node)
29546 // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
29547 ? 2097152 /* Alias */
29548 // An export default clause with any other expression exports a value
29549 : 4 /* Property */;
29550 // If there is an `export default x;` alias declaration, can't `export default` anything else.
29551 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
29552 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
29553 if (node.isExportEquals) {
29554 // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
29555 setValueDeclaration(symbol, node);
29556 }
29557 }
29558 }
29559 function bindNamespaceExportDeclaration(node) {
29560 if (node.modifiers && node.modifiers.length) {
29561 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
29562 }
29563 var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
29564 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
29565 : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
29566 : undefined;
29567 if (diag) {
29568 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
29569 }
29570 else {
29571 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
29572 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
29573 }
29574 }
29575 function bindExportDeclaration(node) {
29576 if (!container.symbol || !container.symbol.exports) {
29577 // Export * in some sort of block construct
29578 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
29579 }
29580 else if (!node.exportClause) {
29581 // All export * declarations are collected in an __export symbol
29582 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
29583 }
29584 }
29585 function bindImportClause(node) {
29586 if (node.name) {
29587 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
29588 }
29589 }
29590 function setCommonJsModuleIndicator(node) {
29591 if (file.externalModuleIndicator) {
29592 return false;
29593 }
29594 if (!file.commonJsModuleIndicator) {
29595 file.commonJsModuleIndicator = node;
29596 bindSourceFileAsExternalModule();
29597 }
29598 return true;
29599 }
29600 function bindObjectDefinePropertyExport(node) {
29601 if (!setCommonJsModuleIndicator(node)) {
29602 return;
29603 }
29604 var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
29605 if (symbol) {
29606 addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
29607 }
29608 return symbol;
29609 });
29610 if (symbol) {
29611 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
29612 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
29613 }
29614 }
29615 function bindExportsPropertyAssignment(node) {
29616 // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
29617 // expression is the declaration
29618 if (!setCommonJsModuleIndicator(node)) {
29619 return;
29620 }
29621 var lhs = node.left;
29622 var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) {
29623 if (symbol) {
29624 addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
29625 }
29626 return symbol;
29627 });
29628 if (symbol) {
29629 var flags = ts.isClassExpression(node.right) ?
29630 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
29631 4 /* Property */ | 1048576 /* ExportValue */;
29632 declareSymbol(symbol.exports, symbol, lhs, flags, 0 /* None */);
29633 }
29634 }
29635 function bindModuleExportsAssignment(node) {
29636 // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
29637 // is still pointing to 'module.exports'.
29638 // We do not want to consider this as 'export=' since a module can have only one of these.
29639 // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
29640 if (!setCommonJsModuleIndicator(node)) {
29641 return;
29642 }
29643 var assignedExpression = ts.getRightMostAssignedExpression(node.right);
29644 if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
29645 return;
29646 }
29647 // 'module.exports = expr' assignment
29648 var flags = ts.exportAssignmentIsAlias(node)
29649 ? 2097152 /* Alias */
29650 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
29651 declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
29652 }
29653 function bindThisPropertyAssignment(node) {
29654 ts.Debug.assert(ts.isInJSFile(node));
29655 var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
29656 switch (thisContainer.kind) {
29657 case 239 /* FunctionDeclaration */:
29658 case 196 /* FunctionExpression */:
29659 var constructorSymbol = thisContainer.symbol;
29660 // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
29661 if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 59 /* EqualsToken */) {
29662 var l = thisContainer.parent.left;
29663 if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) {
29664 constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
29665 }
29666 }
29667 if (constructorSymbol) {
29668 // Declare a 'member' if the container is an ES5 class or ES6 constructor
29669 constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
29670 // It's acceptable for multiple 'this' assignments of the same identifier to occur
29671 declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */);
29672 }
29673 break;
29674 case 157 /* Constructor */:
29675 case 154 /* PropertyDeclaration */:
29676 case 156 /* MethodDeclaration */:
29677 case 158 /* GetAccessor */:
29678 case 159 /* SetAccessor */:
29679 // this.foo assignment in a JavaScript class
29680 // Bind this property to the containing class
29681 var containingClass = thisContainer.parent;
29682 var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
29683 declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true);
29684 break;
29685 case 284 /* SourceFile */:
29686 // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
29687 if (thisContainer.commonJsModuleIndicator) {
29688 declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
29689 }
29690 else {
29691 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220414 /* FunctionScopedVariableExcludes */);
29692 }
29693 break;
29694 default:
29695 ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer));
29696 }
29697 }
29698 function bindSpecialPropertyDeclaration(node) {
29699 if (node.expression.kind === 100 /* ThisKeyword */) {
29700 bindThisPropertyAssignment(node);
29701 }
29702 else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
29703 if (ts.isPrototypeAccess(node.expression)) {
29704 bindPrototypePropertyAssignment(node, node.parent);
29705 }
29706 else {
29707 bindStaticPropertyAssignment(node);
29708 }
29709 }
29710 }
29711 /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
29712 function bindPrototypeAssignment(node) {
29713 node.left.parent = node;
29714 node.right.parent = node;
29715 var lhs = node.left;
29716 bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false);
29717 }
29718 function bindObjectDefinePrototypeProperty(node) {
29719 var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
29720 bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
29721 }
29722 /**
29723 * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
29724 * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
29725 */
29726 function bindPrototypePropertyAssignment(lhs, parent) {
29727 // Look up the function in the local scope, since prototype assignments should
29728 // follow the function declaration
29729 var classPrototype = lhs.expression;
29730 var constructorFunction = classPrototype.expression;
29731 // Fix up parent pointers since we're going to use these nodes before we bind into them
29732 lhs.parent = parent;
29733 constructorFunction.parent = classPrototype;
29734 classPrototype.parent = lhs;
29735 bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true);
29736 }
29737 function bindObjectDefinePropertyAssignment(node) {
29738 var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
29739 var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
29740 namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
29741 bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
29742 }
29743 function bindSpecialPropertyAssignment(node) {
29744 var lhs = node.left;
29745 // Class declarations in Typescript do not allow property declarations
29746 var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression);
29747 if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
29748 return;
29749 }
29750 // Fix up parent pointers since we're going to use these nodes before we bind into them
29751 node.left.parent = node;
29752 node.right.parent = node;
29753 if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) {
29754 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
29755 // var util = module.exports;
29756 // util.property = function ...
29757 bindExportsPropertyAssignment(node);
29758 }
29759 else {
29760 bindStaticPropertyAssignment(lhs);
29761 }
29762 }
29763 /**
29764 * 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.
29765 * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
29766 */
29767 function bindStaticPropertyAssignment(node) {
29768 node.expression.parent = node;
29769 bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false);
29770 }
29771 function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty) {
29772 if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) {
29773 // make symbols or add declarations for intermediate containers
29774 var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
29775 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
29776 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
29777 if (symbol) {
29778 addDeclarationToSymbol(symbol, id, flags_1);
29779 return symbol;
29780 }
29781 else {
29782 var table = parent ? parent.exports :
29783 file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
29784 return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
29785 }
29786 });
29787 }
29788 return namespaceSymbol;
29789 }
29790 function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
29791 if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
29792 return;
29793 }
29794 // Set up the members collection if it doesn't exist already
29795 var symbolTable = isPrototypeProperty ?
29796 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
29797 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
29798 var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration));
29799 var includes = isMethod ? 8192 /* Method */ : 4 /* Property */;
29800 var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */;
29801 declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
29802 }
29803 function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
29804 var namespaceSymbol = lookupSymbolForPropertyAccess(name);
29805 var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
29806 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
29807 : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
29808 namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
29809 bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
29810 }
29811 /**
29812 * Javascript expando values are:
29813 * - Functions
29814 * - classes
29815 * - namespaces
29816 * - variables initialized with function expressions
29817 * - with class expressions
29818 * - with empty object literals
29819 * - with non-empty object literals if assigned to the prototype property
29820 */
29821 function isExpandoSymbol(symbol) {
29822 if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
29823 return true;
29824 }
29825 var node = symbol.valueDeclaration;
29826 if (node && ts.isCallExpression(node)) {
29827 return !!ts.getAssignedExpandoInitializer(node);
29828 }
29829 var init = !node ? undefined :
29830 ts.isVariableDeclaration(node) ? node.initializer :
29831 ts.isBinaryExpression(node) ? node.right :
29832 ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
29833 undefined;
29834 init = init && ts.getRightMostAssignedExpression(init);
29835 if (init) {
29836 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
29837 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 55 /* BarBarToken */ ? init.right : init, isPrototypeAssignment);
29838 }
29839 return false;
29840 }
29841 function getParentOfBinaryExpression(expr) {
29842 while (ts.isBinaryExpression(expr.parent)) {
29843 expr = expr.parent;
29844 }
29845 return expr.parent;
29846 }
29847 function lookupSymbolForPropertyAccess(node, lookupContainer) {
29848 if (lookupContainer === void 0) { lookupContainer = container; }
29849 if (ts.isIdentifier(node)) {
29850 return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
29851 }
29852 else {
29853 var symbol = lookupSymbolForPropertyAccess(node.expression);
29854 return symbol && symbol.exports && symbol.exports.get(node.name.escapedText);
29855 }
29856 }
29857 function forEachIdentifierInEntityName(e, parent, action) {
29858 if (isExportsOrModuleExportsOrAlias(file, e)) {
29859 return file.symbol;
29860 }
29861 else if (ts.isIdentifier(e)) {
29862 return action(e, lookupSymbolForPropertyAccess(e), parent);
29863 }
29864 else {
29865 var s = forEachIdentifierInEntityName(e.expression, parent, action);
29866 if (!s || !s.exports)
29867 return ts.Debug.fail();
29868 return action(e.name, s.exports.get(e.name.escapedText), s);
29869 }
29870 }
29871 function bindCallExpression(node) {
29872 // We're only inspecting call expressions to detect CommonJS modules, so we can skip
29873 // this check if we've already seen the module indicator
29874 if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
29875 setCommonJsModuleIndicator(node);
29876 }
29877 }
29878 function bindClassLikeDeclaration(node) {
29879 if (node.kind === 240 /* ClassDeclaration */) {
29880 bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */);
29881 }
29882 else {
29883 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
29884 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
29885 // Add name of class expression into the map for semantic classifier
29886 if (node.name) {
29887 classifiableNames.set(node.name.escapedText, true);
29888 }
29889 }
29890 var symbol = node.symbol;
29891 // TypeScript 1.0 spec (April 2014): 8.4
29892 // Every class automatically contains a static property member named 'prototype', the
29893 // type of which is an instantiation of the class type with type Any supplied as a type
29894 // argument for each type parameter. It is an error to explicitly declare a static
29895 // property member with the name 'prototype'.
29896 //
29897 // Note: we check for this here because this class may be merging into a module. The
29898 // module might have an exported variable called 'prototype'. We can't allow that as
29899 // that would clash with the built-in 'prototype' for the class.
29900 var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
29901 var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
29902 if (symbolExport) {
29903 if (node.name) {
29904 node.name.parent = node;
29905 }
29906 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
29907 }
29908 symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
29909 prototypeSymbol.parent = symbol;
29910 }
29911 function bindEnumDeclaration(node) {
29912 return ts.isEnumConst(node)
29913 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */)
29914 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */);
29915 }
29916 function bindVariableDeclarationOrBindingElement(node) {
29917 if (inStrictMode) {
29918 checkStrictModeEvalOrArguments(node, node.name);
29919 }
29920 if (!ts.isBindingPattern(node.name)) {
29921 var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node);
29922 var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */);
29923 var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */);
29924 if (ts.isBlockOrCatchScoped(node)) {
29925 bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes);
29926 }
29927 else if (ts.isParameterDeclaration(node)) {
29928 // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
29929 // because its parent chain has already been set up, since parents are set before descending into children.
29930 //
29931 // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
29932 // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
29933 // For example:
29934 // function foo([a,a]) {} // Duplicate Identifier error
29935 // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
29936 // // which correctly set excluded symbols
29937 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */);
29938 }
29939 else {
29940 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes);
29941 }
29942 }
29943 }
29944 function bindParameter(node) {
29945 if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
29946 return;
29947 }
29948 if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
29949 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
29950 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
29951 checkStrictModeEvalOrArguments(node, node.name);
29952 }
29953 if (ts.isBindingPattern(node.name)) {
29954 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
29955 }
29956 else {
29957 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */);
29958 }
29959 // If this is a property-parameter, then also declare the property symbol into the
29960 // containing class.
29961 if (ts.isParameterPropertyDeclaration(node)) {
29962 var classDeclaration = node.parent.parent;
29963 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
29964 }
29965 }
29966 function bindFunctionDeclaration(node) {
29967 if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) {
29968 if (ts.isAsyncFunction(node)) {
29969 emitFlags |= 1024 /* HasAsyncFunctions */;
29970 }
29971 }
29972 checkStrictModeFunctionName(node);
29973 if (inStrictMode) {
29974 checkStrictModeFunctionDeclaration(node);
29975 bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */);
29976 }
29977 else {
29978 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */);
29979 }
29980 }
29981 function bindFunctionExpression(node) {
29982 if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) {
29983 if (ts.isAsyncFunction(node)) {
29984 emitFlags |= 1024 /* HasAsyncFunctions */;
29985 }
29986 }
29987 if (currentFlow) {
29988 node.flowNode = currentFlow;
29989 }
29990 checkStrictModeFunctionName(node);
29991 var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
29992 return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
29993 }
29994 function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
29995 if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */) && ts.isAsyncFunction(node)) {
29996 emitFlags |= 1024 /* HasAsyncFunctions */;
29997 }
29998 if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
29999 node.flowNode = currentFlow;
30000 }
30001 return ts.hasDynamicName(node)
30002 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
30003 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
30004 }
30005 function getInferTypeContainer(node) {
30006 var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
30007 return extendsType && extendsType.parent;
30008 }
30009 function bindTypeParameter(node) {
30010 if (ts.isJSDocTemplateTag(node.parent)) {
30011 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
30012 if (container_1) {
30013 if (!container_1.locals) {
30014 container_1.locals = ts.createSymbolTable();
30015 }
30016 declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
30017 }
30018 else {
30019 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
30020 }
30021 }
30022 else if (node.parent.kind === 176 /* InferType */) {
30023 var container_2 = getInferTypeContainer(node.parent);
30024 if (container_2) {
30025 if (!container_2.locals) {
30026 container_2.locals = ts.createSymbolTable();
30027 }
30028 declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
30029 }
30030 else {
30031 bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
30032 }
30033 }
30034 else {
30035 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
30036 }
30037 }
30038 // reachability checks
30039 function shouldReportErrorOnModuleDeclaration(node) {
30040 var instanceState = getModuleInstanceState(node);
30041 return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
30042 }
30043 function checkUnreachable(node) {
30044 if (!(currentFlow.flags & 1 /* Unreachable */)) {
30045 return false;
30046 }
30047 if (currentFlow === unreachableFlow) {
30048 var reportError =
30049 // report error on all statements except empty ones
30050 (ts.isStatementButNotDeclaration(node) && node.kind !== 220 /* EmptyStatement */) ||
30051 // report error on class declarations
30052 node.kind === 240 /* ClassDeclaration */ ||
30053 // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
30054 (node.kind === 244 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
30055 if (reportError) {
30056 currentFlow = reportedUnreachableFlow;
30057 if (!options.allowUnreachableCode) {
30058 // unreachable code is reported if
30059 // - user has explicitly asked about it AND
30060 // - statement is in not ambient context (statements in ambient context is already an error
30061 // so we should not report extras) AND
30062 // - node is not variable statement OR
30063 // - node is block scoped variable statement OR
30064 // - node is not block scoped variable statement and at least one variable declaration has initializer
30065 // Rationale: we don't want to report errors on non-initialized var's since they are hoisted
30066 // On the other side we do want to report errors on non-initialized 'lets' because of TDZ
30067 var isError_1 = ts.unreachableCodeIsError(options) &&
30068 !(node.flags & 4194304 /* Ambient */) &&
30069 (!ts.isVariableStatement(node) ||
30070 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
30071 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
30072 eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
30073 }
30074 }
30075 }
30076 return true;
30077 }
30078 }
30079 function eachUnreachableRange(node, cb) {
30080 if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
30081 var statements = node.parent.statements;
30082 var slice_1 = ts.sliceAfter(statements, node);
30083 ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
30084 }
30085 else {
30086 cb(node, node);
30087 }
30088 }
30089 // As opposed to a pure declaration like an `interface`
30090 function isExecutableStatement(s) {
30091 // Don't remove statements that can validly be used before they appear.
30092 return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
30093 // `var x;` may declare a variable used above
30094 !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
30095 }
30096 function isPurelyTypeDeclaration(s) {
30097 switch (s.kind) {
30098 case 241 /* InterfaceDeclaration */:
30099 case 242 /* TypeAliasDeclaration */:
30100 return true;
30101 case 244 /* ModuleDeclaration */:
30102 return getModuleInstanceState(s) !== 1 /* Instantiated */;
30103 case 243 /* EnumDeclaration */:
30104 return ts.hasModifier(s, 2048 /* Const */);
30105 default:
30106 return false;
30107 }
30108 }
30109 function isExportsOrModuleExportsOrAlias(sourceFile, node) {
30110 return ts.isExportsIdentifier(node) ||
30111 ts.isModuleExportsPropertyAccessExpression(node) ||
30112 ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node);
30113 }
30114 ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
30115 function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) {
30116 var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
30117 return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) &&
30118 !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer);
30119 }
30120 function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) {
30121 return isExportsOrModuleExportsOrAlias(sourceFile, node) ||
30122 (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right)));
30123 }
30124 function lookupSymbolForNameWorker(container, name) {
30125 var local = container.locals && container.locals.get(name);
30126 if (local) {
30127 return local.exportSymbol || local;
30128 }
30129 if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
30130 return container.jsGlobalAugmentations.get(name);
30131 }
30132 return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
30133 }
30134 /**
30135 * Computes the transform flags for a node, given the transform flags of its subtree
30136 *
30137 * @param node The node to analyze
30138 * @param subtreeFlags Transform flags computed for this node's subtree
30139 */
30140 function computeTransformFlagsForNode(node, subtreeFlags) {
30141 var kind = node.kind;
30142 switch (kind) {
30143 case 191 /* CallExpression */:
30144 return computeCallExpression(node, subtreeFlags);
30145 case 192 /* NewExpression */:
30146 return computeNewExpression(node, subtreeFlags);
30147 case 244 /* ModuleDeclaration */:
30148 return computeModuleDeclaration(node, subtreeFlags);
30149 case 195 /* ParenthesizedExpression */:
30150 return computeParenthesizedExpression(node, subtreeFlags);
30151 case 204 /* BinaryExpression */:
30152 return computeBinaryExpression(node, subtreeFlags);
30153 case 221 /* ExpressionStatement */:
30154 return computeExpressionStatement(node, subtreeFlags);
30155 case 151 /* Parameter */:
30156 return computeParameter(node, subtreeFlags);
30157 case 197 /* ArrowFunction */:
30158 return computeArrowFunction(node, subtreeFlags);
30159 case 196 /* FunctionExpression */:
30160 return computeFunctionExpression(node, subtreeFlags);
30161 case 239 /* FunctionDeclaration */:
30162 return computeFunctionDeclaration(node, subtreeFlags);
30163 case 237 /* VariableDeclaration */:
30164 return computeVariableDeclaration(node, subtreeFlags);
30165 case 238 /* VariableDeclarationList */:
30166 return computeVariableDeclarationList(node, subtreeFlags);
30167 case 219 /* VariableStatement */:
30168 return computeVariableStatement(node, subtreeFlags);
30169 case 233 /* LabeledStatement */:
30170 return computeLabeledStatement(node, subtreeFlags);
30171 case 240 /* ClassDeclaration */:
30172 return computeClassDeclaration(node, subtreeFlags);
30173 case 209 /* ClassExpression */:
30174 return computeClassExpression(node, subtreeFlags);
30175 case 273 /* HeritageClause */:
30176 return computeHeritageClause(node, subtreeFlags);
30177 case 274 /* CatchClause */:
30178 return computeCatchClause(node, subtreeFlags);
30179 case 211 /* ExpressionWithTypeArguments */:
30180 return computeExpressionWithTypeArguments(node, subtreeFlags);
30181 case 157 /* Constructor */:
30182 return computeConstructor(node, subtreeFlags);
30183 case 154 /* PropertyDeclaration */:
30184 return computePropertyDeclaration(node, subtreeFlags);
30185 case 156 /* MethodDeclaration */:
30186 return computeMethod(node, subtreeFlags);
30187 case 158 /* GetAccessor */:
30188 case 159 /* SetAccessor */:
30189 return computeAccessor(node, subtreeFlags);
30190 case 248 /* ImportEqualsDeclaration */:
30191 return computeImportEquals(node, subtreeFlags);
30192 case 189 /* PropertyAccessExpression */:
30193 return computePropertyAccess(node, subtreeFlags);
30194 case 190 /* ElementAccessExpression */:
30195 return computeElementAccess(node, subtreeFlags);
30196 default:
30197 return computeOther(node, kind, subtreeFlags);
30198 }
30199 }
30200 ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
30201 function computeCallExpression(node, subtreeFlags) {
30202 var transformFlags = subtreeFlags;
30203 var callee = ts.skipOuterExpressions(node.expression);
30204 var expression = node.expression;
30205 if (node.typeArguments) {
30206 transformFlags |= 1 /* AssertTypeScript */;
30207 }
30208 if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
30209 // If the this node contains a SpreadExpression, or is a super call, then it is an ES6
30210 // node.
30211 transformFlags |= 128 /* AssertES2015 */;
30212 if (ts.isSuperProperty(callee)) {
30213 transformFlags |= 2048 /* ContainsLexicalThis */;
30214 }
30215 }
30216 if (expression.kind === 92 /* ImportKeyword */) {
30217 transformFlags |= 524288 /* ContainsDynamicImport */;
30218 }
30219 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30220 return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
30221 }
30222 function computeNewExpression(node, subtreeFlags) {
30223 var transformFlags = subtreeFlags;
30224 if (node.typeArguments) {
30225 transformFlags |= 1 /* AssertTypeScript */;
30226 }
30227 if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
30228 // If the this node contains a SpreadElementExpression then it is an ES6
30229 // node.
30230 transformFlags |= 128 /* AssertES2015 */;
30231 }
30232 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30233 return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
30234 }
30235 function computeBinaryExpression(node, subtreeFlags) {
30236 var transformFlags = subtreeFlags;
30237 var operatorTokenKind = node.operatorToken.kind;
30238 var leftKind = node.left.kind;
30239 if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) {
30240 // Destructuring object assignments with are ES2015 syntax
30241 // and possibly ES2018 if they contain rest
30242 transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
30243 }
30244 else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) {
30245 // Destructuring assignments are ES2015 syntax.
30246 transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
30247 }
30248 else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */
30249 || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) {
30250 // Exponentiation is ES2016 syntax.
30251 transformFlags |= 64 /* AssertES2016 */;
30252 }
30253 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30254 return transformFlags & ~536870912 /* NodeExcludes */;
30255 }
30256 function computeParameter(node, subtreeFlags) {
30257 var transformFlags = subtreeFlags;
30258 var name = node.name;
30259 var initializer = node.initializer;
30260 var dotDotDotToken = node.dotDotDotToken;
30261 // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
30262 // syntax.
30263 if (node.questionToken
30264 || node.type
30265 || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
30266 || ts.isThisIdentifier(name)) {
30267 transformFlags |= 1 /* AssertTypeScript */;
30268 }
30269 // If a parameter has an accessibility modifier, then it is TypeScript syntax.
30270 if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
30271 transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
30272 }
30273 // parameters with object rest destructuring are ES2018 syntax
30274 if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
30275 transformFlags |= 16 /* AssertES2018 */;
30276 }
30277 // If a parameter has an initializer, a binding pattern or a dotDotDot token, then
30278 // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
30279 if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
30280 transformFlags |= 128 /* AssertES2015 */;
30281 }
30282 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30283 return transformFlags & ~536870912 /* ParameterExcludes */;
30284 }
30285 function computeParenthesizedExpression(node, subtreeFlags) {
30286 var transformFlags = subtreeFlags;
30287 var expression = node.expression;
30288 var expressionKind = expression.kind;
30289 // If the node is synthesized, it means the emitter put the parentheses there,
30290 // not the user. If we didn't want them, the emitter would not have put them
30291 // there.
30292 if (expressionKind === 212 /* AsExpression */
30293 || expressionKind === 194 /* TypeAssertionExpression */) {
30294 transformFlags |= 1 /* AssertTypeScript */;
30295 }
30296 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30297 return transformFlags & ~536870912 /* OuterExpressionExcludes */;
30298 }
30299 function computeClassDeclaration(node, subtreeFlags) {
30300 var transformFlags;
30301 if (ts.hasModifier(node, 2 /* Ambient */)) {
30302 // An ambient declaration is TypeScript syntax.
30303 transformFlags = 1 /* AssertTypeScript */;
30304 }
30305 else {
30306 // A ClassDeclaration is ES6 syntax.
30307 transformFlags = subtreeFlags | 128 /* AssertES2015 */;
30308 // A class with a parameter property assignment, property initializer, computed property name, or decorator is
30309 // TypeScript syntax.
30310 // An exported declaration may be TypeScript syntax, but is handled by the visitor
30311 // for a namespace declaration.
30312 if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */)
30313 || node.typeParameters) {
30314 transformFlags |= 1 /* AssertTypeScript */;
30315 }
30316 }
30317 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30318 return transformFlags & ~536888320 /* ClassExcludes */;
30319 }
30320 function computeClassExpression(node, subtreeFlags) {
30321 // A ClassExpression is ES6 syntax.
30322 var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
30323 // A class with a parameter property assignment, property initializer, or decorator is
30324 // TypeScript syntax.
30325 if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */
30326 || node.typeParameters) {
30327 transformFlags |= 1 /* AssertTypeScript */;
30328 }
30329 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30330 return transformFlags & ~536888320 /* ClassExcludes */;
30331 }
30332 function computeHeritageClause(node, subtreeFlags) {
30333 var transformFlags = subtreeFlags;
30334 switch (node.token) {
30335 case 86 /* ExtendsKeyword */:
30336 // An `extends` HeritageClause is ES6 syntax.
30337 transformFlags |= 128 /* AssertES2015 */;
30338 break;
30339 case 109 /* ImplementsKeyword */:
30340 // An `implements` HeritageClause is TypeScript syntax.
30341 transformFlags |= 1 /* AssertTypeScript */;
30342 break;
30343 default:
30344 ts.Debug.fail("Unexpected token for heritage clause");
30345 break;
30346 }
30347 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30348 return transformFlags & ~536870912 /* NodeExcludes */;
30349 }
30350 function computeCatchClause(node, subtreeFlags) {
30351 var transformFlags = subtreeFlags;
30352 if (!node.variableDeclaration) {
30353 transformFlags |= 8 /* AssertES2019 */;
30354 }
30355 else if (ts.isBindingPattern(node.variableDeclaration.name)) {
30356 transformFlags |= 128 /* AssertES2015 */;
30357 }
30358 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30359 return transformFlags & ~536879104 /* CatchClauseExcludes */;
30360 }
30361 function computeExpressionWithTypeArguments(node, subtreeFlags) {
30362 // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
30363 // extends clause of a class.
30364 var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
30365 // If an ExpressionWithTypeArguments contains type arguments, then it
30366 // is TypeScript syntax.
30367 if (node.typeArguments) {
30368 transformFlags |= 1 /* AssertTypeScript */;
30369 }
30370 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30371 return transformFlags & ~536870912 /* NodeExcludes */;
30372 }
30373 function computeConstructor(node, subtreeFlags) {
30374 var transformFlags = subtreeFlags;
30375 // TypeScript-specific modifiers and overloads are TypeScript syntax
30376 if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
30377 || !node.body) {
30378 transformFlags |= 1 /* AssertTypeScript */;
30379 }
30380 // function declarations with object rest destructuring are ES2018 syntax
30381 if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
30382 transformFlags |= 16 /* AssertES2018 */;
30383 }
30384 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30385 return transformFlags & ~537372672 /* ConstructorExcludes */;
30386 }
30387 function computeMethod(node, subtreeFlags) {
30388 // A MethodDeclaration is ES6 syntax.
30389 var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
30390 // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
30391 // overloads are TypeScript syntax.
30392 if (node.decorators
30393 || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
30394 || node.typeParameters
30395 || node.type
30396 || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly
30397 || !node.body) {
30398 transformFlags |= 1 /* AssertTypeScript */;
30399 }
30400 // function declarations with object rest destructuring are ES2018 syntax
30401 if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
30402 transformFlags |= 16 /* AssertES2018 */;
30403 }
30404 // An async method declaration is ES2017 syntax.
30405 if (ts.hasModifier(node, 256 /* Async */)) {
30406 transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
30407 }
30408 if (node.asteriskToken) {
30409 transformFlags |= 256 /* AssertGenerator */;
30410 }
30411 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30412 return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
30413 }
30414 function computeAccessor(node, subtreeFlags) {
30415 var transformFlags = subtreeFlags;
30416 // Decorators, TypeScript-specific modifiers, type annotations, and overloads are
30417 // TypeScript syntax.
30418 if (node.decorators
30419 || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
30420 || node.type
30421 || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly
30422 || !node.body) {
30423 transformFlags |= 1 /* AssertTypeScript */;
30424 }
30425 // function declarations with object rest destructuring are ES2018 syntax
30426 if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
30427 transformFlags |= 16 /* AssertES2018 */;
30428 }
30429 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30430 return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
30431 }
30432 function computePropertyDeclaration(node, subtreeFlags) {
30433 // A PropertyDeclaration is TypeScript syntax.
30434 var transformFlags = subtreeFlags | 1 /* AssertTypeScript */;
30435 // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
30436 // so that it handle the transformation.
30437 if (node.initializer || ts.isComputedPropertyName(node.name)) {
30438 transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */;
30439 }
30440 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30441 return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */);
30442 }
30443 function computeFunctionDeclaration(node, subtreeFlags) {
30444 var transformFlags;
30445 var modifierFlags = ts.getModifierFlags(node);
30446 var body = node.body;
30447 if (!body || (modifierFlags & 2 /* Ambient */)) {
30448 // An ambient declaration is TypeScript syntax.
30449 // A FunctionDeclaration without a body is an overload and is TypeScript syntax.
30450 transformFlags = 1 /* AssertTypeScript */;
30451 }
30452 else {
30453 transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
30454 // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
30455 // syntax.
30456 if (modifierFlags & 2270 /* TypeScriptModifier */
30457 || node.typeParameters
30458 || node.type) {
30459 transformFlags |= 1 /* AssertTypeScript */;
30460 }
30461 // An async function declaration is ES2017 syntax.
30462 if (modifierFlags & 256 /* Async */) {
30463 transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
30464 }
30465 // function declarations with object rest destructuring are ES2018 syntax
30466 if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
30467 transformFlags |= 16 /* AssertES2018 */;
30468 }
30469 // If a FunctionDeclaration is generator function and is the body of a
30470 // transformed async function, then this node can be transformed to a
30471 // down-level generator.
30472 // Currently we do not support transforming any other generator functions
30473 // down level.
30474 if (node.asteriskToken) {
30475 transformFlags |= 256 /* AssertGenerator */;
30476 }
30477 }
30478 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30479 return transformFlags & ~537373696 /* FunctionExcludes */;
30480 }
30481 function computeFunctionExpression(node, subtreeFlags) {
30482 var transformFlags = subtreeFlags;
30483 // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
30484 // syntax.
30485 if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
30486 || node.typeParameters
30487 || node.type) {
30488 transformFlags |= 1 /* AssertTypeScript */;
30489 }
30490 // An async function expression is ES2017 syntax.
30491 if (ts.hasModifier(node, 256 /* Async */)) {
30492 transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
30493 }
30494 // function expressions with object rest destructuring are ES2018 syntax
30495 if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
30496 transformFlags |= 16 /* AssertES2018 */;
30497 }
30498 // If a FunctionExpression is generator function and is the body of a
30499 // transformed async function, then this node can be transformed to a
30500 // down-level generator.
30501 if (node.asteriskToken) {
30502 transformFlags |= 256 /* AssertGenerator */;
30503 }
30504 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30505 return transformFlags & ~537373696 /* FunctionExcludes */;
30506 }
30507 function computeArrowFunction(node, subtreeFlags) {
30508 // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
30509 var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
30510 // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
30511 // syntax.
30512 if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
30513 || node.typeParameters
30514 || node.type) {
30515 transformFlags |= 1 /* AssertTypeScript */;
30516 }
30517 // An async arrow function is ES2017 syntax.
30518 if (ts.hasModifier(node, 256 /* Async */)) {
30519 transformFlags |= 32 /* AssertES2017 */;
30520 }
30521 // arrow functions with object rest destructuring are ES2018 syntax
30522 if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
30523 transformFlags |= 16 /* AssertES2018 */;
30524 }
30525 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30526 return transformFlags & ~537371648 /* ArrowFunctionExcludes */;
30527 }
30528 function computePropertyAccess(node, subtreeFlags) {
30529 var transformFlags = subtreeFlags;
30530 // If a PropertyAccessExpression starts with a super keyword, then it is
30531 // ES6 syntax, and requires a lexical `this` binding.
30532 if (node.expression.kind === 98 /* SuperKeyword */) {
30533 // super inside of an async function requires hoisting the super access (ES2017).
30534 // same for super inside of an async generator, which is ES2018.
30535 transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
30536 }
30537 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30538 return transformFlags & ~536870912 /* PropertyAccessExcludes */;
30539 }
30540 function computeElementAccess(node, subtreeFlags) {
30541 var transformFlags = subtreeFlags;
30542 // If an ElementAccessExpression starts with a super keyword, then it is
30543 // ES6 syntax, and requires a lexical `this` binding.
30544 if (node.expression.kind === 98 /* SuperKeyword */) {
30545 // super inside of an async function requires hoisting the super access (ES2017).
30546 // same for super inside of an async generator, which is ES2018.
30547 transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
30548 }
30549 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30550 return transformFlags & ~536870912 /* PropertyAccessExcludes */;
30551 }
30552 function computeVariableDeclaration(node, subtreeFlags) {
30553 var transformFlags = subtreeFlags;
30554 transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
30555 // A VariableDeclaration containing ObjectRest is ES2018 syntax
30556 if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
30557 transformFlags |= 16 /* AssertES2018 */;
30558 }
30559 // Type annotations are TypeScript syntax.
30560 if (node.type) {
30561 transformFlags |= 1 /* AssertTypeScript */;
30562 }
30563 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30564 return transformFlags & ~536870912 /* NodeExcludes */;
30565 }
30566 function computeVariableStatement(node, subtreeFlags) {
30567 var transformFlags;
30568 var declarationListTransformFlags = node.declarationList.transformFlags;
30569 // An ambient declaration is TypeScript syntax.
30570 if (ts.hasModifier(node, 2 /* Ambient */)) {
30571 transformFlags = 1 /* AssertTypeScript */;
30572 }
30573 else {
30574 transformFlags = subtreeFlags;
30575 if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) {
30576 transformFlags |= 128 /* AssertES2015 */;
30577 }
30578 }
30579 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30580 return transformFlags & ~536870912 /* NodeExcludes */;
30581 }
30582 function computeLabeledStatement(node, subtreeFlags) {
30583 var transformFlags = subtreeFlags;
30584 // A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
30585 if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */
30586 && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
30587 transformFlags |= 128 /* AssertES2015 */;
30588 }
30589 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30590 return transformFlags & ~536870912 /* NodeExcludes */;
30591 }
30592 function computeImportEquals(node, subtreeFlags) {
30593 var transformFlags = subtreeFlags;
30594 // An ImportEqualsDeclaration with a namespace reference is TypeScript.
30595 if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
30596 transformFlags |= 1 /* AssertTypeScript */;
30597 }
30598 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30599 return transformFlags & ~536870912 /* NodeExcludes */;
30600 }
30601 function computeExpressionStatement(node, subtreeFlags) {
30602 var transformFlags = subtreeFlags;
30603 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30604 return transformFlags & ~536870912 /* NodeExcludes */;
30605 }
30606 function computeModuleDeclaration(node, subtreeFlags) {
30607 var transformFlags = 1 /* AssertTypeScript */;
30608 var modifierFlags = ts.getModifierFlags(node);
30609 if ((modifierFlags & 2 /* Ambient */) === 0) {
30610 transformFlags |= subtreeFlags;
30611 }
30612 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30613 return transformFlags & ~537168896 /* ModuleExcludes */;
30614 }
30615 function computeVariableDeclarationList(node, subtreeFlags) {
30616 var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
30617 if (subtreeFlags & 65536 /* ContainsBindingPattern */) {
30618 transformFlags |= 128 /* AssertES2015 */;
30619 }
30620 // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
30621 if (node.flags & 3 /* BlockScoped */) {
30622 transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */;
30623 }
30624 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30625 return transformFlags & ~536944640 /* VariableDeclarationListExcludes */;
30626 }
30627 function computeOther(node, kind, subtreeFlags) {
30628 // Mark transformations needed for each node
30629 var transformFlags = subtreeFlags;
30630 var excludeFlags = 536870912 /* NodeExcludes */;
30631 switch (kind) {
30632 case 121 /* AsyncKeyword */:
30633 case 201 /* AwaitExpression */:
30634 // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators)
30635 transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */;
30636 break;
30637 case 194 /* TypeAssertionExpression */:
30638 case 212 /* AsExpression */:
30639 case 313 /* PartiallyEmittedExpression */:
30640 // These nodes are TypeScript syntax.
30641 transformFlags |= 1 /* AssertTypeScript */;
30642 excludeFlags = 536870912 /* OuterExpressionExcludes */;
30643 break;
30644 case 115 /* PublicKeyword */:
30645 case 113 /* PrivateKeyword */:
30646 case 114 /* ProtectedKeyword */:
30647 case 118 /* AbstractKeyword */:
30648 case 125 /* DeclareKeyword */:
30649 case 77 /* ConstKeyword */:
30650 case 243 /* EnumDeclaration */:
30651 case 278 /* EnumMember */:
30652 case 213 /* NonNullExpression */:
30653 case 133 /* ReadonlyKeyword */:
30654 // These nodes are TypeScript syntax.
30655 transformFlags |= 1 /* AssertTypeScript */;
30656 break;
30657 case 260 /* JsxElement */:
30658 case 261 /* JsxSelfClosingElement */:
30659 case 262 /* JsxOpeningElement */:
30660 case 11 /* JsxText */:
30661 case 263 /* JsxClosingElement */:
30662 case 264 /* JsxFragment */:
30663 case 265 /* JsxOpeningFragment */:
30664 case 266 /* JsxClosingFragment */:
30665 case 267 /* JsxAttribute */:
30666 case 268 /* JsxAttributes */:
30667 case 269 /* JsxSpreadAttribute */:
30668 case 270 /* JsxExpression */:
30669 // These nodes are Jsx syntax.
30670 transformFlags |= 2 /* AssertJsx */;
30671 break;
30672 case 14 /* NoSubstitutionTemplateLiteral */:
30673 case 15 /* TemplateHead */:
30674 case 16 /* TemplateMiddle */:
30675 case 17 /* TemplateTail */:
30676 case 206 /* TemplateExpression */:
30677 case 193 /* TaggedTemplateExpression */:
30678 case 276 /* ShorthandPropertyAssignment */:
30679 case 116 /* StaticKeyword */:
30680 case 214 /* MetaProperty */:
30681 // These nodes are ES6 syntax.
30682 transformFlags |= 128 /* AssertES2015 */;
30683 break;
30684 case 10 /* StringLiteral */:
30685 if (node.hasExtendedUnicodeEscape) {
30686 transformFlags |= 128 /* AssertES2015 */;
30687 }
30688 break;
30689 case 8 /* NumericLiteral */:
30690 if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
30691 transformFlags |= 128 /* AssertES2015 */;
30692 }
30693 break;
30694 case 9 /* BigIntLiteral */:
30695 transformFlags |= 4 /* AssertESNext */;
30696 break;
30697 case 227 /* ForOfStatement */:
30698 // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
30699 if (node.awaitModifier) {
30700 transformFlags |= 16 /* AssertES2018 */;
30701 }
30702 transformFlags |= 128 /* AssertES2015 */;
30703 break;
30704 case 207 /* YieldExpression */:
30705 // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
30706 // generator).
30707 transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */;
30708 break;
30709 case 120 /* AnyKeyword */:
30710 case 135 /* NumberKeyword */:
30711 case 146 /* BigIntKeyword */:
30712 case 132 /* NeverKeyword */:
30713 case 136 /* ObjectKeyword */:
30714 case 138 /* StringKeyword */:
30715 case 123 /* BooleanKeyword */:
30716 case 139 /* SymbolKeyword */:
30717 case 106 /* VoidKeyword */:
30718 case 150 /* TypeParameter */:
30719 case 153 /* PropertySignature */:
30720 case 155 /* MethodSignature */:
30721 case 160 /* CallSignature */:
30722 case 161 /* ConstructSignature */:
30723 case 162 /* IndexSignature */:
30724 case 163 /* TypePredicate */:
30725 case 164 /* TypeReference */:
30726 case 165 /* FunctionType */:
30727 case 166 /* ConstructorType */:
30728 case 167 /* TypeQuery */:
30729 case 168 /* TypeLiteral */:
30730 case 169 /* ArrayType */:
30731 case 170 /* TupleType */:
30732 case 171 /* OptionalType */:
30733 case 172 /* RestType */:
30734 case 173 /* UnionType */:
30735 case 174 /* IntersectionType */:
30736 case 175 /* ConditionalType */:
30737 case 176 /* InferType */:
30738 case 177 /* ParenthesizedType */:
30739 case 241 /* InterfaceDeclaration */:
30740 case 242 /* TypeAliasDeclaration */:
30741 case 178 /* ThisType */:
30742 case 179 /* TypeOperator */:
30743 case 180 /* IndexedAccessType */:
30744 case 181 /* MappedType */:
30745 case 182 /* LiteralType */:
30746 case 247 /* NamespaceExportDeclaration */:
30747 // Types and signatures are TypeScript syntax, and exclude all other facts.
30748 transformFlags = 1 /* AssertTypeScript */;
30749 excludeFlags = -2 /* TypeExcludes */;
30750 break;
30751 case 149 /* ComputedPropertyName */:
30752 // Even though computed property names are ES6, we don't treat them as such.
30753 // This is so that they can flow through PropertyName transforms unaffected.
30754 // Instead, we mark the container as ES6, so that it can properly handle the transform.
30755 transformFlags |= 16384 /* ContainsComputedPropertyName */;
30756 break;
30757 case 208 /* SpreadElement */:
30758 transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */;
30759 break;
30760 case 277 /* SpreadAssignment */:
30761 transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
30762 break;
30763 case 98 /* SuperKeyword */:
30764 // This node is ES6 syntax.
30765 transformFlags |= 128 /* AssertES2015 */;
30766 excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
30767 break;
30768 case 100 /* ThisKeyword */:
30769 // Mark this node and its ancestors as containing a lexical `this` keyword.
30770 transformFlags |= 2048 /* ContainsLexicalThis */;
30771 break;
30772 case 184 /* ObjectBindingPattern */:
30773 transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
30774 if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
30775 transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
30776 }
30777 excludeFlags = 536875008 /* BindingPatternExcludes */;
30778 break;
30779 case 185 /* ArrayBindingPattern */:
30780 transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
30781 excludeFlags = 536875008 /* BindingPatternExcludes */;
30782 break;
30783 case 186 /* BindingElement */:
30784 transformFlags |= 128 /* AssertES2015 */;
30785 if (node.dotDotDotToken) {
30786 transformFlags |= 4096 /* ContainsRestOrSpread */;
30787 }
30788 break;
30789 case 152 /* Decorator */:
30790 // This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
30791 transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
30792 break;
30793 case 188 /* ObjectLiteralExpression */:
30794 excludeFlags = 536896512 /* ObjectLiteralExcludes */;
30795 if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) {
30796 // If an ObjectLiteralExpression contains a ComputedPropertyName, then it
30797 // is an ES6 node.
30798 transformFlags |= 128 /* AssertES2015 */;
30799 }
30800 if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
30801 // If an ObjectLiteralExpression contains a spread element, then it
30802 // is an ES2018 node.
30803 transformFlags |= 16 /* AssertES2018 */;
30804 }
30805 break;
30806 case 187 /* ArrayLiteralExpression */:
30807 excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
30808 break;
30809 case 223 /* DoStatement */:
30810 case 224 /* WhileStatement */:
30811 case 225 /* ForStatement */:
30812 case 226 /* ForInStatement */:
30813 // A loop containing a block scoped binding *may* need to be transformed from ES6.
30814 if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) {
30815 transformFlags |= 128 /* AssertES2015 */;
30816 }
30817 break;
30818 case 284 /* SourceFile */:
30819 break;
30820 case 230 /* ReturnStatement */:
30821 // Return statements may require an `await` in ES2018.
30822 transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */;
30823 break;
30824 case 228 /* ContinueStatement */:
30825 case 229 /* BreakStatement */:
30826 transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */;
30827 break;
30828 }
30829 node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
30830 return transformFlags & ~excludeFlags;
30831 }
30832 function propagatePropertyNameFlags(node, transformFlags) {
30833 return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */);
30834 }
30835 /**
30836 * Gets the transform flags to exclude when unioning the transform flags of a subtree.
30837 *
30838 * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
30839 * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
30840 * than calling this function.
30841 */
30842 function getTransformFlagsSubtreeExclusions(kind) {
30843 if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) {
30844 return -2 /* TypeExcludes */;
30845 }
30846 switch (kind) {
30847 case 191 /* CallExpression */:
30848 case 192 /* NewExpression */:
30849 case 187 /* ArrayLiteralExpression */:
30850 return 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
30851 case 244 /* ModuleDeclaration */:
30852 return 537168896 /* ModuleExcludes */;
30853 case 151 /* Parameter */:
30854 return 536870912 /* ParameterExcludes */;
30855 case 197 /* ArrowFunction */:
30856 return 537371648 /* ArrowFunctionExcludes */;
30857 case 196 /* FunctionExpression */:
30858 case 239 /* FunctionDeclaration */:
30859 return 537373696 /* FunctionExcludes */;
30860 case 238 /* VariableDeclarationList */:
30861 return 536944640 /* VariableDeclarationListExcludes */;
30862 case 240 /* ClassDeclaration */:
30863 case 209 /* ClassExpression */:
30864 return 536888320 /* ClassExcludes */;
30865 case 157 /* Constructor */:
30866 return 537372672 /* ConstructorExcludes */;
30867 case 156 /* MethodDeclaration */:
30868 case 158 /* GetAccessor */:
30869 case 159 /* SetAccessor */:
30870 return 537372672 /* MethodOrAccessorExcludes */;
30871 case 120 /* AnyKeyword */:
30872 case 135 /* NumberKeyword */:
30873 case 146 /* BigIntKeyword */:
30874 case 132 /* NeverKeyword */:
30875 case 138 /* StringKeyword */:
30876 case 136 /* ObjectKeyword */:
30877 case 123 /* BooleanKeyword */:
30878 case 139 /* SymbolKeyword */:
30879 case 106 /* VoidKeyword */:
30880 case 150 /* TypeParameter */:
30881 case 153 /* PropertySignature */:
30882 case 155 /* MethodSignature */:
30883 case 160 /* CallSignature */:
30884 case 161 /* ConstructSignature */:
30885 case 162 /* IndexSignature */:
30886 case 241 /* InterfaceDeclaration */:
30887 case 242 /* TypeAliasDeclaration */:
30888 return -2 /* TypeExcludes */;
30889 case 188 /* ObjectLiteralExpression */:
30890 return 536896512 /* ObjectLiteralExcludes */;
30891 case 274 /* CatchClause */:
30892 return 536879104 /* CatchClauseExcludes */;
30893 case 184 /* ObjectBindingPattern */:
30894 case 185 /* ArrayBindingPattern */:
30895 return 536875008 /* BindingPatternExcludes */;
30896 case 194 /* TypeAssertionExpression */:
30897 case 212 /* AsExpression */:
30898 case 313 /* PartiallyEmittedExpression */:
30899 case 195 /* ParenthesizedExpression */:
30900 case 98 /* SuperKeyword */:
30901 return 536870912 /* OuterExpressionExcludes */;
30902 case 189 /* PropertyAccessExpression */:
30903 case 190 /* ElementAccessExpression */:
30904 return 536870912 /* PropertyAccessExcludes */;
30905 default:
30906 return 536870912 /* NodeExcludes */;
30907 }
30908 }
30909 ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
30910 /**
30911 * "Binds" JSDoc nodes in TypeScript code.
30912 * Since we will never create symbols for JSDoc, we just set parent pointers instead.
30913 */
30914 function setParentPointers(parent, child) {
30915 child.parent = parent;
30916 ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
30917 }
30918})(ts || (ts = {}));
30919/** @internal */
30920var ts;
30921(function (ts) {
30922 function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) {
30923 return getSymbolWalker;
30924 function getSymbolWalker(accept) {
30925 if (accept === void 0) { accept = function () { return true; }; }
30926 var visitedTypes = []; // Sparse array from id to type
30927 var visitedSymbols = []; // Sparse array from id to symbol
30928 return {
30929 walkType: function (type) {
30930 try {
30931 visitType(type);
30932 return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
30933 }
30934 finally {
30935 ts.clear(visitedTypes);
30936 ts.clear(visitedSymbols);
30937 }
30938 },
30939 walkSymbol: function (symbol) {
30940 try {
30941 visitSymbol(symbol);
30942 return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
30943 }
30944 finally {
30945 ts.clear(visitedTypes);
30946 ts.clear(visitedSymbols);
30947 }
30948 },
30949 };
30950 function visitType(type) {
30951 if (!type) {
30952 return;
30953 }
30954 if (visitedTypes[type.id]) {
30955 return;
30956 }
30957 visitedTypes[type.id] = type;
30958 // Reuse visitSymbol to visit the type's symbol,
30959 // but be sure to bail on recuring into the type if accept declines the symbol.
30960 var shouldBail = visitSymbol(type.symbol);
30961 if (shouldBail)
30962 return;
30963 // Visit the type's related types, if any
30964 if (type.flags & 524288 /* Object */) {
30965 var objectType = type;
30966 var objectFlags = objectType.objectFlags;
30967 if (objectFlags & 4 /* Reference */) {
30968 visitTypeReference(type);
30969 }
30970 if (objectFlags & 32 /* Mapped */) {
30971 visitMappedType(type);
30972 }
30973 if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
30974 visitInterfaceType(type);
30975 }
30976 if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
30977 visitObjectType(objectType);
30978 }
30979 }
30980 if (type.flags & 262144 /* TypeParameter */) {
30981 visitTypeParameter(type);
30982 }
30983 if (type.flags & 3145728 /* UnionOrIntersection */) {
30984 visitUnionOrIntersectionType(type);
30985 }
30986 if (type.flags & 4194304 /* Index */) {
30987 visitIndexType(type);
30988 }
30989 if (type.flags & 8388608 /* IndexedAccess */) {
30990 visitIndexedAccessType(type);
30991 }
30992 }
30993 function visitTypeReference(type) {
30994 visitType(type.target);
30995 ts.forEach(type.typeArguments, visitType);
30996 }
30997 function visitTypeParameter(type) {
30998 visitType(getConstraintOfTypeParameter(type));
30999 }
31000 function visitUnionOrIntersectionType(type) {
31001 ts.forEach(type.types, visitType);
31002 }
31003 function visitIndexType(type) {
31004 visitType(type.type);
31005 }
31006 function visitIndexedAccessType(type) {
31007 visitType(type.objectType);
31008 visitType(type.indexType);
31009 visitType(type.constraint);
31010 }
31011 function visitMappedType(type) {
31012 visitType(type.typeParameter);
31013 visitType(type.constraintType);
31014 visitType(type.templateType);
31015 visitType(type.modifiersType);
31016 }
31017 function visitSignature(signature) {
31018 var typePredicate = getTypePredicateOfSignature(signature);
31019 if (typePredicate) {
31020 visitType(typePredicate.type);
31021 }
31022 ts.forEach(signature.typeParameters, visitType);
31023 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
31024 var parameter = _a[_i];
31025 visitSymbol(parameter);
31026 }
31027 visitType(getRestTypeOfSignature(signature));
31028 visitType(getReturnTypeOfSignature(signature));
31029 }
31030 function visitInterfaceType(interfaceT) {
31031 visitObjectType(interfaceT);
31032 ts.forEach(interfaceT.typeParameters, visitType);
31033 ts.forEach(getBaseTypes(interfaceT), visitType);
31034 visitType(interfaceT.thisType);
31035 }
31036 function visitObjectType(type) {
31037 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
31038 visitType(stringIndexType);
31039 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
31040 visitType(numberIndexType);
31041 // The two checks above *should* have already resolved the type (if needed), so this should be cached
31042 var resolved = resolveStructuredTypeMembers(type);
31043 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
31044 var signature = _a[_i];
31045 visitSignature(signature);
31046 }
31047 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
31048 var signature = _c[_b];
31049 visitSignature(signature);
31050 }
31051 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
31052 var p = _e[_d];
31053 visitSymbol(p);
31054 }
31055 }
31056 function visitSymbol(symbol) {
31057 if (!symbol) {
31058 return false;
31059 }
31060 var symbolId = ts.getSymbolId(symbol);
31061 if (visitedSymbols[symbolId]) {
31062 return false;
31063 }
31064 visitedSymbols[symbolId] = symbol;
31065 if (!accept(symbol)) {
31066 return true;
31067 }
31068 var t = getTypeOfSymbol(symbol);
31069 visitType(t); // Should handle members on classes and such
31070 if (symbol.exports) {
31071 symbol.exports.forEach(visitSymbol);
31072 }
31073 ts.forEach(symbol.declarations, function (d) {
31074 // Type queries are too far resolved when we just visit the symbol's type
31075 // (their type resolved directly to the member deeply referenced)
31076 // So to get the intervening symbols, we need to check if there's a type
31077 // query node on any of the symbol's declarations and get symbols there
31078 if (d.type && d.type.kind === 167 /* TypeQuery */) {
31079 var query = d.type;
31080 var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
31081 visitSymbol(entity);
31082 }
31083 });
31084 return false;
31085 }
31086 }
31087 }
31088 ts.createGetSymbolWalker = createGetSymbolWalker;
31089})(ts || (ts = {}));
31090/* @internal */
31091var ts;
31092(function (ts) {
31093 var ambientModuleSymbolRegex = /^".+"$/;
31094 var nextSymbolId = 1;
31095 var nextNodeId = 1;
31096 var nextMergeId = 1;
31097 var nextFlowId = 1;
31098 function getNodeId(node) {
31099 if (!node.id) {
31100 node.id = nextNodeId;
31101 nextNodeId++;
31102 }
31103 return node.id;
31104 }
31105 ts.getNodeId = getNodeId;
31106 function getSymbolId(symbol) {
31107 if (!symbol.id) {
31108 symbol.id = nextSymbolId;
31109 nextSymbolId++;
31110 }
31111 return symbol.id;
31112 }
31113 ts.getSymbolId = getSymbolId;
31114 function isInstantiatedModule(node, preserveConstEnums) {
31115 var moduleState = ts.getModuleInstanceState(node);
31116 return moduleState === 1 /* Instantiated */ ||
31117 (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
31118 }
31119 ts.isInstantiatedModule = isInstantiatedModule;
31120 function createTypeChecker(host, produceDiagnostics) {
31121 var getPackagesSet = ts.memoize(function () {
31122 var set = ts.createMap();
31123 host.getSourceFiles().forEach(function (sf) {
31124 if (!sf.resolvedModules)
31125 return;
31126 ts.forEachEntry(sf.resolvedModules, function (r) {
31127 if (r && r.packageId)
31128 set.set(r.packageId.name, true);
31129 });
31130 });
31131 return set;
31132 });
31133 // Cancellation that controls whether or not we can cancel in the middle of type checking.
31134 // In general cancelling is *not* safe for the type checker. We might be in the middle of
31135 // computing something, and we will leave our internals in an inconsistent state. Callers
31136 // who set the cancellation token should catch if a cancellation exception occurs, and
31137 // should throw away and create a new TypeChecker.
31138 //
31139 // Currently we only support setting the cancellation token when getting diagnostics. This
31140 // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
31141 // they no longer need the information (for example, if the user started editing again).
31142 var cancellationToken;
31143 var requestedExternalEmitHelpers;
31144 var externalHelpersModule;
31145 // tslint:disable variable-name
31146 var Symbol = ts.objectAllocator.getSymbolConstructor();
31147 var Type = ts.objectAllocator.getTypeConstructor();
31148 var Signature = ts.objectAllocator.getSignatureConstructor();
31149 // tslint:enable variable-name
31150 var typeCount = 0;
31151 var symbolCount = 0;
31152 var enumCount = 0;
31153 var instantiationDepth = 0;
31154 var constraintDepth = 0;
31155 var currentNode;
31156 var emptySymbols = ts.createSymbolTable();
31157 var identityMapper = ts.identity;
31158 var compilerOptions = host.getCompilerOptions();
31159 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
31160 var moduleKind = ts.getEmitModuleKind(compilerOptions);
31161 var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
31162 var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
31163 var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
31164 var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
31165 var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
31166 var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
31167 var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
31168 var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
31169 var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
31170 var emitResolver = createResolver();
31171 var nodeBuilder = createNodeBuilder();
31172 var globals = ts.createSymbolTable();
31173 var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
31174 undefinedSymbol.declarations = [];
31175 var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
31176 globalThisSymbol.exports = globals;
31177 globalThisSymbol.valueDeclaration = ts.createNode(72 /* Identifier */);
31178 globalThisSymbol.valueDeclaration.escapedText = "globalThis";
31179 globals.set(globalThisSymbol.escapedName, globalThisSymbol);
31180 var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
31181 var requireSymbol = createSymbol(4 /* Property */, "require");
31182 /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
31183 var apparentArgumentCount;
31184 // for public members that accept a Node or one of its subtypes, we must guard against
31185 // synthetic nodes created during transformations by calling `getParseTreeNode`.
31186 // for most of these, we perform the guard only on `checker` to avoid any possible
31187 // extra cost of calling `getParseTreeNode` when calling these functions from inside the
31188 // checker.
31189 var checker = {
31190 getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
31191 getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
31192 getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
31193 getTypeCount: function () { return typeCount; },
31194 isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
31195 isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
31196 isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
31197 getMergedSymbol: getMergedSymbol,
31198 getDiagnostics: getDiagnostics,
31199 getGlobalDiagnostics: getGlobalDiagnostics,
31200 getTypeOfSymbolAtLocation: function (symbol, location) {
31201 location = ts.getParseTreeNode(location);
31202 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
31203 },
31204 getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
31205 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
31206 if (parameter === undefined)
31207 return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
31208 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
31209 },
31210 getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
31211 getPropertiesOfType: getPropertiesOfType,
31212 getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
31213 getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
31214 getIndexInfoOfType: getIndexInfoOfType,
31215 getSignaturesOfType: getSignaturesOfType,
31216 getIndexTypeOfType: getIndexTypeOfType,
31217 getBaseTypes: getBaseTypes,
31218 getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
31219 getWidenedType: getWidenedType,
31220 getTypeFromTypeNode: function (nodeIn) {
31221 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
31222 return node ? getTypeFromTypeNode(node) : errorType;
31223 },
31224 getParameterType: getTypeAtPosition,
31225 getPromisedTypeOfPromise: getPromisedTypeOfPromise,
31226 getReturnTypeOfSignature: getReturnTypeOfSignature,
31227 getNullableType: getNullableType,
31228 getNonNullableType: getNonNullableType,
31229 typeToTypeNode: nodeBuilder.typeToTypeNode,
31230 indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
31231 signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
31232 symbolToEntityName: nodeBuilder.symbolToEntityName,
31233 symbolToExpression: nodeBuilder.symbolToExpression,
31234 symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
31235 symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
31236 typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
31237 getSymbolsInScope: function (location, meaning) {
31238 location = ts.getParseTreeNode(location);
31239 return location ? getSymbolsInScope(location, meaning) : [];
31240 },
31241 getSymbolAtLocation: function (node) {
31242 node = ts.getParseTreeNode(node);
31243 return node ? getSymbolAtLocation(node) : undefined;
31244 },
31245 getShorthandAssignmentValueSymbol: function (node) {
31246 node = ts.getParseTreeNode(node);
31247 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
31248 },
31249 getExportSpecifierLocalTargetSymbol: function (nodeIn) {
31250 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
31251 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
31252 },
31253 getExportSymbolOfSymbol: function (symbol) {
31254 return getMergedSymbol(symbol.exportSymbol || symbol);
31255 },
31256 getTypeAtLocation: function (node) {
31257 node = ts.getParseTreeNode(node);
31258 return node ? getTypeOfNode(node) : errorType;
31259 },
31260 getPropertySymbolOfDestructuringAssignment: function (locationIn) {
31261 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
31262 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
31263 },
31264 signatureToString: function (signature, enclosingDeclaration, flags, kind) {
31265 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
31266 },
31267 typeToString: function (type, enclosingDeclaration, flags) {
31268 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
31269 },
31270 symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
31271 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
31272 },
31273 typePredicateToString: function (predicate, enclosingDeclaration, flags) {
31274 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
31275 },
31276 writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
31277 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
31278 },
31279 writeType: function (type, enclosingDeclaration, flags, writer) {
31280 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
31281 },
31282 writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
31283 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
31284 },
31285 writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
31286 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
31287 },
31288 getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
31289 getRootSymbols: getRootSymbols,
31290 getContextualType: function (nodeIn) {
31291 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
31292 return node ? getContextualType(node) : undefined;
31293 },
31294 getContextualTypeForObjectLiteralElement: function (nodeIn) {
31295 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
31296 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
31297 },
31298 getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
31299 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
31300 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
31301 },
31302 getContextualTypeForJsxAttribute: function (nodeIn) {
31303 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
31304 return node && getContextualTypeForJsxAttribute(node);
31305 },
31306 isContextSensitive: isContextSensitive,
31307 getFullyQualifiedName: getFullyQualifiedName,
31308 getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
31309 return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
31310 },
31311 getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
31312 return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
31313 },
31314 getExpandedParameters: getExpandedParameters,
31315 hasEffectiveRestParameter: hasEffectiveRestParameter,
31316 getConstantValue: function (nodeIn) {
31317 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
31318 return node ? getConstantValue(node) : undefined;
31319 },
31320 isValidPropertyAccess: function (nodeIn, propertyName) {
31321 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
31322 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
31323 },
31324 isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
31325 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
31326 return !!node && isValidPropertyAccessForCompletions(node, type, property);
31327 },
31328 getSignatureFromDeclaration: function (declarationIn) {
31329 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
31330 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
31331 },
31332 isImplementationOfOverload: function (node) {
31333 var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
31334 return parsed ? isImplementationOfOverload(parsed) : undefined;
31335 },
31336 getImmediateAliasedSymbol: getImmediateAliasedSymbol,
31337 getAliasedSymbol: resolveAlias,
31338 getEmitResolver: getEmitResolver,
31339 getExportsOfModule: getExportsOfModuleAsArray,
31340 getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
31341 getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier),
31342 getAmbientModules: getAmbientModules,
31343 getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
31344 isOptionalParameter: function (nodeIn) {
31345 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
31346 return node ? isOptionalParameter(node) : false;
31347 },
31348 tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
31349 tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
31350 tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
31351 // we deliberately exclude augmentations
31352 // since we are only interested in declarations of the module itself
31353 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
31354 },
31355 getApparentType: getApparentType,
31356 getUnionType: getUnionType,
31357 createAnonymousType: createAnonymousType,
31358 createSignature: createSignature,
31359 createSymbol: createSymbol,
31360 createIndexInfo: createIndexInfo,
31361 getAnyType: function () { return anyType; },
31362 getStringType: function () { return stringType; },
31363 getNumberType: function () { return numberType; },
31364 createPromiseType: createPromiseType,
31365 createArrayType: createArrayType,
31366 getElementTypeOfArrayType: getElementTypeOfArrayType,
31367 getBooleanType: function () { return booleanType; },
31368 getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
31369 getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
31370 getVoidType: function () { return voidType; },
31371 getUndefinedType: function () { return undefinedType; },
31372 getNullType: function () { return nullType; },
31373 getESSymbolType: function () { return esSymbolType; },
31374 getNeverType: function () { return neverType; },
31375 isSymbolAccessible: isSymbolAccessible,
31376 getObjectFlags: ts.getObjectFlags,
31377 isArrayType: isArrayType,
31378 isTupleType: isTupleType,
31379 isArrayLikeType: isArrayLikeType,
31380 isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
31381 getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
31382 getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); },
31383 getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
31384 getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); },
31385 getBaseConstraintOfType: getBaseConstraintOfType,
31386 getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
31387 resolveName: function (name, location, meaning, excludeGlobals) {
31388 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
31389 },
31390 getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
31391 getAccessibleSymbolChain: getAccessibleSymbolChain,
31392 getTypePredicateOfSignature: getTypePredicateOfSignature,
31393 resolveExternalModuleSymbol: resolveExternalModuleSymbol,
31394 tryGetThisTypeAt: function (node, includeGlobalThis) {
31395 node = ts.getParseTreeNode(node);
31396 return node && tryGetThisTypeAt(node, includeGlobalThis);
31397 },
31398 getTypeArgumentConstraint: function (nodeIn) {
31399 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
31400 return node && getTypeArgumentConstraint(node);
31401 },
31402 getSuggestionDiagnostics: function (file, ct) {
31403 if (ts.skipTypeChecking(file, compilerOptions)) {
31404 return ts.emptyArray;
31405 }
31406 var diagnostics;
31407 try {
31408 // Record the cancellation token so it can be checked later on during checkSourceElement.
31409 // Do this in a finally block so we can ensure that it gets reset back to nothing after
31410 // this call is done.
31411 cancellationToken = ct;
31412 // Ensure file is type checked
31413 checkSourceFile(file);
31414 ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
31415 diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.get(file.fileName));
31416 if (!file.isDeclarationFile && (!unusedIsError(0 /* Local */) || !unusedIsError(1 /* Parameter */))) {
31417 addUnusedDiagnostics();
31418 }
31419 return diagnostics || ts.emptyArray;
31420 }
31421 finally {
31422 cancellationToken = undefined;
31423 }
31424 function addUnusedDiagnostics() {
31425 checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
31426 if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) {
31427 (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
31428 }
31429 });
31430 }
31431 },
31432 runWithCancellationToken: function (token, callback) {
31433 try {
31434 cancellationToken = token;
31435 return callback(checker);
31436 }
31437 finally {
31438 cancellationToken = undefined;
31439 }
31440 },
31441 getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
31442 };
31443 function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
31444 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
31445 apparentArgumentCount = argumentCount;
31446 var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
31447 apparentArgumentCount = undefined;
31448 return res;
31449 }
31450 var tupleTypes = ts.createMap();
31451 var unionTypes = ts.createMap();
31452 var intersectionTypes = ts.createMap();
31453 var literalTypes = ts.createMap();
31454 var indexedAccessTypes = ts.createMap();
31455 var conditionalTypes = ts.createMap();
31456 var evolvingArrayTypes = [];
31457 var undefinedProperties = ts.createMap();
31458 var unknownSymbol = createSymbol(4 /* Property */, "unknown");
31459 var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
31460 var anyType = createIntrinsicType(1 /* Any */, "any");
31461 var autoType = createIntrinsicType(1 /* Any */, "any");
31462 var wildcardType = createIntrinsicType(1 /* Any */, "any");
31463 var errorType = createIntrinsicType(1 /* Any */, "error");
31464 var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
31465 var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
31466 var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */);
31467 var nullType = createIntrinsicType(65536 /* Null */, "null");
31468 var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */);
31469 var stringType = createIntrinsicType(4 /* String */, "string");
31470 var numberType = createIntrinsicType(8 /* Number */, "number");
31471 var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
31472 var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
31473 var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
31474 var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
31475 var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
31476 trueType.regularType = regularTrueType;
31477 trueType.freshType = trueType;
31478 regularTrueType.regularType = regularTrueType;
31479 regularTrueType.freshType = trueType;
31480 falseType.regularType = regularFalseType;
31481 falseType.freshType = falseType;
31482 regularFalseType.regularType = regularFalseType;
31483 regularFalseType.freshType = falseType;
31484 var booleanType = createBooleanType([regularFalseType, regularTrueType]);
31485 // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
31486 // (The union is cached, so simply doing the marking here is sufficient)
31487 createBooleanType([regularFalseType, trueType]);
31488 createBooleanType([falseType, regularTrueType]);
31489 createBooleanType([falseType, trueType]);
31490 var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
31491 var voidType = createIntrinsicType(16384 /* Void */, "void");
31492 var neverType = createIntrinsicType(131072 /* Never */, "never");
31493 var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
31494 var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */);
31495 var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
31496 var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
31497 var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
31498 var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
31499 var numberOrBigIntType = getUnionType([numberType, bigintType]);
31500 var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
31501 var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
31502 emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
31503 var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
31504 emptyTypeLiteralSymbol.members = ts.createSymbolTable();
31505 var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
31506 var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
31507 emptyGenericType.instantiations = ts.createMap();
31508 var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
31509 // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
31510 // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
31511 anyFunctionType.objectFlags |= 524288 /* NonInferrableType */;
31512 var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
31513 var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
31514 var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
31515 var markerSuperType = createTypeParameter();
31516 var markerSubType = createTypeParameter();
31517 markerSubType.constraint = markerSuperType;
31518 var markerOtherType = createTypeParameter();
31519 var noTypePredicate = createIdentifierTypePredicate("<<unresolved>>", 0, anyType);
31520 var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
31521 var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
31522 var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
31523 var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
31524 var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
31525 /** Key is "/path/to/a.ts|/path/to/b.ts". */
31526 var amalgamatedDuplicates;
31527 var reverseMappedCache = ts.createMap();
31528 var ambientModulesCache;
31529 /**
31530 * List of every ambient module with a "*" wildcard.
31531 * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
31532 * This is only used if there is no exact match.
31533 */
31534 var patternAmbientModules;
31535 var globalObjectType;
31536 var globalFunctionType;
31537 var globalCallableFunctionType;
31538 var globalNewableFunctionType;
31539 var globalArrayType;
31540 var globalReadonlyArrayType;
31541 var globalStringType;
31542 var globalNumberType;
31543 var globalBooleanType;
31544 var globalRegExpType;
31545 var globalThisType;
31546 var anyArrayType;
31547 var autoArrayType;
31548 var anyReadonlyArrayType;
31549 var deferredGlobalNonNullableTypeAlias;
31550 // The library files are only loaded when the feature is used.
31551 // This allows users to just specify library files they want to used through --lib
31552 // and they will not get an error from not having unrelated library files
31553 var deferredGlobalESSymbolConstructorSymbol;
31554 var deferredGlobalESSymbolType;
31555 var deferredGlobalTypedPropertyDescriptorType;
31556 var deferredGlobalPromiseType;
31557 var deferredGlobalPromiseLikeType;
31558 var deferredGlobalPromiseConstructorSymbol;
31559 var deferredGlobalPromiseConstructorLikeType;
31560 var deferredGlobalIterableType;
31561 var deferredGlobalIteratorType;
31562 var deferredGlobalIterableIteratorType;
31563 var deferredGlobalAsyncIterableType;
31564 var deferredGlobalAsyncIteratorType;
31565 var deferredGlobalAsyncIterableIteratorType;
31566 var deferredGlobalTemplateStringsArrayType;
31567 var deferredGlobalImportMetaType;
31568 var deferredGlobalExtractSymbol;
31569 var deferredGlobalExcludeSymbol;
31570 var deferredGlobalPickSymbol;
31571 var deferredGlobalBigIntType;
31572 var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
31573 var flowLoopStart = 0;
31574 var flowLoopCount = 0;
31575 var sharedFlowCount = 0;
31576 var flowAnalysisDisabled = false;
31577 var emptyStringType = getLiteralType("");
31578 var zeroType = getLiteralType(0);
31579 var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
31580 var resolutionTargets = [];
31581 var resolutionResults = [];
31582 var resolutionPropertyNames = [];
31583 var suggestionCount = 0;
31584 var maximumSuggestionCount = 10;
31585 var mergedSymbols = [];
31586 var symbolLinks = [];
31587 var nodeLinks = [];
31588 var flowLoopCaches = [];
31589 var flowLoopNodes = [];
31590 var flowLoopKeys = [];
31591 var flowLoopTypes = [];
31592 var sharedFlowNodes = [];
31593 var sharedFlowTypes = [];
31594 var potentialThisCollisions = [];
31595 var potentialNewTargetCollisions = [];
31596 var awaitedTypeStack = [];
31597 var diagnostics = ts.createDiagnosticCollection();
31598 // Suggestion diagnostics must have a file. Keyed by source file name.
31599 var suggestionDiagnostics = ts.createMultiMap();
31600 var TypeFacts;
31601 (function (TypeFacts) {
31602 TypeFacts[TypeFacts["None"] = 0] = "None";
31603 TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
31604 TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
31605 TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
31606 TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
31607 TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
31608 TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
31609 TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
31610 TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
31611 TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
31612 TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
31613 TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
31614 TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
31615 TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
31616 TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
31617 TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
31618 TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
31619 TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
31620 TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
31621 TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
31622 TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
31623 TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
31624 TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
31625 TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
31626 TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
31627 TypeFacts[TypeFacts["All"] = 16777215] = "All";
31628 // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
31629 // The presence of a particular fact means that the given test is true for some (and possibly all) values
31630 // of that kind of type.
31631 TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
31632 TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
31633 TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
31634 TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
31635 TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
31636 TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
31637 TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
31638 TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
31639 TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
31640 TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
31641 TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
31642 TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
31643 TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
31644 TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
31645 TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
31646 TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
31647 TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
31648 TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
31649 TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
31650 TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
31651 TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
31652 TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
31653 TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
31654 TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
31655 TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
31656 TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
31657 TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
31658 TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
31659 TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
31660 TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
31661 TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
31662 TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
31663 TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
31664 TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
31665 TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
31666 TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
31667 TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
31668 TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
31669 TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
31670 TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
31671 TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
31672 TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
31673 })(TypeFacts || (TypeFacts = {}));
31674 var typeofEQFacts = ts.createMapFromTemplate({
31675 string: 1 /* TypeofEQString */,
31676 number: 2 /* TypeofEQNumber */,
31677 bigint: 4 /* TypeofEQBigInt */,
31678 boolean: 8 /* TypeofEQBoolean */,
31679 symbol: 16 /* TypeofEQSymbol */,
31680 undefined: 65536 /* EQUndefined */,
31681 object: 32 /* TypeofEQObject */,
31682 function: 64 /* TypeofEQFunction */
31683 });
31684 var typeofNEFacts = ts.createMapFromTemplate({
31685 string: 256 /* TypeofNEString */,
31686 number: 512 /* TypeofNENumber */,
31687 bigint: 1024 /* TypeofNEBigInt */,
31688 boolean: 2048 /* TypeofNEBoolean */,
31689 symbol: 4096 /* TypeofNESymbol */,
31690 undefined: 524288 /* NEUndefined */,
31691 object: 8192 /* TypeofNEObject */,
31692 function: 16384 /* TypeofNEFunction */
31693 });
31694 var typeofTypesByName = ts.createMapFromTemplate({
31695 string: stringType,
31696 number: numberType,
31697 bigint: bigintType,
31698 boolean: booleanType,
31699 symbol: esSymbolType,
31700 undefined: undefinedType
31701 });
31702 var typeofType = createTypeofType();
31703 var _jsxNamespace;
31704 var _jsxFactoryEntity;
31705 var subtypeRelation = ts.createMap();
31706 var assignableRelation = ts.createMap();
31707 var comparableRelation = ts.createMap();
31708 var identityRelation = ts.createMap();
31709 var enumRelation = ts.createMap();
31710 var TypeSystemPropertyName;
31711 (function (TypeSystemPropertyName) {
31712 TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
31713 TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
31714 TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
31715 TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
31716 TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
31717 TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
31718 TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference";
31719 })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
31720 var CheckMode;
31721 (function (CheckMode) {
31722 CheckMode[CheckMode["Normal"] = 0] = "Normal";
31723 CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
31724 CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
31725 CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
31726 CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
31727 CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
31728 })(CheckMode || (CheckMode = {}));
31729 var CallbackCheck;
31730 (function (CallbackCheck) {
31731 CallbackCheck[CallbackCheck["None"] = 0] = "None";
31732 CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant";
31733 CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict";
31734 })(CallbackCheck || (CallbackCheck = {}));
31735 var MappedTypeModifiers;
31736 (function (MappedTypeModifiers) {
31737 MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
31738 MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
31739 MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
31740 MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
31741 })(MappedTypeModifiers || (MappedTypeModifiers = {}));
31742 var ExpandingFlags;
31743 (function (ExpandingFlags) {
31744 ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
31745 ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
31746 ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
31747 ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
31748 })(ExpandingFlags || (ExpandingFlags = {}));
31749 var MembersOrExportsResolutionKind;
31750 (function (MembersOrExportsResolutionKind) {
31751 MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
31752 MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
31753 })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
31754 var UnusedKind;
31755 (function (UnusedKind) {
31756 UnusedKind[UnusedKind["Local"] = 0] = "Local";
31757 UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
31758 })(UnusedKind || (UnusedKind = {}));
31759 var builtinGlobals = ts.createSymbolTable();
31760 builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
31761 var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
31762 initializeTypeChecker();
31763 return checker;
31764 function getJsxNamespace(location) {
31765 if (location) {
31766 var file = ts.getSourceFileOfNode(location);
31767 if (file) {
31768 if (file.localJsxNamespace) {
31769 return file.localJsxNamespace;
31770 }
31771 var jsxPragma = file.pragmas.get("jsx");
31772 if (jsxPragma) {
31773 var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217
31774 file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
31775 if (file.localJsxFactory) {
31776 return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
31777 }
31778 }
31779 }
31780 }
31781 if (!_jsxNamespace) {
31782 _jsxNamespace = "React";
31783 if (compilerOptions.jsxFactory) {
31784 _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
31785 if (_jsxFactoryEntity) {
31786 _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText;
31787 }
31788 }
31789 else if (compilerOptions.reactNamespace) {
31790 _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
31791 }
31792 }
31793 return _jsxNamespace;
31794 }
31795 function getEmitResolver(sourceFile, cancellationToken) {
31796 // Ensure we have all the type information in place for this file so that all the
31797 // emitter questions of this resolver will return the right information.
31798 getDiagnostics(sourceFile, cancellationToken);
31799 return emitResolver;
31800 }
31801 function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
31802 var diagnostic = location
31803 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
31804 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
31805 var existing = diagnostics.lookup(diagnostic);
31806 if (existing) {
31807 return existing;
31808 }
31809 else {
31810 diagnostics.add(diagnostic);
31811 return diagnostic;
31812 }
31813 }
31814 function error(location, message, arg0, arg1, arg2, arg3) {
31815 var diagnostic = location
31816 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
31817 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
31818 diagnostics.add(diagnostic);
31819 return diagnostic;
31820 }
31821 function addErrorOrSuggestion(isError, diagnostic) {
31822 if (isError) {
31823 diagnostics.add(diagnostic);
31824 }
31825 else {
31826 suggestionDiagnostics.add(diagnostic.file.fileName, __assign({}, diagnostic, { category: ts.DiagnosticCategory.Suggestion }));
31827 }
31828 }
31829 function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
31830 addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message));
31831 }
31832 function createSymbol(flags, name, checkFlags) {
31833 symbolCount++;
31834 var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
31835 symbol.checkFlags = checkFlags || 0;
31836 return symbol;
31837 }
31838 function isTransientSymbol(symbol) {
31839 return (symbol.flags & 33554432 /* Transient */) !== 0;
31840 }
31841 function getExcludedSymbolFlags(flags) {
31842 var result = 0;
31843 if (flags & 2 /* BlockScopedVariable */)
31844 result |= 67220415 /* BlockScopedVariableExcludes */;
31845 if (flags & 1 /* FunctionScopedVariable */)
31846 result |= 67220414 /* FunctionScopedVariableExcludes */;
31847 if (flags & 4 /* Property */)
31848 result |= 0 /* PropertyExcludes */;
31849 if (flags & 8 /* EnumMember */)
31850 result |= 68008959 /* EnumMemberExcludes */;
31851 if (flags & 16 /* Function */)
31852 result |= 67219887 /* FunctionExcludes */;
31853 if (flags & 32 /* Class */)
31854 result |= 68008383 /* ClassExcludes */;
31855 if (flags & 64 /* Interface */)
31856 result |= 67897736 /* InterfaceExcludes */;
31857 if (flags & 256 /* RegularEnum */)
31858 result |= 68008191 /* RegularEnumExcludes */;
31859 if (flags & 128 /* ConstEnum */)
31860 result |= 68008831 /* ConstEnumExcludes */;
31861 if (flags & 512 /* ValueModule */)
31862 result |= 110735 /* ValueModuleExcludes */;
31863 if (flags & 8192 /* Method */)
31864 result |= 67212223 /* MethodExcludes */;
31865 if (flags & 32768 /* GetAccessor */)
31866 result |= 67154879 /* GetAccessorExcludes */;
31867 if (flags & 65536 /* SetAccessor */)
31868 result |= 67187647 /* SetAccessorExcludes */;
31869 if (flags & 262144 /* TypeParameter */)
31870 result |= 67635688 /* TypeParameterExcludes */;
31871 if (flags & 524288 /* TypeAlias */)
31872 result |= 67897832 /* TypeAliasExcludes */;
31873 if (flags & 2097152 /* Alias */)
31874 result |= 2097152 /* AliasExcludes */;
31875 return result;
31876 }
31877 function recordMergedSymbol(target, source) {
31878 if (!source.mergeId) {
31879 source.mergeId = nextMergeId;
31880 nextMergeId++;
31881 }
31882 mergedSymbols[source.mergeId] = target;
31883 }
31884 function cloneSymbol(symbol) {
31885 var result = createSymbol(symbol.flags, symbol.escapedName);
31886 result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
31887 result.parent = symbol.parent;
31888 if (symbol.valueDeclaration)
31889 result.valueDeclaration = symbol.valueDeclaration;
31890 if (symbol.constEnumOnlyModule)
31891 result.constEnumOnlyModule = true;
31892 if (symbol.members)
31893 result.members = ts.cloneMap(symbol.members);
31894 if (symbol.exports)
31895 result.exports = ts.cloneMap(symbol.exports);
31896 recordMergedSymbol(result, symbol);
31897 return result;
31898 }
31899 /**
31900 * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
31901 * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
31902 */
31903 function mergeSymbol(target, source) {
31904 if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
31905 (source.flags | target.flags) & 67108864 /* Assignment */) {
31906 ts.Debug.assert(source !== target);
31907 if (!(target.flags & 33554432 /* Transient */)) {
31908 var resolvedTarget = resolveSymbol(target);
31909 if (resolvedTarget === unknownSymbol) {
31910 return source;
31911 }
31912 target = cloneSymbol(resolvedTarget);
31913 }
31914 // Javascript static-property-assignment declarations always merge, even though they are also values
31915 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
31916 // reset flag when merging instantiated module into value module that has only const enums
31917 target.constEnumOnlyModule = false;
31918 }
31919 target.flags |= source.flags;
31920 if (source.valueDeclaration &&
31921 (!target.valueDeclaration ||
31922 ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) ||
31923 ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) {
31924 // other kinds of value declarations take precedence over modules and assignment declarations
31925 target.valueDeclaration = source.valueDeclaration;
31926 }
31927 ts.addRange(target.declarations, source.declarations);
31928 if (source.members) {
31929 if (!target.members)
31930 target.members = ts.createSymbolTable();
31931 mergeSymbolTable(target.members, source.members);
31932 }
31933 if (source.exports) {
31934 if (!target.exports)
31935 target.exports = ts.createSymbolTable();
31936 mergeSymbolTable(target.exports, source.exports);
31937 }
31938 recordMergedSymbol(target, source);
31939 }
31940 else if (target.flags & 1024 /* NamespaceModule */) {
31941 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));
31942 }
31943 else { // error
31944 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
31945 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
31946 var message = isEitherEnum
31947 ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
31948 : isEitherBlockScoped_1
31949 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
31950 : ts.Diagnostics.Duplicate_identifier_0;
31951 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
31952 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
31953 var symbolName_1 = symbolToString(source);
31954 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
31955 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
31956 var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
31957 var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
31958 var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
31959 return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() });
31960 });
31961 var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
31962 return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
31963 });
31964 addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
31965 addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
31966 }
31967 else {
31968 addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
31969 addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
31970 }
31971 }
31972 return target;
31973 function addDuplicateLocations(locs, symbol) {
31974 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
31975 var decl = _a[_i];
31976 ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl);
31977 }
31978 }
31979 }
31980 function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
31981 ts.forEach(target.declarations, function (node) {
31982 var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
31983 addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations);
31984 });
31985 }
31986 function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) {
31987 var err = lookupOrIssueError(errorNode, message, symbolName);
31988 for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
31989 var relatedNode = _a[_i];
31990 err.relatedInformation = err.relatedInformation || [];
31991 if (ts.length(err.relatedInformation) >= 5)
31992 continue;
31993 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
31994 }
31995 }
31996 function combineSymbolTables(first, second) {
31997 if (!ts.hasEntries(first))
31998 return second;
31999 if (!ts.hasEntries(second))
32000 return first;
32001 var combined = ts.createSymbolTable();
32002 mergeSymbolTable(combined, first);
32003 mergeSymbolTable(combined, second);
32004 return combined;
32005 }
32006 function mergeSymbolTable(target, source) {
32007 source.forEach(function (sourceSymbol, id) {
32008 var targetSymbol = target.get(id);
32009 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol);
32010 });
32011 }
32012 function mergeModuleAugmentation(moduleName) {
32013 var moduleAugmentation = moduleName.parent;
32014 if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
32015 // this is a combined symbol for multiple augmentations within the same file.
32016 // its symbol already has accumulated information for all declarations
32017 // so we need to add it just once - do the work only for first declaration
32018 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
32019 return;
32020 }
32021 if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
32022 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
32023 }
32024 else {
32025 // find a module that about to be augmented
32026 // do not validate names of augmentations that are defined in ambient context
32027 var moduleNotFoundError = !(moduleName.parent.parent.flags & 4194304 /* Ambient */)
32028 ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
32029 : undefined;
32030 var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
32031 if (!mainModule) {
32032 return;
32033 }
32034 // obtain item referenced by 'export='
32035 mainModule = resolveExternalModuleSymbol(mainModule);
32036 if (mainModule.flags & 1920 /* Namespace */) {
32037 mainModule = mergeSymbol(mainModule, moduleAugmentation.symbol);
32038 }
32039 else {
32040 // moduleName will be a StringLiteral since this is not `declare global`.
32041 error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
32042 }
32043 }
32044 }
32045 function addToSymbolTable(target, source, message) {
32046 source.forEach(function (sourceSymbol, id) {
32047 var targetSymbol = target.get(id);
32048 if (targetSymbol) {
32049 // Error on redeclarations
32050 ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
32051 }
32052 else {
32053 target.set(id, sourceSymbol);
32054 }
32055 });
32056 function addDeclarationDiagnostic(id, message) {
32057 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
32058 }
32059 }
32060 function getSymbolLinks(symbol) {
32061 if (symbol.flags & 33554432 /* Transient */)
32062 return symbol;
32063 var id = getSymbolId(symbol);
32064 return symbolLinks[id] || (symbolLinks[id] = {});
32065 }
32066 function getNodeLinks(node) {
32067 var nodeId = getNodeId(node);
32068 return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
32069 }
32070 function isGlobalSourceFile(node) {
32071 return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
32072 }
32073 function getSymbol(symbols, name, meaning) {
32074 if (meaning) {
32075 var symbol = symbols.get(name);
32076 if (symbol) {
32077 ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
32078 if (symbol.flags & meaning) {
32079 return symbol;
32080 }
32081 if (symbol.flags & 2097152 /* Alias */) {
32082 var target = resolveAlias(symbol);
32083 // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
32084 if (target === unknownSymbol || target.flags & meaning) {
32085 return symbol;
32086 }
32087 }
32088 }
32089 }
32090 // return undefined if we can't find a symbol.
32091 }
32092 /**
32093 * Get symbols that represent parameter-property-declaration as parameter and as property declaration
32094 * @param parameter a parameterDeclaration node
32095 * @param parameterName a name of the parameter to get the symbols for.
32096 * @return a tuple of two symbols
32097 */
32098 function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
32099 var constructorDeclaration = parameter.parent;
32100 var classDeclaration = parameter.parent.parent;
32101 var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */);
32102 var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */);
32103 if (parameterSymbol && propertySymbol) {
32104 return [parameterSymbol, propertySymbol];
32105 }
32106 return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
32107 }
32108 function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
32109 var declarationFile = ts.getSourceFileOfNode(declaration);
32110 var useFile = ts.getSourceFileOfNode(usage);
32111 if (declarationFile !== useFile) {
32112 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
32113 (!compilerOptions.outFile && !compilerOptions.out) ||
32114 isInTypeQuery(usage) ||
32115 declaration.flags & 4194304 /* Ambient */) {
32116 // nodes are in different files and order cannot be determined
32117 return true;
32118 }
32119 // declaration is after usage
32120 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
32121 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
32122 return true;
32123 }
32124 var sourceFiles = host.getSourceFiles();
32125 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
32126 }
32127 if (declaration.pos <= usage.pos) {
32128 // declaration is before usage
32129 if (declaration.kind === 186 /* BindingElement */) {
32130 // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
32131 var errorBindingElement = ts.getAncestor(usage, 186 /* BindingElement */);
32132 if (errorBindingElement) {
32133 return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
32134 declaration.pos < errorBindingElement.pos;
32135 }
32136 // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
32137 return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 237 /* VariableDeclaration */), usage);
32138 }
32139 else if (declaration.kind === 237 /* VariableDeclaration */) {
32140 // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
32141 return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
32142 }
32143 else if (ts.isClassDeclaration(declaration)) {
32144 // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
32145 return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
32146 }
32147 return true;
32148 }
32149 // declaration is after usage, but it can still be legal if usage is deferred:
32150 // 1. inside an export specifier
32151 // 2. inside a function
32152 // 3. inside an instance property initializer, a reference to a non-instance property
32153 // 4. inside a static property initializer, a reference to a static method in the same class
32154 // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
32155 // or if usage is in a type context:
32156 // 1. inside a type query (typeof in type position)
32157 // 2. inside a jsdoc comment
32158 if (usage.parent.kind === 257 /* ExportSpecifier */ || (usage.parent.kind === 254 /* ExportAssignment */ && usage.parent.isExportEquals)) {
32159 // export specifiers do not use the variable, they only make it available for use
32160 return true;
32161 }
32162 // When resolving symbols for exports, the `usage` location passed in can be the export site directly
32163 if (usage.kind === 254 /* ExportAssignment */ && usage.isExportEquals) {
32164 return true;
32165 }
32166 var container = ts.getEnclosingBlockScopeContainer(declaration);
32167 return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container);
32168 function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
32169 var container = ts.getEnclosingBlockScopeContainer(declaration);
32170 switch (declaration.parent.parent.kind) {
32171 case 219 /* VariableStatement */:
32172 case 225 /* ForStatement */:
32173 case 227 /* ForOfStatement */:
32174 // variable statement/for/for-of statement case,
32175 // use site should not be inside variable declaration (initializer of declaration or binding element)
32176 if (isSameScopeDescendentOf(usage, declaration, container)) {
32177 return true;
32178 }
32179 break;
32180 }
32181 // ForIn/ForOf case - use site should not be used in expression part
32182 var grandparent = declaration.parent.parent;
32183 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container);
32184 }
32185 function isUsedInFunctionOrInstanceProperty(usage, declaration, container) {
32186 return !!ts.findAncestor(usage, function (current) {
32187 if (current === container) {
32188 return "quit";
32189 }
32190 if (ts.isFunctionLike(current)) {
32191 return true;
32192 }
32193 var initializerOfProperty = current.parent &&
32194 current.parent.kind === 154 /* PropertyDeclaration */ &&
32195 current.parent.initializer === current;
32196 if (initializerOfProperty) {
32197 if (ts.hasModifier(current.parent, 32 /* Static */)) {
32198 if (declaration.kind === 156 /* MethodDeclaration */) {
32199 return true;
32200 }
32201 }
32202 else {
32203 var isDeclarationInstanceProperty = declaration.kind === 154 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */);
32204 if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
32205 return true;
32206 }
32207 }
32208 }
32209 return false;
32210 });
32211 }
32212 }
32213 /**
32214 * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
32215 * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
32216 * the given name can be found.
32217 *
32218 * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
32219 */
32220 function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
32221 if (excludeGlobals === void 0) { excludeGlobals = false; }
32222 return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
32223 }
32224 function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
32225 var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
32226 var result;
32227 var lastLocation;
32228 var lastSelfReferenceLocation;
32229 var propertyWithInvalidInitializer;
32230 var errorLocation = location;
32231 var grandparent;
32232 var isInExternalModule = false;
32233 loop: while (location) {
32234 // Locals of a source file are not in scope (because they get merged into the global symbol table)
32235 if (location.locals && !isGlobalSourceFile(location)) {
32236 if (result = lookup(location.locals, name, meaning)) {
32237 var useResult = true;
32238 if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
32239 // symbol lookup restrictions for function-like declarations
32240 // - Type parameters of a function are in scope in the entire function declaration, including the parameter
32241 // list and return type. However, local types are only in scope in the function body.
32242 // - parameters are only in the scope of function body
32243 // This restriction does not apply to JSDoc comment types because they are parented
32244 // at a higher level than type parameters would normally be
32245 if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
32246 useResult = result.flags & 262144 /* TypeParameter */
32247 // type parameters are visible in parameter list, return type and type parameter list
32248 ? lastLocation === location.type ||
32249 lastLocation.kind === 151 /* Parameter */ ||
32250 lastLocation.kind === 150 /* TypeParameter */
32251 // local types not visible outside the function body
32252 : false;
32253 }
32254 if (meaning & result.flags & 3 /* Variable */) {
32255 // expression inside parameter will lookup as normal variable scope when targeting es2015+
32256 var functionLocation = location;
32257 if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) &&
32258 functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
32259 useResult = false;
32260 }
32261 else if (result.flags & 1 /* FunctionScopedVariable */) {
32262 // parameters are visible only inside function body, parameter list and return type
32263 // technically for parameter list case here we might mix parameters and variables declared in function,
32264 // however it is detected separately when checking initializers of parameters
32265 // to make sure that they reference no variables declared after them.
32266 useResult =
32267 lastLocation.kind === 151 /* Parameter */ ||
32268 (lastLocation === location.type &&
32269 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
32270 }
32271 }
32272 }
32273 else if (location.kind === 175 /* ConditionalType */) {
32274 // A type parameter declared using 'infer T' in a conditional type is visible only in
32275 // the true branch of the conditional type.
32276 useResult = lastLocation === location.trueType;
32277 }
32278 if (useResult) {
32279 break loop;
32280 }
32281 else {
32282 result = undefined;
32283 }
32284 }
32285 }
32286 switch (location.kind) {
32287 case 284 /* SourceFile */:
32288 if (!ts.isExternalOrCommonJsModule(location))
32289 break;
32290 isInExternalModule = true;
32291 // falls through
32292 case 244 /* ModuleDeclaration */:
32293 var moduleExports = getSymbolOfNode(location).exports;
32294 if (location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location)) {
32295 // It's an external module. First see if the module has an export default and if the local
32296 // name of that export default matches.
32297 if (result = moduleExports.get("default" /* Default */)) {
32298 var localSymbol = ts.getLocalSymbolForExportDefault(result);
32299 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
32300 break loop;
32301 }
32302 result = undefined;
32303 }
32304 // Because of module/namespace merging, a module's exports are in scope,
32305 // yet we never want to treat an export specifier as putting a member in scope.
32306 // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
32307 // Two things to note about this:
32308 // 1. We have to check this without calling getSymbol. The problem with calling getSymbol
32309 // on an export specifier is that it might find the export specifier itself, and try to
32310 // resolve it as an alias. This will cause the checker to consider the export specifier
32311 // a circular alias reference when it might not be.
32312 // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
32313 // an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
32314 // which is not the desired behavior.
32315 var moduleExport = moduleExports.get(name);
32316 if (moduleExport &&
32317 moduleExport.flags === 2097152 /* Alias */ &&
32318 ts.getDeclarationOfKind(moduleExport, 257 /* ExportSpecifier */)) {
32319 break;
32320 }
32321 }
32322 // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
32323 if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
32324 if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
32325 result = undefined;
32326 }
32327 else {
32328 break loop;
32329 }
32330 }
32331 break;
32332 case 243 /* EnumDeclaration */:
32333 if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
32334 break loop;
32335 }
32336 break;
32337 case 154 /* PropertyDeclaration */:
32338 case 153 /* PropertySignature */:
32339 // TypeScript 1.0 spec (April 2014): 8.4.1
32340 // Initializer expressions for instance member variables are evaluated in the scope
32341 // of the class constructor body but are not permitted to reference parameters or
32342 // local variables of the constructor. This effectively means that entities from outer scopes
32343 // by the same name as a constructor parameter or local variable are inaccessible
32344 // in initializer expressions for instance member variables.
32345 if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) {
32346 var ctor = findConstructorDeclaration(location.parent);
32347 if (ctor && ctor.locals) {
32348 if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) {
32349 // Remember the property node, it will be used later to report appropriate error
32350 propertyWithInvalidInitializer = location;
32351 }
32352 }
32353 }
32354 break;
32355 case 240 /* ClassDeclaration */:
32356 case 209 /* ClassExpression */:
32357 case 241 /* InterfaceDeclaration */:
32358 // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
32359 // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
32360 // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
32361 if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) {
32362 if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
32363 // ignore type parameters not declared in this container
32364 result = undefined;
32365 break;
32366 }
32367 if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) {
32368 // TypeScript 1.0 spec (April 2014): 3.4.1
32369 // The scope of a type parameter extends over the entire declaration with which the type
32370 // parameter list is associated, with the exception of static member declarations in classes.
32371 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
32372 return undefined;
32373 }
32374 break loop;
32375 }
32376 if (location.kind === 209 /* ClassExpression */ && meaning & 32 /* Class */) {
32377 var className = location.name;
32378 if (className && name === className.escapedText) {
32379 result = location.symbol;
32380 break loop;
32381 }
32382 }
32383 break;
32384 case 211 /* ExpressionWithTypeArguments */:
32385 // The type parameters of a class are not in scope in the base class expression.
32386 if (lastLocation === location.expression && location.parent.token === 86 /* ExtendsKeyword */) {
32387 var container = location.parent.parent;
32388 if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) {
32389 if (nameNotFoundMessage) {
32390 error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
32391 }
32392 return undefined;
32393 }
32394 }
32395 break;
32396 // It is not legal to reference a class's own type parameters from a computed property name that
32397 // belongs to the class. For example:
32398 //
32399 // function foo<T>() { return '' }
32400 // class C<T> { // <-- Class's own type parameter T
32401 // [foo<T>()]() { } // <-- Reference to T from class's own computed property
32402 // }
32403 //
32404 case 149 /* ComputedPropertyName */:
32405 grandparent = location.parent.parent;
32406 if (ts.isClassLike(grandparent) || grandparent.kind === 241 /* InterfaceDeclaration */) {
32407 // A reference to this grandparent's type parameters would be an error
32408 if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) {
32409 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
32410 return undefined;
32411 }
32412 }
32413 break;
32414 case 197 /* ArrowFunction */:
32415 // when targeting ES6 or higher there is no 'arguments' in an arrow function
32416 // for lower compile targets the resolved symbol is used to emit an error
32417 if (compilerOptions.target >= 2 /* ES2015 */) {
32418 break;
32419 }
32420 // falls through
32421 case 156 /* MethodDeclaration */:
32422 case 157 /* Constructor */:
32423 case 158 /* GetAccessor */:
32424 case 159 /* SetAccessor */:
32425 case 239 /* FunctionDeclaration */:
32426 if (meaning & 3 /* Variable */ && name === "arguments") {
32427 result = argumentsSymbol;
32428 break loop;
32429 }
32430 break;
32431 case 196 /* FunctionExpression */:
32432 if (meaning & 3 /* Variable */ && name === "arguments") {
32433 result = argumentsSymbol;
32434 break loop;
32435 }
32436 if (meaning & 16 /* Function */) {
32437 var functionName = location.name;
32438 if (functionName && name === functionName.escapedText) {
32439 result = location.symbol;
32440 break loop;
32441 }
32442 }
32443 break;
32444 case 152 /* Decorator */:
32445 // Decorators are resolved at the class declaration. Resolving at the parameter
32446 // or member would result in looking up locals in the method.
32447 //
32448 // function y() {}
32449 // class C {
32450 // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
32451 // }
32452 //
32453 if (location.parent && location.parent.kind === 151 /* Parameter */) {
32454 location = location.parent;
32455 }
32456 //
32457 // function y() {}
32458 // class C {
32459 // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
32460 // }
32461 //
32462 // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
32463 //
32464 // type T = number;
32465 // declare function y(x: T): any;
32466 // @param(1 as T) // <-- T should resolve to the type alias outside of class C
32467 // class C<T> {}
32468 if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) {
32469 location = location.parent;
32470 }
32471 break;
32472 case 309 /* JSDocTypedefTag */:
32473 case 302 /* JSDocCallbackTag */:
32474 // js type aliases do not resolve names from their host, so skip past it
32475 location = ts.getJSDocHost(location);
32476 break;
32477 }
32478 if (isSelfReferenceLocation(location)) {
32479 lastSelfReferenceLocation = location;
32480 }
32481 lastLocation = location;
32482 location = location.parent;
32483 }
32484 // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
32485 // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
32486 // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
32487 if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
32488 result.isReferenced |= meaning;
32489 }
32490 if (!result) {
32491 if (lastLocation) {
32492 ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
32493 if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
32494 return lastLocation.symbol;
32495 }
32496 }
32497 if (!excludeGlobals) {
32498 result = lookup(globals, name, meaning);
32499 }
32500 }
32501 if (!result) {
32502 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
32503 if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
32504 return requireSymbol;
32505 }
32506 }
32507 }
32508 if (!result) {
32509 if (nameNotFoundMessage) {
32510 if (!errorLocation ||
32511 !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
32512 !checkAndReportErrorForExtendingInterface(errorLocation) &&
32513 !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
32514 !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
32515 !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
32516 !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
32517 var suggestion = void 0;
32518 if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
32519 suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
32520 if (suggestion) {
32521 var suggestionName = symbolToString(suggestion);
32522 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
32523 if (suggestion.valueDeclaration) {
32524 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
32525 }
32526 }
32527 }
32528 if (!suggestion) {
32529 error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
32530 }
32531 suggestionCount++;
32532 }
32533 }
32534 return undefined;
32535 }
32536 // Perform extra checks only if error reporting was requested
32537 if (nameNotFoundMessage) {
32538 if (propertyWithInvalidInitializer) {
32539 // We have a match, but the reference occurred within a property initializer and the identifier also binds
32540 // to a local variable in the constructor where the code will be emitted.
32541 var propertyName = propertyWithInvalidInitializer.name;
32542 error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
32543 return undefined;
32544 }
32545 // Only check for block-scoped variable if we have an error location and are looking for the
32546 // name with variable meaning
32547 // For example,
32548 // declare module foo {
32549 // interface bar {}
32550 // }
32551 // const foo/*1*/: foo/*2*/.bar;
32552 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
32553 // block-scoped variable and namespace module. However, only when we
32554 // try to resolve name in /*1*/ which is used in variable position,
32555 // we want to check for block-scoped
32556 if (errorLocation &&
32557 (meaning & 2 /* BlockScopedVariable */ ||
32558 ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) {
32559 var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
32560 if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
32561 checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
32562 }
32563 }
32564 // If we're in an external module, we can't reference value symbols created from UMD export declarations
32565 if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) {
32566 var merged = getMergedSymbol(result);
32567 if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
32568 error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217
32569 }
32570 }
32571 }
32572 return result;
32573 }
32574 function isSelfReferenceLocation(node) {
32575 switch (node.kind) {
32576 case 239 /* FunctionDeclaration */:
32577 case 240 /* ClassDeclaration */:
32578 case 241 /* InterfaceDeclaration */:
32579 case 243 /* EnumDeclaration */:
32580 case 242 /* TypeAliasDeclaration */:
32581 case 244 /* ModuleDeclaration */: // For `namespace N { N; }`
32582 return true;
32583 default:
32584 return false;
32585 }
32586 }
32587 function diagnosticName(nameArg) {
32588 return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
32589 }
32590 function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
32591 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
32592 var decl = _a[_i];
32593 if (decl.kind === 150 /* TypeParameter */) {
32594 var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
32595 if (parent === container) {
32596 return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
32597 }
32598 }
32599 }
32600 return false;
32601 }
32602 function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
32603 if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
32604 return false;
32605 }
32606 var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
32607 var location = container;
32608 while (location) {
32609 if (ts.isClassLike(location.parent)) {
32610 var classSymbol = getSymbolOfNode(location.parent);
32611 if (!classSymbol) {
32612 break;
32613 }
32614 // Check to see if a static member exists.
32615 var constructorType = getTypeOfSymbol(classSymbol);
32616 if (getPropertyOfType(constructorType, name)) {
32617 error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
32618 return true;
32619 }
32620 // No static member is present.
32621 // Check if we're in an instance method and look for a relevant instance member.
32622 if (location === container && !ts.hasModifier(location, 32 /* Static */)) {
32623 var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
32624 if (getPropertyOfType(instanceType, name)) {
32625 error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
32626 return true;
32627 }
32628 }
32629 }
32630 location = location.parent;
32631 }
32632 return false;
32633 }
32634 function checkAndReportErrorForExtendingInterface(errorLocation) {
32635 var expression = getEntityNameForExtendingInterface(errorLocation);
32636 if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
32637 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
32638 return true;
32639 }
32640 return false;
32641 }
32642 /**
32643 * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
32644 * but returns undefined if that expression is not an EntityNameExpression.
32645 */
32646 function getEntityNameForExtendingInterface(node) {
32647 switch (node.kind) {
32648 case 72 /* Identifier */:
32649 case 189 /* PropertyAccessExpression */:
32650 return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
32651 case 211 /* ExpressionWithTypeArguments */:
32652 if (ts.isEntityNameExpression(node.expression)) {
32653 return node.expression;
32654 }
32655 // falls through
32656 default:
32657 return undefined;
32658 }
32659 }
32660 function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
32661 var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0);
32662 if (meaning === namespaceMeaning) {
32663 var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
32664 var parent = errorLocation.parent;
32665 if (symbol) {
32666 if (ts.isQualifiedName(parent)) {
32667 ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
32668 var propName = parent.right.escapedText;
32669 var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
32670 if (propType) {
32671 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));
32672 return true;
32673 }
32674 }
32675 error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
32676 return true;
32677 }
32678 }
32679 return false;
32680 }
32681 function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
32682 if (meaning & (67897832 /* Type */ & ~1920 /* Namespace */)) {
32683 var symbol = resolveSymbol(resolveName(errorLocation, name, ~67897832 /* Type */ & 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
32684 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
32685 error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, ts.unescapeLeadingUnderscores(name));
32686 return true;
32687 }
32688 }
32689 return false;
32690 }
32691 function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
32692 if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) {
32693 if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") {
32694 error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
32695 return true;
32696 }
32697 var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
32698 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
32699 var message = isES2015OrLaterConstructorName(name)
32700 ? 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
32701 : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
32702 error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
32703 return true;
32704 }
32705 }
32706 return false;
32707 }
32708 function isES2015OrLaterConstructorName(n) {
32709 switch (n) {
32710 case "Promise":
32711 case "Symbol":
32712 case "Map":
32713 case "WeakMap":
32714 case "Set":
32715 case "WeakSet":
32716 return true;
32717 }
32718 return false;
32719 }
32720 function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
32721 if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) {
32722 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
32723 if (symbol) {
32724 error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
32725 return true;
32726 }
32727 }
32728 else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) {
32729 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
32730 if (symbol) {
32731 error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
32732 return true;
32733 }
32734 }
32735 return false;
32736 }
32737 function checkResolvedBlockScopedVariable(result, errorLocation) {
32738 ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
32739 // Block-scoped variables cannot be used before their definition
32740 var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 243 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); });
32741 if (declaration === undefined)
32742 return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined");
32743 if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
32744 var diagnosticMessage = void 0;
32745 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
32746 if (result.flags & 2 /* BlockScopedVariable */) {
32747 diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
32748 }
32749 else if (result.flags & 32 /* Class */) {
32750 diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
32751 }
32752 else if (result.flags & 256 /* RegularEnum */) {
32753 diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
32754 }
32755 else {
32756 ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
32757 if (compilerOptions.preserveConstEnums) {
32758 diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
32759 }
32760 }
32761 if (diagnosticMessage) {
32762 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
32763 }
32764 }
32765 }
32766 /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
32767 * If at any point current node is equal to 'parent' node - return true.
32768 * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
32769 */
32770 function isSameScopeDescendentOf(initial, parent, stopAt) {
32771 return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
32772 }
32773 function getAnyImportSyntax(node) {
32774 switch (node.kind) {
32775 case 248 /* ImportEqualsDeclaration */:
32776 return node;
32777 case 250 /* ImportClause */:
32778 return node.parent;
32779 case 251 /* NamespaceImport */:
32780 return node.parent.parent;
32781 case 253 /* ImportSpecifier */:
32782 return node.parent.parent.parent;
32783 default:
32784 return undefined;
32785 }
32786 }
32787 function getDeclarationOfAliasSymbol(symbol) {
32788 return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration);
32789 }
32790 function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
32791 if (node.moduleReference.kind === 259 /* ExternalModuleReference */) {
32792 return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node)));
32793 }
32794 return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
32795 }
32796 function resolveExportByName(moduleSymbol, name, dontResolveAlias) {
32797 var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
32798 return exportValue
32799 ? getPropertyOfType(getTypeOfSymbol(exportValue), name)
32800 : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias);
32801 }
32802 function isSyntacticDefault(node) {
32803 return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
32804 }
32805 function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
32806 if (!allowSyntheticDefaultImports) {
32807 return false;
32808 }
32809 // Declaration files (and ambient modules)
32810 if (!file || file.isDeclarationFile) {
32811 // Definitely cannot have a synthetic default if they have a syntactic default member specified
32812 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
32813 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
32814 return false;
32815 }
32816 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
32817 // So we check a bit more,
32818 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) {
32819 // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
32820 // it definitely is a module and does not have a synthetic default
32821 return false;
32822 }
32823 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
32824 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
32825 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
32826 return true;
32827 }
32828 // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
32829 if (!ts.isSourceFileJS(file)) {
32830 return hasExportAssignmentSymbol(moduleSymbol);
32831 }
32832 // 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
32833 return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias);
32834 }
32835 function getTargetOfImportClause(node, dontResolveAlias) {
32836 var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
32837 if (moduleSymbol) {
32838 var exportDefaultSymbol = void 0;
32839 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
32840 exportDefaultSymbol = moduleSymbol;
32841 }
32842 else {
32843 exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias);
32844 }
32845 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
32846 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
32847 if (!exportDefaultSymbol && !hasSyntheticDefault) {
32848 error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
32849 }
32850 else if (hasSyntheticDefault) {
32851 // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
32852 return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
32853 }
32854 return exportDefaultSymbol;
32855 }
32856 }
32857 function getTargetOfNamespaceImport(node, dontResolveAlias) {
32858 var moduleSpecifier = node.parent.parent.moduleSpecifier;
32859 return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias);
32860 }
32861 // This function creates a synthetic symbol that combines the value side of one symbol with the
32862 // type/namespace side of another symbol. Consider this example:
32863 //
32864 // declare module graphics {
32865 // interface Point {
32866 // x: number;
32867 // y: number;
32868 // }
32869 // }
32870 // declare var graphics: {
32871 // Point: new (x: number, y: number) => graphics.Point;
32872 // }
32873 // declare module "graphics" {
32874 // export = graphics;
32875 // }
32876 //
32877 // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
32878 // property with the type/namespace side interface 'Point'.
32879 function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
32880 if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
32881 return unknownSymbol;
32882 }
32883 if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) {
32884 return valueSymbol;
32885 }
32886 var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
32887 result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
32888 result.parent = valueSymbol.parent || typeSymbol.parent;
32889 if (valueSymbol.valueDeclaration)
32890 result.valueDeclaration = valueSymbol.valueDeclaration;
32891 if (typeSymbol.members)
32892 result.members = typeSymbol.members;
32893 if (valueSymbol.exports)
32894 result.exports = valueSymbol.exports;
32895 return result;
32896 }
32897 function getExportOfModule(symbol, name, dontResolveAlias) {
32898 if (symbol.flags & 1536 /* Module */) {
32899 return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias);
32900 }
32901 }
32902 function getPropertyOfVariable(symbol, name) {
32903 if (symbol.flags & 3 /* Variable */) {
32904 var typeAnnotation = symbol.valueDeclaration.type;
32905 if (typeAnnotation) {
32906 return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
32907 }
32908 }
32909 }
32910 function getExternalModuleMember(node, specifier, dontResolveAlias) {
32911 if (dontResolveAlias === void 0) { dontResolveAlias = false; }
32912 var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217
32913 var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias);
32914 if (targetSymbol) {
32915 var name = specifier.propertyName || specifier.name;
32916 if (name.escapedText) {
32917 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
32918 return moduleSymbol;
32919 }
32920 var symbolFromVariable = void 0;
32921 // First check if module was specified with "export=". If so, get the member from the resolved type
32922 if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
32923 symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
32924 }
32925 else {
32926 symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
32927 }
32928 // if symbolFromVariable is export - get its final target
32929 symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
32930 var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias);
32931 // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default
32932 if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) {
32933 symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
32934 }
32935 var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
32936 combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
32937 symbolFromModule || symbolFromVariable;
32938 if (!symbol) {
32939 var moduleName = getFullyQualifiedName(moduleSymbol, node);
32940 var declarationName = ts.declarationNameToString(name);
32941 var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
32942 if (suggestion !== undefined) {
32943 var suggestionName = symbolToString(suggestion);
32944 var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
32945 if (suggestion.valueDeclaration) {
32946 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
32947 }
32948 }
32949 else {
32950 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
32951 }
32952 }
32953 return symbol;
32954 }
32955 }
32956 }
32957 function getTargetOfImportSpecifier(node, dontResolveAlias) {
32958 return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
32959 }
32960 function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
32961 return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
32962 }
32963 function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
32964 return node.parent.parent.moduleSpecifier ?
32965 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
32966 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
32967 }
32968 function getTargetOfExportAssignment(node, dontResolveAlias) {
32969 var expression = (ts.isExportAssignment(node) ? node.expression : node.right);
32970 if (ts.isClassExpression(expression)) {
32971 return checkExpression(expression).symbol;
32972 }
32973 var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
32974 if (aliasLike) {
32975 return aliasLike;
32976 }
32977 checkExpression(expression);
32978 return getNodeLinks(expression).resolvedSymbol;
32979 }
32980 function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
32981 if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
32982 switch (node.kind) {
32983 case 248 /* ImportEqualsDeclaration */:
32984 return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
32985 case 250 /* ImportClause */:
32986 return getTargetOfImportClause(node, dontRecursivelyResolve);
32987 case 251 /* NamespaceImport */:
32988 return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
32989 case 253 /* ImportSpecifier */:
32990 return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
32991 case 257 /* ExportSpecifier */:
32992 return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
32993 case 254 /* ExportAssignment */:
32994 case 204 /* BinaryExpression */:
32995 return getTargetOfExportAssignment(node, dontRecursivelyResolve);
32996 case 247 /* NamespaceExportDeclaration */:
32997 return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
32998 default:
32999 return ts.Debug.fail();
33000 }
33001 }
33002 /**
33003 * Indicates that a symbol is an alias that does not merge with a local declaration.
33004 * OR Is a JSContainer which may merge an alias with a local declaration
33005 */
33006 function isNonLocalAlias(symbol, excludes) {
33007 if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; }
33008 if (!symbol)
33009 return false;
33010 return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
33011 }
33012 function resolveSymbol(symbol, dontResolveAlias) {
33013 return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
33014 }
33015 function resolveAlias(symbol) {
33016 ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
33017 var links = getSymbolLinks(symbol);
33018 if (!links.target) {
33019 links.target = resolvingSymbol;
33020 var node = getDeclarationOfAliasSymbol(symbol);
33021 if (!node)
33022 return ts.Debug.fail();
33023 var target = getTargetOfAliasDeclaration(node);
33024 if (links.target === resolvingSymbol) {
33025 links.target = target || unknownSymbol;
33026 }
33027 else {
33028 error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
33029 }
33030 }
33031 else if (links.target === resolvingSymbol) {
33032 links.target = unknownSymbol;
33033 }
33034 return links.target;
33035 }
33036 function markExportAsReferenced(node) {
33037 var symbol = getSymbolOfNode(node);
33038 var target = resolveAlias(symbol);
33039 if (target) {
33040 var markAlias = target === unknownSymbol ||
33041 ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target));
33042 if (markAlias) {
33043 markAliasSymbolAsReferenced(symbol);
33044 }
33045 }
33046 }
33047 // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
33048 // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
33049 // the alias as an expression (which recursively takes us back here if the target references another alias).
33050 function markAliasSymbolAsReferenced(symbol) {
33051 var links = getSymbolLinks(symbol);
33052 if (!links.referenced) {
33053 links.referenced = true;
33054 var node = getDeclarationOfAliasSymbol(symbol);
33055 if (!node)
33056 return ts.Debug.fail();
33057 if (node.kind === 254 /* ExportAssignment */) {
33058 // export default <symbol>
33059 checkExpressionCached(node.expression);
33060 }
33061 else if (node.kind === 257 /* ExportSpecifier */) {
33062 // export { <symbol> } or export { <symbol> as foo }
33063 checkExpressionCached(node.propertyName || node.name);
33064 }
33065 else if (ts.isInternalModuleImportEqualsDeclaration(node)) {
33066 // import foo = <symbol>
33067 checkExpressionCached(node.moduleReference);
33068 }
33069 }
33070 }
33071 // This function is only for imports with entity names
33072 function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
33073 // There are three things we might try to look for. In the following examples,
33074 // the search term is enclosed in |...|:
33075 //
33076 // import a = |b|; // Namespace
33077 // import a = |b.c|; // Value, type, namespace
33078 // import a = |b.c|.d; // Namespace
33079 if (entityName.kind === 72 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
33080 entityName = entityName.parent;
33081 }
33082 // Check for case 1 and 3 in the above example
33083 if (entityName.kind === 72 /* Identifier */ || entityName.parent.kind === 148 /* QualifiedName */) {
33084 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
33085 }
33086 else {
33087 // Case 2 in above example
33088 // entityName.kind could be a QualifiedName or a Missing identifier
33089 ts.Debug.assert(entityName.parent.kind === 248 /* ImportEqualsDeclaration */);
33090 return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
33091 }
33092 }
33093 function getFullyQualifiedName(symbol, containingLocation) {
33094 return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
33095 }
33096 /**
33097 * Resolves a qualified name and any involved aliases.
33098 */
33099 function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
33100 if (ts.nodeIsMissing(name)) {
33101 return undefined;
33102 }
33103 var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0);
33104 var symbol;
33105 if (name.kind === 72 /* Identifier */) {
33106 var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText);
33107 var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
33108 symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true);
33109 if (!symbol) {
33110 return symbolFromJSPrototype;
33111 }
33112 }
33113 else if (name.kind === 148 /* QualifiedName */ || name.kind === 189 /* PropertyAccessExpression */) {
33114 var left = name.kind === 148 /* QualifiedName */ ? name.left : name.expression;
33115 var right = name.kind === 148 /* QualifiedName */ ? name.right : name.name;
33116 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
33117 if (!namespace || ts.nodeIsMissing(right)) {
33118 return undefined;
33119 }
33120 else if (namespace === unknownSymbol) {
33121 return namespace;
33122 }
33123 if (ts.isInJSFile(name)) {
33124 if (namespace.valueDeclaration &&
33125 ts.isVariableDeclaration(namespace.valueDeclaration) &&
33126 namespace.valueDeclaration.initializer &&
33127 isCommonJsRequire(namespace.valueDeclaration.initializer)) {
33128 var moduleName = namespace.valueDeclaration.initializer.arguments[0];
33129 var moduleSym = resolveExternalModuleName(moduleName, moduleName);
33130 if (moduleSym) {
33131 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
33132 if (resolvedModuleSymbol) {
33133 namespace = resolvedModuleSymbol;
33134 }
33135 }
33136 }
33137 }
33138 symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning);
33139 if (!symbol) {
33140 if (!ignoreErrors) {
33141 error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
33142 }
33143 return undefined;
33144 }
33145 }
33146 else {
33147 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
33148 }
33149 ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
33150 return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
33151 }
33152 /**
33153 * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
33154 * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
33155 * name resolution won't work either.
33156 * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
33157 */
33158 function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
33159 if (isJSDocTypeReference(name.parent)) {
33160 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
33161 if (secondaryLocation) {
33162 return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
33163 }
33164 }
33165 }
33166 function getAssignmentDeclarationLocation(node) {
33167 var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
33168 if (typeAlias) {
33169 return;
33170 }
33171 var host = ts.getJSDocHost(node);
33172 if (ts.isExpressionStatement(host) &&
33173 ts.isBinaryExpression(host.expression) &&
33174 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
33175 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
33176 var symbol = getSymbolOfNode(host.expression.left);
33177 if (symbol) {
33178 return getDeclarationOfJSPrototypeContainer(symbol);
33179 }
33180 }
33181 if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
33182 ts.isBinaryExpression(host.parent.parent) &&
33183 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
33184 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
33185 var symbol = getSymbolOfNode(host.parent.parent.left);
33186 if (symbol) {
33187 return getDeclarationOfJSPrototypeContainer(symbol);
33188 }
33189 }
33190 var sig = ts.getHostSignatureFromJSDocHost(host);
33191 if (sig) {
33192 var symbol = getSymbolOfNode(sig);
33193 return symbol && symbol.valueDeclaration;
33194 }
33195 }
33196 function getDeclarationOfJSPrototypeContainer(symbol) {
33197 var decl = symbol.parent.valueDeclaration;
33198 if (!decl) {
33199 return undefined;
33200 }
33201 var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
33202 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
33203 undefined;
33204 return initializer || decl;
33205 }
33206 function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
33207 return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0);
33208 }
33209 function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
33210 if (isForAugmentation === void 0) { isForAugmentation = false; }
33211 return ts.isStringLiteralLike(moduleReferenceExpression)
33212 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
33213 : undefined;
33214 }
33215 function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
33216 if (isForAugmentation === void 0) { isForAugmentation = false; }
33217 if (moduleReference === undefined) {
33218 return;
33219 }
33220 if (ts.startsWith(moduleReference, "@types/")) {
33221 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
33222 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
33223 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
33224 }
33225 var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
33226 if (ambientModule) {
33227 return ambientModule;
33228 }
33229 var currentSourceFile = ts.getSourceFileOfNode(location);
33230 var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
33231 var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
33232 var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
33233 if (sourceFile) {
33234 if (sourceFile.symbol) {
33235 if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
33236 errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
33237 }
33238 // merged symbol is module declaration symbol combined with all augmentations
33239 return getMergedSymbol(sourceFile.symbol);
33240 }
33241 if (moduleNotFoundError) {
33242 // report errors only if it was requested
33243 error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
33244 }
33245 return undefined;
33246 }
33247 if (patternAmbientModules) {
33248 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
33249 if (pattern) {
33250 return getMergedSymbol(pattern.symbol);
33251 }
33252 }
33253 // May be an untyped module. If so, ignore resolutionDiagnostic.
33254 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) {
33255 if (isForAugmentation) {
33256 var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
33257 error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
33258 }
33259 else {
33260 errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
33261 }
33262 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
33263 return undefined;
33264 }
33265 if (moduleNotFoundError) {
33266 // See if this was possibly a projectReference redirect
33267 if (resolvedModule) {
33268 var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
33269 if (redirect) {
33270 error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
33271 return undefined;
33272 }
33273 }
33274 if (resolutionDiagnostic) {
33275 error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
33276 }
33277 else {
33278 var tsExtension = ts.tryExtractTSExtension(moduleReference);
33279 if (tsExtension) {
33280 var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
33281 error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
33282 }
33283 else if (!compilerOptions.resolveJsonModule &&
33284 ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
33285 ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
33286 ts.hasJsonModuleEmitEnabled(compilerOptions)) {
33287 error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
33288 }
33289 else {
33290 error(errorNode, moduleNotFoundError, moduleReference);
33291 }
33292 }
33293 }
33294 return undefined;
33295 }
33296 function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
33297 var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
33298 var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
33299 ? typesPackageExists(packageId.name)
33300 ? ts.chainDiagnosticMessages(
33301 /*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))
33302 : ts.chainDiagnosticMessages(
33303 /*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))
33304 : undefined;
33305 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));
33306 }
33307 function typesPackageExists(packageName) {
33308 return getPackagesSet().has(ts.getTypesPackageName(packageName));
33309 }
33310 function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
33311 if (moduleSymbol) {
33312 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
33313 var exported = getCommonJsExportEquals(exportEquals, moduleSymbol);
33314 return getMergedSymbol(exported) || moduleSymbol;
33315 }
33316 return undefined;
33317 }
33318 function getCommonJsExportEquals(exported, moduleSymbol) {
33319 if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
33320 return exported;
33321 }
33322 var merged = cloneSymbol(exported);
33323 if (merged.exports === undefined) {
33324 merged.flags = merged.flags | 512 /* ValueModule */;
33325 merged.exports = ts.createSymbolTable();
33326 }
33327 moduleSymbol.exports.forEach(function (s, name) {
33328 if (name === "export=" /* ExportEquals */)
33329 return;
33330 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
33331 });
33332 return merged;
33333 }
33334 // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
33335 // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
33336 // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
33337 function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
33338 var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
33339 if (!dontResolveAlias && symbol) {
33340 if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
33341 var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
33342 ? "allowSyntheticDefaultImports"
33343 : "esModuleInterop";
33344 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);
33345 return symbol;
33346 }
33347 if (compilerOptions.esModuleInterop) {
33348 var referenceParent = referencingLocation.parent;
33349 if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
33350 ts.isImportCall(referenceParent)) {
33351 var type = getTypeOfSymbol(symbol);
33352 var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
33353 if (!sigs || !sigs.length) {
33354 sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
33355 }
33356 if (sigs && sigs.length) {
33357 var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
33358 // Create a new symbol which has the module's type less the call and construct signatures
33359 var result = createSymbol(symbol.flags, symbol.escapedName);
33360 result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
33361 result.parent = symbol.parent;
33362 result.target = symbol;
33363 result.originatingImport = referenceParent;
33364 if (symbol.valueDeclaration)
33365 result.valueDeclaration = symbol.valueDeclaration;
33366 if (symbol.constEnumOnlyModule)
33367 result.constEnumOnlyModule = true;
33368 if (symbol.members)
33369 result.members = ts.cloneMap(symbol.members);
33370 if (symbol.exports)
33371 result.exports = ts.cloneMap(symbol.exports);
33372 var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
33373 result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
33374 return result;
33375 }
33376 }
33377 }
33378 }
33379 return symbol;
33380 }
33381 function hasExportAssignmentSymbol(moduleSymbol) {
33382 return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
33383 }
33384 function getExportsOfModuleAsArray(moduleSymbol) {
33385 return symbolsToArray(getExportsOfModule(moduleSymbol));
33386 }
33387 function getExportsAndPropertiesOfModule(moduleSymbol) {
33388 var exports = getExportsOfModuleAsArray(moduleSymbol);
33389 var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
33390 if (exportEquals !== moduleSymbol) {
33391 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
33392 }
33393 return exports;
33394 }
33395 function tryGetMemberInModuleExports(memberName, moduleSymbol) {
33396 var symbolTable = getExportsOfModule(moduleSymbol);
33397 if (symbolTable) {
33398 return symbolTable.get(memberName);
33399 }
33400 }
33401 function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
33402 var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
33403 if (symbol) {
33404 return symbol;
33405 }
33406 var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
33407 if (exportEquals === moduleSymbol) {
33408 return undefined;
33409 }
33410 var type = getTypeOfSymbol(exportEquals);
33411 return type.flags & 131068 /* Primitive */ ? undefined : getPropertyOfType(type, memberName);
33412 }
33413 function getExportsOfSymbol(symbol) {
33414 return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
33415 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
33416 symbol.exports || emptySymbols;
33417 }
33418 function getExportsOfModule(moduleSymbol) {
33419 var links = getSymbolLinks(moduleSymbol);
33420 return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
33421 }
33422 /**
33423 * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
33424 * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
33425 */
33426 function extendExportSymbols(target, source, lookupTable, exportNode) {
33427 if (!source)
33428 return;
33429 source.forEach(function (sourceSymbol, id) {
33430 if (id === "default" /* Default */)
33431 return;
33432 var targetSymbol = target.get(id);
33433 if (!targetSymbol) {
33434 target.set(id, sourceSymbol);
33435 if (lookupTable && exportNode) {
33436 lookupTable.set(id, {
33437 specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
33438 });
33439 }
33440 }
33441 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
33442 var collisionTracker = lookupTable.get(id);
33443 if (!collisionTracker.exportsWithDuplicate) {
33444 collisionTracker.exportsWithDuplicate = [exportNode];
33445 }
33446 else {
33447 collisionTracker.exportsWithDuplicate.push(exportNode);
33448 }
33449 }
33450 });
33451 }
33452 function getExportsOfModuleWorker(moduleSymbol) {
33453 var visitedSymbols = [];
33454 // A module defined by an 'export=' consists of one export that needs to be resolved
33455 moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
33456 return visit(moduleSymbol) || emptySymbols;
33457 // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
33458 // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
33459 function visit(symbol) {
33460 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
33461 return;
33462 }
33463 var symbols = ts.cloneMap(symbol.exports);
33464 // All export * declarations are collected in an __export symbol by the binder
33465 var exportStars = symbol.exports.get("__export" /* ExportStar */);
33466 if (exportStars) {
33467 var nestedSymbols = ts.createSymbolTable();
33468 var lookupTable_1 = ts.createMap();
33469 for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
33470 var node = _a[_i];
33471 var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
33472 var exportedSymbols = visit(resolvedModule);
33473 extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
33474 }
33475 lookupTable_1.forEach(function (_a, id) {
33476 var exportsWithDuplicate = _a.exportsWithDuplicate;
33477 // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
33478 if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
33479 return;
33480 }
33481 for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
33482 var node = exportsWithDuplicate_1[_i];
33483 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)));
33484 }
33485 });
33486 extendExportSymbols(symbols, nestedSymbols);
33487 }
33488 return symbols;
33489 }
33490 }
33491 function getMergedSymbol(symbol) {
33492 var merged;
33493 return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
33494 }
33495 function getSymbolOfNode(node) {
33496 return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
33497 }
33498 function getParentOfSymbol(symbol) {
33499 return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
33500 }
33501 function getAlternativeContainingModules(symbol, enclosingDeclaration) {
33502 var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
33503 var id = "" + getNodeId(containingFile);
33504 var links = getSymbolLinks(symbol);
33505 var results;
33506 if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
33507 return results;
33508 }
33509 if (containingFile && containingFile.imports) {
33510 // Try to make an import using an import already in the enclosing file, if possible
33511 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
33512 var importRef = _a[_i];
33513 if (ts.nodeIsSynthesized(importRef))
33514 continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
33515 var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
33516 if (!resolvedModule)
33517 continue;
33518 var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
33519 if (!ref)
33520 continue;
33521 results = ts.append(results, resolvedModule);
33522 }
33523 if (ts.length(results)) {
33524 (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
33525 return results;
33526 }
33527 }
33528 if (links.extendedContainers) {
33529 return links.extendedContainers;
33530 }
33531 // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
33532 var otherFiles = host.getSourceFiles();
33533 for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
33534 var file = otherFiles_1[_b];
33535 if (!ts.isExternalModule(file))
33536 continue;
33537 var sym = getSymbolOfNode(file);
33538 var ref = getAliasForSymbolInContainer(sym, symbol);
33539 if (!ref)
33540 continue;
33541 results = ts.append(results, sym);
33542 }
33543 return links.extendedContainers = results || ts.emptyArray;
33544 }
33545 /**
33546 * Attempts to find the symbol corresponding to the container a symbol is in - usually this
33547 * is just its' `.parent`, but for locals, this value is `undefined`
33548 */
33549 function getContainersOfSymbol(symbol, enclosingDeclaration) {
33550 var container = getParentOfSymbol(symbol);
33551 if (container) {
33552 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
33553 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
33554 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
33555 return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
33556 }
33557 var res = ts.append(additionalContainers, container);
33558 return ts.concatenate(res, reexportContainers);
33559 }
33560 var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; });
33561 if (!ts.length(candidates)) {
33562 return undefined;
33563 }
33564 return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
33565 function fileSymbolIfFileSymbolExportEqualsContainer(d) {
33566 var fileSymbol = getExternalModuleContainer(d);
33567 var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
33568 return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined;
33569 }
33570 }
33571 function getAliasForSymbolInContainer(container, symbol) {
33572 if (container === getParentOfSymbol(symbol)) {
33573 // fast path, `symbol` is either already the alias or isn't aliased
33574 return symbol;
33575 }
33576 var exports = getExportsOfSymbol(container);
33577 var quick = exports.get(symbol.escapedName);
33578 if (quick && symbolRefersToTarget(quick)) {
33579 return quick;
33580 }
33581 return ts.forEachEntry(exports, function (exported) {
33582 if (symbolRefersToTarget(exported)) {
33583 return exported;
33584 }
33585 });
33586 function symbolRefersToTarget(s) {
33587 if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) {
33588 return s;
33589 }
33590 }
33591 }
33592 function getExportSymbolOfValueSymbolIfExported(symbol) {
33593 return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
33594 }
33595 function symbolIsValue(symbol) {
33596 return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */);
33597 }
33598 function findConstructorDeclaration(node) {
33599 var members = node.members;
33600 for (var _i = 0, members_2 = members; _i < members_2.length; _i++) {
33601 var member = members_2[_i];
33602 if (member.kind === 157 /* Constructor */ && ts.nodeIsPresent(member.body)) {
33603 return member;
33604 }
33605 }
33606 }
33607 function createType(flags) {
33608 var result = new Type(checker, flags);
33609 typeCount++;
33610 result.id = typeCount;
33611 return result;
33612 }
33613 function createIntrinsicType(kind, intrinsicName, objectFlags) {
33614 if (objectFlags === void 0) { objectFlags = 0; }
33615 var type = createType(kind);
33616 type.intrinsicName = intrinsicName;
33617 type.objectFlags = objectFlags;
33618 return type;
33619 }
33620 function createBooleanType(trueFalseTypes) {
33621 var type = getUnionType(trueFalseTypes);
33622 type.flags |= 16 /* Boolean */;
33623 type.intrinsicName = "boolean";
33624 return type;
33625 }
33626 function createObjectType(objectFlags, symbol) {
33627 var type = createType(524288 /* Object */);
33628 type.objectFlags = objectFlags;
33629 type.symbol = symbol;
33630 type.members = undefined;
33631 type.properties = undefined;
33632 type.callSignatures = undefined;
33633 type.constructSignatures = undefined;
33634 type.stringIndexInfo = undefined;
33635 type.numberIndexInfo = undefined;
33636 return type;
33637 }
33638 function createTypeofType() {
33639 return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
33640 }
33641 function createTypeParameter(symbol) {
33642 var type = createType(262144 /* TypeParameter */);
33643 if (symbol)
33644 type.symbol = symbol;
33645 return type;
33646 }
33647 // A reserved member name starts with two underscores, but the third character cannot be an underscore
33648 // or the @ symbol. A third underscore indicates an escaped form of an identifer that started
33649 // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
33650 // Symbol instance.
33651 function isReservedMemberName(name) {
33652 return name.charCodeAt(0) === 95 /* _ */ &&
33653 name.charCodeAt(1) === 95 /* _ */ &&
33654 name.charCodeAt(2) !== 95 /* _ */ &&
33655 name.charCodeAt(2) !== 64 /* at */;
33656 }
33657 function getNamedMembers(members) {
33658 var result;
33659 members.forEach(function (symbol, id) {
33660 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
33661 (result || (result = [])).push(symbol);
33662 }
33663 });
33664 return result || ts.emptyArray;
33665 }
33666 function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
33667 type.members = members;
33668 type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
33669 type.callSignatures = callSignatures;
33670 type.constructSignatures = constructSignatures;
33671 type.stringIndexInfo = stringIndexInfo;
33672 type.numberIndexInfo = numberIndexInfo;
33673 return type;
33674 }
33675 function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
33676 return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
33677 }
33678 function forEachSymbolTableInScope(enclosingDeclaration, callback) {
33679 var result;
33680 for (var location = enclosingDeclaration; location; location = location.parent) {
33681 // Locals of a source file are not in scope (because they get merged into the global symbol table)
33682 if (location.locals && !isGlobalSourceFile(location)) {
33683 if (result = callback(location.locals)) {
33684 return result;
33685 }
33686 }
33687 switch (location.kind) {
33688 case 284 /* SourceFile */:
33689 if (!ts.isExternalOrCommonJsModule(location)) {
33690 break;
33691 }
33692 // falls through
33693 case 244 /* ModuleDeclaration */:
33694 if (result = callback(getSymbolOfNode(location).exports)) {
33695 return result;
33696 }
33697 break;
33698 }
33699 }
33700 return callback(globals);
33701 }
33702 function getQualifiedLeftMeaning(rightMeaning) {
33703 // If we are looking in value space, the parent meaning is value, other wise it is namespace
33704 return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */;
33705 }
33706 function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
33707 if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
33708 if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
33709 return undefined;
33710 }
33711 var id = "" + getSymbolId(symbol);
33712 var visitedSymbolTables = visitedSymbolTablesMap.get(id);
33713 if (!visitedSymbolTables) {
33714 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
33715 }
33716 return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
33717 /**
33718 * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already)
33719 */
33720 function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
33721 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
33722 return undefined;
33723 }
33724 var result = trySymbolTable(symbols, ignoreQualification);
33725 visitedSymbolTables.pop();
33726 return result;
33727 }
33728 function canQualifySymbol(symbolFromSymbolTable, meaning) {
33729 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
33730 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
33731 // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
33732 !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
33733 }
33734 function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
33735 return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) &&
33736 // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
33737 // and if symbolFromSymbolTable or alias resolution matches the symbol,
33738 // check the symbol can be qualified, it is only then this symbol is accessible
33739 !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
33740 (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning));
33741 }
33742 function trySymbolTable(symbols, ignoreQualification) {
33743 // If symbol is directly available by its name in the symbol table
33744 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
33745 return [symbol];
33746 }
33747 // Check if symbol is any of the alias
33748 return ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
33749 if (symbolFromSymbolTable.flags & 2097152 /* Alias */
33750 && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
33751 && symbolFromSymbolTable.escapedName !== "default" /* Default */
33752 && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
33753 // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
33754 && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
33755 // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
33756 // See similar comment in `resolveName` for details
33757 && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */))) {
33758 var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
33759 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
33760 return [symbolFromSymbolTable];
33761 }
33762 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
33763 // but only if the symbolFromSymbolTable can be qualified
33764 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
33765 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
33766 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
33767 return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
33768 }
33769 }
33770 if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
33771 if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
33772 return [symbol];
33773 }
33774 }
33775 });
33776 }
33777 }
33778 function needsQualification(symbol, enclosingDeclaration, meaning) {
33779 var qualify = false;
33780 forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
33781 // If symbol of this name is not available in the symbol table we are ok
33782 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
33783 if (!symbolFromSymbolTable) {
33784 // Continue to the next symbol table
33785 return false;
33786 }
33787 // If the symbol with this name is present it should refer to the symbol
33788 if (symbolFromSymbolTable === symbol) {
33789 // No need to qualify
33790 return true;
33791 }
33792 // Qualify if the symbol from symbol table has same meaning as expected
33793 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 257 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
33794 if (symbolFromSymbolTable.flags & meaning) {
33795 qualify = true;
33796 return true;
33797 }
33798 // Continue to the next symbol table
33799 return false;
33800 });
33801 return qualify;
33802 }
33803 function isPropertyOrMethodDeclarationSymbol(symbol) {
33804 if (symbol.declarations && symbol.declarations.length) {
33805 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
33806 var declaration = _a[_i];
33807 switch (declaration.kind) {
33808 case 154 /* PropertyDeclaration */:
33809 case 156 /* MethodDeclaration */:
33810 case 158 /* GetAccessor */:
33811 case 159 /* SetAccessor */:
33812 continue;
33813 default:
33814 return false;
33815 }
33816 }
33817 return true;
33818 }
33819 return false;
33820 }
33821 function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
33822 var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
33823 return access.accessibility === 0 /* Accessible */;
33824 }
33825 function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
33826 var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
33827 return access.accessibility === 0 /* Accessible */;
33828 }
33829 function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) {
33830 if (!ts.length(symbols))
33831 return;
33832 var hadAccessibleChain;
33833 for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
33834 var symbol = _a[_i];
33835 // Symbol is accessible if it by itself is accessible
33836 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
33837 if (accessibleSymbolChain) {
33838 hadAccessibleChain = symbol;
33839 var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
33840 if (hasAccessibleDeclarations) {
33841 return hasAccessibleDeclarations;
33842 }
33843 }
33844 else {
33845 if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
33846 // Any meaning of a module symbol is always accessible via an `import` type
33847 return {
33848 accessibility: 0 /* Accessible */
33849 };
33850 }
33851 }
33852 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
33853 // It could be a qualified symbol and hence verify the path
33854 // e.g.:
33855 // module m {
33856 // export class c {
33857 // }
33858 // }
33859 // const x: typeof m.c
33860 // In the above example when we start with checking if typeof m.c symbol is accessible,
33861 // we are going to see if c can be accessed in scope directly.
33862 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
33863 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
33864 var containers = getContainersOfSymbol(symbol, enclosingDeclaration);
33865 // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
33866 // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
33867 // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal.
33868 var firstDecl = ts.first(symbol.declarations);
33869 if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) {
33870 if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) {
33871 containers = [getSymbolOfNode(firstDecl.parent)];
33872 }
33873 }
33874 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
33875 if (parentResult) {
33876 return parentResult;
33877 }
33878 }
33879 if (hadAccessibleChain) {
33880 return {
33881 accessibility: 1 /* NotAccessible */,
33882 errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
33883 errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
33884 };
33885 }
33886 }
33887 /**
33888 * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
33889 *
33890 * @param symbol a Symbol to check if accessible
33891 * @param enclosingDeclaration a Node containing reference to the symbol
33892 * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
33893 * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
33894 */
33895 function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
33896 if (symbol && enclosingDeclaration) {
33897 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible);
33898 if (result) {
33899 return result;
33900 }
33901 // This could be a symbol that is not exported in the external module
33902 // or it could be a symbol from different external module that is not aliased and hence cannot be named
33903 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
33904 if (symbolExternalModule) {
33905 var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
33906 if (symbolExternalModule !== enclosingExternalModule) {
33907 // name from different external module that is not visible
33908 return {
33909 accessibility: 2 /* CannotBeNamed */,
33910 errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
33911 errorModuleName: symbolToString(symbolExternalModule)
33912 };
33913 }
33914 }
33915 // Just a local name that is not accessible
33916 return {
33917 accessibility: 1 /* NotAccessible */,
33918 errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
33919 };
33920 }
33921 return { accessibility: 0 /* Accessible */ };
33922 }
33923 function getExternalModuleContainer(declaration) {
33924 var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
33925 return node && getSymbolOfNode(node);
33926 }
33927 function hasExternalModuleSymbol(declaration) {
33928 return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
33929 }
33930 function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
33931 return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
33932 }
33933 function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
33934 var aliasesToMakeVisible;
33935 if (!ts.every(symbol.declarations, getIsDeclarationVisible)) {
33936 return undefined;
33937 }
33938 return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
33939 function getIsDeclarationVisible(declaration) {
33940 if (!isDeclarationVisible(declaration)) {
33941 // Mark the unexported alias as visible if its parent is visible
33942 // because these kind of aliases can be used to name types in declaration file
33943 var anyImportSyntax = getAnyImportSyntax(declaration);
33944 if (anyImportSyntax &&
33945 !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
33946 isDeclarationVisible(anyImportSyntax.parent)) {
33947 return addVisibleAlias(declaration, anyImportSyntax);
33948 }
33949 else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
33950 !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
33951 isDeclarationVisible(declaration.parent.parent.parent)) {
33952 return addVisibleAlias(declaration, declaration.parent.parent);
33953 }
33954 else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
33955 && !ts.hasModifier(declaration, 1 /* Export */)
33956 && isDeclarationVisible(declaration.parent)) {
33957 return addVisibleAlias(declaration, declaration);
33958 }
33959 // Declaration is not visible
33960 return false;
33961 }
33962 return true;
33963 }
33964 function addVisibleAlias(declaration, aliasingStatement) {
33965 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
33966 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
33967 // since we will do the emitting later in trackSymbol.
33968 if (shouldComputeAliasToMakeVisible) {
33969 getNodeLinks(declaration).isVisible = true;
33970 aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
33971 }
33972 return true;
33973 }
33974 }
33975 function isEntityNameVisible(entityName, enclosingDeclaration) {
33976 // get symbol of the first identifier of the entityName
33977 var meaning;
33978 if (entityName.parent.kind === 167 /* TypeQuery */ ||
33979 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
33980 entityName.parent.kind === 149 /* ComputedPropertyName */) {
33981 // Typeof value
33982 meaning = 67220415 /* Value */ | 1048576 /* ExportValue */;
33983 }
33984 else if (entityName.kind === 148 /* QualifiedName */ || entityName.kind === 189 /* PropertyAccessExpression */ ||
33985 entityName.parent.kind === 248 /* ImportEqualsDeclaration */) {
33986 // Left identifier from type reference or TypeAlias
33987 // Entity name of the import declaration
33988 meaning = 1920 /* Namespace */;
33989 }
33990 else {
33991 // Type Reference or TypeAlias entity = Identifier
33992 meaning = 67897832 /* Type */;
33993 }
33994 var firstIdentifier = getFirstIdentifier(entityName);
33995 var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
33996 // Verify if the symbol is accessible
33997 return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
33998 accessibility: 1 /* NotAccessible */,
33999 errorSymbolName: ts.getTextOfNode(firstIdentifier),
34000 errorNode: firstIdentifier
34001 };
34002 }
34003 function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
34004 if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
34005 var nodeFlags = 70221824 /* IgnoreErrors */;
34006 if (flags & 2 /* UseOnlyExternalAliasing */) {
34007 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
34008 }
34009 if (flags & 1 /* WriteTypeParametersOrArguments */) {
34010 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
34011 }
34012 if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
34013 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
34014 }
34015 if (flags & 16 /* DoNotIncludeSymbolChain */) {
34016 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
34017 }
34018 var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
34019 return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
34020 function symbolToStringWorker(writer) {
34021 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
34022 var printer = ts.createPrinter({ removeComments: true });
34023 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
34024 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
34025 return writer;
34026 }
34027 }
34028 function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
34029 if (flags === void 0) { flags = 0 /* None */; }
34030 return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
34031 function signatureToStringWorker(writer) {
34032 var sigOutput;
34033 if (flags & 262144 /* WriteArrowStyleSignature */) {
34034 sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructorType */ : 165 /* FunctionType */;
34035 }
34036 else {
34037 sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */;
34038 }
34039 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
34040 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
34041 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
34042 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217
34043 return writer;
34044 }
34045 }
34046 function typeToString(type, enclosingDeclaration, flags, writer) {
34047 if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
34048 if (writer === void 0) { writer = ts.createTextWriter(""); }
34049 var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
34050 var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
34051 if (typeNode === undefined)
34052 return ts.Debug.fail("should always get typenode");
34053 var options = { removeComments: true };
34054 var printer = ts.createPrinter(options);
34055 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
34056 printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
34057 var result = writer.getText();
34058 var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2;
34059 if (maxLength && result && result.length >= maxLength) {
34060 return result.substr(0, maxLength - "...".length) + "...";
34061 }
34062 return result;
34063 }
34064 function toNodeBuilderFlags(flags) {
34065 if (flags === void 0) { flags = 0 /* None */; }
34066 return flags & 9469291 /* NodeBuilderFlagsMask */;
34067 }
34068 function createNodeBuilder() {
34069 return {
34070 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
34071 return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
34072 },
34073 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
34074 return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); });
34075 },
34076 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
34077 return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
34078 },
34079 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
34080 return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
34081 },
34082 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
34083 return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
34084 },
34085 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
34086 return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
34087 },
34088 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
34089 return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
34090 },
34091 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
34092 return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
34093 },
34094 };
34095 function withContext(enclosingDeclaration, flags, tracker, cb) {
34096 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
34097 var context = {
34098 enclosingDeclaration: enclosingDeclaration,
34099 flags: flags || 0 /* None */,
34100 // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
34101 tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
34102 getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
34103 getSourceFiles: function () { return host.getSourceFiles(); },
34104 getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); })
34105 } : undefined },
34106 encounteredError: false,
34107 visitedTypes: undefined,
34108 symbolDepth: undefined,
34109 inferTypeParameters: undefined,
34110 approximateLength: 0
34111 };
34112 var resultingNode = cb(context);
34113 return context.encounteredError ? undefined : resultingNode;
34114 }
34115 function checkTruncationLength(context) {
34116 if (context.truncating)
34117 return context.truncating;
34118 return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength;
34119 }
34120 function typeToTypeNodeHelper(type, context) {
34121 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
34122 cancellationToken.throwIfCancellationRequested();
34123 }
34124 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
34125 context.flags &= ~8388608 /* InTypeAlias */;
34126 if (!type) {
34127 context.encounteredError = true;
34128 return undefined; // TODO: GH#18217
34129 }
34130 if (type.flags & 1 /* Any */) {
34131 context.approximateLength += 3;
34132 return ts.createKeywordTypeNode(120 /* AnyKeyword */);
34133 }
34134 if (type.flags & 2 /* Unknown */) {
34135 return ts.createKeywordTypeNode(143 /* UnknownKeyword */);
34136 }
34137 if (type.flags & 4 /* String */) {
34138 context.approximateLength += 6;
34139 return ts.createKeywordTypeNode(138 /* StringKeyword */);
34140 }
34141 if (type.flags & 8 /* Number */) {
34142 context.approximateLength += 6;
34143 return ts.createKeywordTypeNode(135 /* NumberKeyword */);
34144 }
34145 if (type.flags & 64 /* BigInt */) {
34146 context.approximateLength += 6;
34147 return ts.createKeywordTypeNode(146 /* BigIntKeyword */);
34148 }
34149 if (type.flags & 16 /* Boolean */) {
34150 context.approximateLength += 7;
34151 return ts.createKeywordTypeNode(123 /* BooleanKeyword */);
34152 }
34153 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
34154 var parentSymbol = getParentOfSymbol(type.symbol);
34155 var parentName = symbolToTypeNode(parentSymbol, context, 67897832 /* Type */);
34156 var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type
34157 ? parentName
34158 : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined));
34159 return enumLiteralName;
34160 }
34161 if (type.flags & 1056 /* EnumLike */) {
34162 return symbolToTypeNode(type.symbol, context, 67897832 /* Type */);
34163 }
34164 if (type.flags & 128 /* StringLiteral */) {
34165 context.approximateLength += (type.value.length + 2);
34166 return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */));
34167 }
34168 if (type.flags & 256 /* NumberLiteral */) {
34169 context.approximateLength += (("" + type.value).length);
34170 return ts.createLiteralTypeNode((ts.createLiteral(type.value)));
34171 }
34172 if (type.flags & 2048 /* BigIntLiteral */) {
34173 context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
34174 return ts.createLiteralTypeNode((ts.createLiteral(type.value)));
34175 }
34176 if (type.flags & 512 /* BooleanLiteral */) {
34177 context.approximateLength += type.intrinsicName.length;
34178 return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse();
34179 }
34180 if (type.flags & 8192 /* UniqueESSymbol */) {
34181 if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
34182 if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
34183 context.approximateLength += 6;
34184 return symbolToTypeNode(type.symbol, context, 67220415 /* Value */);
34185 }
34186 if (context.tracker.reportInaccessibleUniqueSymbolError) {
34187 context.tracker.reportInaccessibleUniqueSymbolError();
34188 }
34189 }
34190 context.approximateLength += 13;
34191 return ts.createTypeOperatorNode(142 /* UniqueKeyword */, ts.createKeywordTypeNode(139 /* SymbolKeyword */));
34192 }
34193 if (type.flags & 16384 /* Void */) {
34194 context.approximateLength += 4;
34195 return ts.createKeywordTypeNode(106 /* VoidKeyword */);
34196 }
34197 if (type.flags & 32768 /* Undefined */) {
34198 context.approximateLength += 9;
34199 return ts.createKeywordTypeNode(141 /* UndefinedKeyword */);
34200 }
34201 if (type.flags & 65536 /* Null */) {
34202 context.approximateLength += 4;
34203 return ts.createKeywordTypeNode(96 /* NullKeyword */);
34204 }
34205 if (type.flags & 131072 /* Never */) {
34206 context.approximateLength += 5;
34207 return ts.createKeywordTypeNode(132 /* NeverKeyword */);
34208 }
34209 if (type.flags & 4096 /* ESSymbol */) {
34210 context.approximateLength += 6;
34211 return ts.createKeywordTypeNode(139 /* SymbolKeyword */);
34212 }
34213 if (type.flags & 67108864 /* NonPrimitive */) {
34214 context.approximateLength += 6;
34215 return ts.createKeywordTypeNode(136 /* ObjectKeyword */);
34216 }
34217 if (type.flags & 262144 /* TypeParameter */ && type.isThisType) {
34218 if (context.flags & 4194304 /* InObjectTypeLiteral */) {
34219 if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
34220 context.encounteredError = true;
34221 }
34222 if (context.tracker.reportInaccessibleThisError) {
34223 context.tracker.reportInaccessibleThisError();
34224 }
34225 }
34226 context.approximateLength += 4;
34227 return ts.createThis();
34228 }
34229 var objectFlags = ts.getObjectFlags(type);
34230 if (objectFlags & 4 /* Reference */) {
34231 ts.Debug.assert(!!(type.flags & 524288 /* Object */));
34232 return typeReferenceToTypeNode(type);
34233 }
34234 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
34235 if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
34236 context.approximateLength += (ts.symbolName(type.symbol).length + 6);
34237 return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
34238 }
34239 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
34240 type.flags & 262144 /* TypeParameter */ &&
34241 ts.length(type.symbol.declarations) &&
34242 ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
34243 typeParameterShadowsNameInScope(type, context) &&
34244 !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
34245 var name = type.symbol.declarations[0].name;
34246 context.approximateLength += ts.idText(name).length;
34247 return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined);
34248 }
34249 // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
34250 return type.symbol
34251 ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */)
34252 : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined);
34253 }
34254 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
34255 var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
34256 if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
34257 return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
34258 return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes);
34259 }
34260 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
34261 var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
34262 if (ts.length(types) === 1) {
34263 return typeToTypeNodeHelper(types[0], context);
34264 }
34265 var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
34266 if (typeNodes && typeNodes.length > 0) {
34267 var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 173 /* UnionType */ : 174 /* IntersectionType */, typeNodes);
34268 return unionOrIntersectionTypeNode;
34269 }
34270 else {
34271 if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
34272 context.encounteredError = true;
34273 }
34274 return undefined; // TODO: GH#18217
34275 }
34276 }
34277 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
34278 ts.Debug.assert(!!(type.flags & 524288 /* Object */));
34279 // The type is an object literal type.
34280 return createAnonymousTypeNode(type);
34281 }
34282 if (type.flags & 4194304 /* Index */) {
34283 var indexedType = type.type;
34284 context.approximateLength += 6;
34285 var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
34286 return ts.createTypeOperatorNode(indexTypeNode);
34287 }
34288 if (type.flags & 8388608 /* IndexedAccess */) {
34289 var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
34290 var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
34291 context.approximateLength += 2;
34292 return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
34293 }
34294 if (type.flags & 16777216 /* Conditional */) {
34295 var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
34296 var saveInferTypeParameters = context.inferTypeParameters;
34297 context.inferTypeParameters = type.root.inferTypeParameters;
34298 var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
34299 context.inferTypeParameters = saveInferTypeParameters;
34300 var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
34301 var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
34302 context.approximateLength += 15;
34303 return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
34304 }
34305 if (type.flags & 33554432 /* Substitution */) {
34306 return typeToTypeNodeHelper(type.typeVariable, context);
34307 }
34308 return ts.Debug.fail("Should be unreachable.");
34309 function createMappedTypeNodeFromType(type) {
34310 ts.Debug.assert(!!(type.flags & 524288 /* Object */));
34311 var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
34312 var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
34313 var appropriateConstraintTypeNode;
34314 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
34315 // We have a { [P in keyof T]: X }
34316 // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
34317 appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
34318 }
34319 else {
34320 appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
34321 }
34322 var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
34323 var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
34324 var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
34325 context.approximateLength += 10;
34326 return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
34327 }
34328 function createAnonymousTypeNode(type) {
34329 var typeId = "" + type.id;
34330 var symbol = type.symbol;
34331 var id;
34332 if (symbol) {
34333 var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
34334 id = (isConstructorObject ? "+" : "") + getSymbolId(symbol);
34335 if (isJSConstructor(symbol.valueDeclaration)) {
34336 // Instance and static types share the same symbol; only add 'typeof' for the static side.
34337 var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */;
34338 return symbolToTypeNode(symbol, context, isInstanceType);
34339 }
34340 // Always use 'typeof T' for type of class, enum, and module objects
34341 else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 209 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
34342 symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
34343 shouldWriteTypeOfFunctionSymbol()) {
34344 return symbolToTypeNode(symbol, context, 67220415 /* Value */);
34345 }
34346 else if (context.visitedTypes && context.visitedTypes.has(typeId)) {
34347 // If type is an anonymous type literal in a type alias declaration, use type alias name
34348 var typeAlias = getTypeAliasForTypeLiteral(type);
34349 if (typeAlias) {
34350 // The specified symbol flags need to be reinterpreted as type flags
34351 return symbolToTypeNode(typeAlias, context, 67897832 /* Type */);
34352 }
34353 else {
34354 return createElidedInformationPlaceholder(context);
34355 }
34356 }
34357 else {
34358 // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
34359 // of types allows us to catch circular references to instantiations of the same anonymous type
34360 if (!context.visitedTypes) {
34361 context.visitedTypes = ts.createMap();
34362 }
34363 if (!context.symbolDepth) {
34364 context.symbolDepth = ts.createMap();
34365 }
34366 var depth = context.symbolDepth.get(id) || 0;
34367 if (depth > 10) {
34368 return createElidedInformationPlaceholder(context);
34369 }
34370 context.symbolDepth.set(id, depth + 1);
34371 context.visitedTypes.set(typeId, true);
34372 var result = createTypeNodeFromObjectType(type);
34373 context.visitedTypes.delete(typeId);
34374 context.symbolDepth.set(id, depth);
34375 return result;
34376 }
34377 }
34378 else {
34379 // Anonymous types without a symbol are never circular.
34380 return createTypeNodeFromObjectType(type);
34381 }
34382 function shouldWriteTypeOfFunctionSymbol() {
34383 var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
34384 ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); });
34385 var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
34386 (symbol.parent || // is exported function symbol
34387 ts.forEach(symbol.declarations, function (declaration) {
34388 return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
34389 }));
34390 if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
34391 // typeof is allowed only for static/non local functions
34392 return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively
34393 (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed
34394 }
34395 }
34396 }
34397 function createTypeNodeFromObjectType(type) {
34398 if (isGenericMappedType(type)) {
34399 return createMappedTypeNodeFromType(type);
34400 }
34401 var resolved = resolveStructuredTypeMembers(type);
34402 if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
34403 if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
34404 context.approximateLength += 2;
34405 return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
34406 }
34407 if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
34408 var signature = resolved.callSignatures[0];
34409 var signatureNode = signatureToSignatureDeclarationHelper(signature, 165 /* FunctionType */, context);
34410 return signatureNode;
34411 }
34412 if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
34413 var signature = resolved.constructSignatures[0];
34414 var signatureNode = signatureToSignatureDeclarationHelper(signature, 166 /* ConstructorType */, context);
34415 return signatureNode;
34416 }
34417 }
34418 var savedFlags = context.flags;
34419 context.flags |= 4194304 /* InObjectTypeLiteral */;
34420 var members = createTypeNodesFromResolvedType(resolved);
34421 context.flags = savedFlags;
34422 var typeLiteralNode = ts.createTypeLiteralNode(members);
34423 context.approximateLength += 2;
34424 return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
34425 }
34426 function typeReferenceToTypeNode(type) {
34427 var typeArguments = type.typeArguments || ts.emptyArray;
34428 if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
34429 if (context.flags & 2 /* WriteArrayAsGenericType */) {
34430 var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
34431 return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
34432 }
34433 var elementType = typeToTypeNodeHelper(typeArguments[0], context);
34434 var arrayType = ts.createArrayTypeNode(elementType);
34435 return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, arrayType);
34436 }
34437 else if (type.target.objectFlags & 8 /* Tuple */) {
34438 if (typeArguments.length > 0) {
34439 var arity = getTypeReferenceArity(type);
34440 var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
34441 var hasRestElement = type.target.hasRestElement;
34442 if (tupleConstituentNodes) {
34443 for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) {
34444 tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ?
34445 ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
34446 ts.createOptionalTypeNode(tupleConstituentNodes[i]);
34447 }
34448 var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
34449 return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
34450 }
34451 }
34452 if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
34453 var tupleTypeNode = ts.createTupleTypeNode([]);
34454 return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
34455 }
34456 context.encounteredError = true;
34457 return undefined; // TODO: GH#18217
34458 }
34459 else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
34460 type.symbol.valueDeclaration &&
34461 ts.isClassLike(type.symbol.valueDeclaration) &&
34462 !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
34463 return createAnonymousTypeNode(type);
34464 }
34465 else {
34466 var outerTypeParameters = type.target.outerTypeParameters;
34467 var i = 0;
34468 var resultType = void 0;
34469 if (outerTypeParameters) {
34470 var length_1 = outerTypeParameters.length;
34471 while (i < length_1) {
34472 // Find group of type arguments for type parameters with the same declaring container.
34473 var start = i;
34474 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
34475 do {
34476 i++;
34477 } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
34478 // When type parameters are their own type arguments for the whole group (i.e. we have
34479 // the default outer type arguments), we don't show the group.
34480 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
34481 var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
34482 var flags_2 = context.flags;
34483 context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
34484 var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice);
34485 context.flags = flags_2;
34486 resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
34487 }
34488 }
34489 }
34490 var typeArgumentNodes = void 0;
34491 if (typeArguments.length > 0) {
34492 var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
34493 typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
34494 }
34495 var flags = context.flags;
34496 context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
34497 var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes);
34498 context.flags = flags;
34499 return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
34500 }
34501 }
34502 function appendReferenceToType(root, ref) {
34503 if (ts.isImportTypeNode(root)) {
34504 // first shift type arguments
34505 var innerParams = root.typeArguments;
34506 if (root.qualifier) {
34507 (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
34508 }
34509 root.typeArguments = ref.typeArguments;
34510 // then move qualifiers
34511 var ids = getAccessStack(ref);
34512 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
34513 var id = ids_1[_i];
34514 root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
34515 }
34516 return root;
34517 }
34518 else {
34519 // first shift type arguments
34520 var innerParams = root.typeArguments;
34521 (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
34522 root.typeArguments = ref.typeArguments;
34523 // then move qualifiers
34524 var ids = getAccessStack(ref);
34525 for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
34526 var id = ids_2[_a];
34527 root.typeName = ts.createQualifiedName(root.typeName, id);
34528 }
34529 return root;
34530 }
34531 }
34532 function getAccessStack(ref) {
34533 var state = ref.typeName;
34534 var ids = [];
34535 while (!ts.isIdentifier(state)) {
34536 ids.unshift(state.right);
34537 state = state.left;
34538 }
34539 ids.unshift(state);
34540 return ids;
34541 }
34542 function createTypeNodesFromResolvedType(resolvedType) {
34543 if (checkTruncationLength(context)) {
34544 return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)];
34545 }
34546 var typeElements = [];
34547 for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
34548 var signature = _a[_i];
34549 typeElements.push(signatureToSignatureDeclarationHelper(signature, 160 /* CallSignature */, context));
34550 }
34551 for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
34552 var signature = _c[_b];
34553 typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context));
34554 }
34555 if (resolvedType.stringIndexInfo) {
34556 var indexSignature = void 0;
34557 if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
34558 indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
34559 indexSignature.type = createElidedInformationPlaceholder(context);
34560 }
34561 else {
34562 indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
34563 }
34564 typeElements.push(indexSignature);
34565 }
34566 if (resolvedType.numberIndexInfo) {
34567 typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
34568 }
34569 var properties = resolvedType.properties;
34570 if (!properties) {
34571 return typeElements;
34572 }
34573 var i = 0;
34574 for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
34575 var propertySymbol = properties_1[_d];
34576 i++;
34577 if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
34578 if (propertySymbol.flags & 4194304 /* Prototype */) {
34579 continue;
34580 }
34581 if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
34582 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
34583 }
34584 }
34585 if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
34586 typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
34587 addPropertyToElementList(properties[properties.length - 1], context, typeElements);
34588 break;
34589 }
34590 addPropertyToElementList(propertySymbol, context, typeElements);
34591 }
34592 return typeElements.length ? typeElements : undefined;
34593 }
34594 }
34595 function createElidedInformationPlaceholder(context) {
34596 context.approximateLength += 3;
34597 if (!(context.flags & 1 /* NoTruncation */)) {
34598 return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
34599 }
34600 return ts.createKeywordTypeNode(120 /* AnyKeyword */);
34601 }
34602 function addPropertyToElementList(propertySymbol, context, typeElements) {
34603 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 4096 /* ReverseMapped */);
34604 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
34605 anyType : getTypeOfSymbol(propertySymbol);
34606 var saveEnclosingDeclaration = context.enclosingDeclaration;
34607 context.enclosingDeclaration = undefined;
34608 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 2048 /* Late */) {
34609 var decl = ts.first(propertySymbol.declarations);
34610 if (hasLateBindableName(decl)) {
34611 trackComputedName(decl.name, saveEnclosingDeclaration, context);
34612 }
34613 }
34614 var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true);
34615 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
34616 context.enclosingDeclaration = saveEnclosingDeclaration;
34617 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined;
34618 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
34619 var signatures = getSignaturesOfType(propertyType, 0 /* Call */);
34620 for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
34621 var signature = signatures_1[_i];
34622 var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 155 /* MethodSignature */, context);
34623 methodDeclaration.name = propertyName;
34624 methodDeclaration.questionToken = optionalToken;
34625 if (propertySymbol.valueDeclaration) {
34626 // Copy comments to node for declaration emit
34627 ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration);
34628 }
34629 typeElements.push(methodDeclaration);
34630 }
34631 }
34632 else {
34633 var savedFlags = context.flags;
34634 context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
34635 var propertyTypeNode = void 0;
34636 if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
34637 propertyTypeNode = createElidedInformationPlaceholder(context);
34638 }
34639 else {
34640 propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
34641 }
34642 context.flags = savedFlags;
34643 var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined;
34644 if (modifiers) {
34645 context.approximateLength += 9;
34646 }
34647 var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode,
34648 /*initializer*/ undefined);
34649 if (propertySymbol.valueDeclaration) {
34650 // Copy comments to node for declaration emit
34651 ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration);
34652 }
34653 typeElements.push(propertySignature);
34654 }
34655 }
34656 function mapToTypeNodes(types, context, isBareList) {
34657 if (ts.some(types)) {
34658 if (checkTruncationLength(context)) {
34659 if (!isBareList) {
34660 return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
34661 }
34662 else if (types.length > 2) {
34663 return [
34664 typeToTypeNodeHelper(types[0], context),
34665 ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
34666 typeToTypeNodeHelper(types[types.length - 1], context)
34667 ];
34668 }
34669 }
34670 var result = [];
34671 var i = 0;
34672 for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
34673 var type = types_1[_i];
34674 i++;
34675 if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
34676 result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
34677 var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
34678 if (typeNode_1) {
34679 result.push(typeNode_1);
34680 }
34681 break;
34682 }
34683 context.approximateLength += 2; // Account for whitespace + separator
34684 var typeNode = typeToTypeNodeHelper(type, context);
34685 if (typeNode) {
34686 result.push(typeNode);
34687 }
34688 }
34689 return result;
34690 }
34691 }
34692 function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) {
34693 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
34694 var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 138 /* StringKeyword */ : 135 /* NumberKeyword */);
34695 var indexingParameter = ts.createParameter(
34696 /*decorators*/ undefined,
34697 /*modifiers*/ undefined,
34698 /*dotDotDotToken*/ undefined, name,
34699 /*questionToken*/ undefined, indexerTypeNode,
34700 /*initializer*/ undefined);
34701 var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
34702 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
34703 context.encounteredError = true;
34704 }
34705 context.approximateLength += (name.length + 4);
34706 return ts.createIndexSignature(
34707 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
34708 }
34709 function signatureToSignatureDeclarationHelper(signature, kind, context) {
34710 var typeParameters;
34711 var typeArguments;
34712 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
34713 typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
34714 }
34715 else {
34716 typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
34717 }
34718 var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 157 /* Constructor */); });
34719 if (signature.thisParameter) {
34720 var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
34721 parameters.unshift(thisParameter);
34722 }
34723 var returnTypeNode;
34724 var typePredicate = getTypePredicateOfSignature(signature);
34725 if (typePredicate) {
34726 var parameterName = typePredicate.kind === 1 /* Identifier */ ?
34727 ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
34728 ts.createThisTypeNode();
34729 var typeNode = typeToTypeNodeHelper(typePredicate.type, context);
34730 returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode);
34731 }
34732 else {
34733 var returnType = getReturnTypeOfSignature(signature);
34734 returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context);
34735 }
34736 if (context.flags & 256 /* SuppressAnyReturnType */) {
34737 if (returnTypeNode && returnTypeNode.kind === 120 /* AnyKeyword */) {
34738 returnTypeNode = undefined;
34739 }
34740 }
34741 else if (!returnTypeNode) {
34742 returnTypeNode = ts.createKeywordTypeNode(120 /* AnyKeyword */);
34743 }
34744 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
34745 return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
34746 }
34747 function typeParameterShadowsNameInScope(type, context) {
34748 return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false);
34749 }
34750 function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
34751 var savedContextFlags = context.flags;
34752 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
34753 var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
34754 type.symbol.declarations && type.symbol.declarations[0] &&
34755 ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
34756 typeParameterShadowsNameInScope(type, context);
34757 var name = shouldUseGeneratedName
34758 ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */)
34759 : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true);
34760 var defaultParameter = getDefaultFromTypeParameter(type);
34761 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
34762 context.flags = savedContextFlags;
34763 return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
34764 }
34765 function typeParameterToDeclaration(type, context, constraint) {
34766 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
34767 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
34768 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
34769 }
34770 function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
34771 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
34772 if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
34773 parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
34774 }
34775 var parameterType = getTypeOfSymbol(parameterSymbol);
34776 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
34777 parameterType = getOptionalType(parameterType);
34778 }
34779 var parameterTypeNode = typeToTypeNodeHelper(parameterType, context);
34780 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined;
34781 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* RestParameter */;
34782 var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined;
34783 var name = parameterDeclaration
34784 ? parameterDeclaration.name ?
34785 parameterDeclaration.name.kind === 72 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
34786 parameterDeclaration.name.kind === 148 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
34787 cloneBindingName(parameterDeclaration.name) :
34788 ts.symbolName(parameterSymbol)
34789 : ts.symbolName(parameterSymbol);
34790 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* OptionalParameter */;
34791 var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined;
34792 var parameterNode = ts.createParameter(
34793 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode,
34794 /*initializer*/ undefined);
34795 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
34796 return parameterNode;
34797 function cloneBindingName(node) {
34798 return elideInitializerAndSetEmitFlags(node);
34799 function elideInitializerAndSetEmitFlags(node) {
34800 if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
34801 trackComputedName(node, context.enclosingDeclaration, context);
34802 }
34803 var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
34804 var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited);
34805 if (clone.kind === 186 /* BindingElement */) {
34806 clone.initializer = undefined;
34807 }
34808 return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
34809 }
34810 }
34811 }
34812 function trackComputedName(node, enclosingDeclaration, context) {
34813 if (!context.tracker.trackSymbol)
34814 return;
34815 // get symbol of the first identifier of the entityName
34816 var firstIdentifier = getFirstIdentifier(node.expression);
34817 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
34818 if (name) {
34819 context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */);
34820 }
34821 }
34822 function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
34823 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
34824 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
34825 var chain;
34826 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
34827 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
34828 chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
34829 ts.Debug.assert(chain && chain.length > 0);
34830 }
34831 else {
34832 chain = [symbol];
34833 }
34834 return chain;
34835 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
34836 function getSymbolChain(symbol, meaning, endOfChain) {
34837 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
34838 var parentSpecifiers;
34839 if (!accessibleSymbolChain ||
34840 needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
34841 // Go up and add our parent.
34842 var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
34843 if (ts.length(parents_1)) {
34844 parentSpecifiers = parents_1.map(function (symbol) {
34845 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
34846 ? getSpecifierForModuleSymbol(symbol, context)
34847 : undefined;
34848 });
34849 var indices = parents_1.map(function (_, i) { return i; });
34850 indices.sort(sortByBestName);
34851 var sortedParents = indices.map(function (i) { return parents_1[i]; });
34852 for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
34853 var parent = sortedParents_1[_i];
34854 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
34855 if (parentChain) {
34856 accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
34857 break;
34858 }
34859 }
34860 }
34861 }
34862 if (accessibleSymbolChain) {
34863 return accessibleSymbolChain;
34864 }
34865 if (
34866 // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
34867 endOfChain ||
34868 // If a parent symbol is an anonymous type, don't write it.
34869 !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
34870 // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
34871 if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
34872 return;
34873 }
34874 return [symbol];
34875 }
34876 function sortByBestName(a, b) {
34877 var specifierA = parentSpecifiers[a];
34878 var specifierB = parentSpecifiers[b];
34879 if (specifierA && specifierB) {
34880 var isBRelative = ts.pathIsRelative(specifierB);
34881 if (ts.pathIsRelative(specifierA) === isBRelative) {
34882 // Both relative or both non-relative, sort by number of parts
34883 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
34884 }
34885 if (isBRelative) {
34886 // A is non-relative, B is relative: prefer A
34887 return -1;
34888 }
34889 // A is relative, B is non-relative: prefer B
34890 return 1;
34891 }
34892 return 0;
34893 }
34894 }
34895 }
34896 function typeParametersToTypeParameterDeclarations(symbol, context) {
34897 var typeParameterNodes;
34898 var targetSymbol = getTargetSymbol(symbol);
34899 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
34900 typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
34901 }
34902 return typeParameterNodes;
34903 }
34904 function lookupTypeParameterNodes(chain, index, context) {
34905 ts.Debug.assert(chain && 0 <= index && index < chain.length);
34906 var symbol = chain[index];
34907 var typeParameterNodes;
34908 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
34909 var parentSymbol = symbol;
34910 var nextSymbol = chain[index + 1];
34911 if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) {
34912 var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
34913 typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context);
34914 }
34915 else {
34916 typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
34917 }
34918 }
34919 return typeParameterNodes;
34920 }
34921 /**
34922 * Given A[B][C][D], finds A[B]
34923 */
34924 function getTopmostIndexedAccessType(top) {
34925 if (ts.isIndexedAccessTypeNode(top.objectType)) {
34926 return getTopmostIndexedAccessType(top.objectType);
34927 }
34928 return top;
34929 }
34930 function getSpecifierForModuleSymbol(symbol, context) {
34931 var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
34932 if (file && file.moduleName !== undefined) {
34933 // Use the amd name if it is available
34934 return file.moduleName;
34935 }
34936 if (!file) {
34937 if (context.tracker.trackReferencedAmbientModule) {
34938 var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
34939 if (ts.length(ambientDecls)) {
34940 for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
34941 var decl = ambientDecls_1[_i];
34942 context.tracker.trackReferencedAmbientModule(decl, symbol);
34943 }
34944 }
34945 }
34946 if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
34947 return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
34948 }
34949 }
34950 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
34951 // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
34952 if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
34953 return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
34954 }
34955 return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full
34956 }
34957 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
34958 var links = getSymbolLinks(symbol);
34959 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
34960 if (!specifier) {
34961 var isBundle_1 = (compilerOptions.out || compilerOptions.outFile);
34962 // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
34963 // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
34964 // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
34965 // specifier preference
34966 var moduleResolverHost = context.tracker.moduleResolverHost;
34967 var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
34968 specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap));
34969 links.specifierCache = links.specifierCache || ts.createMap();
34970 links.specifierCache.set(contextFile.path, specifier);
34971 }
34972 return specifier;
34973 }
34974 function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
34975 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
34976 var isTypeOf = meaning === 67220415 /* Value */;
34977 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
34978 // module is root, must use `ImportTypeNode`
34979 var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
34980 var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
34981 var specifier = getSpecifierForModuleSymbol(chain[0], context);
34982 if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
34983 // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
34984 // since declaration files with these kinds of references are liable to fail when published :(
34985 context.encounteredError = true;
34986 if (context.tracker.reportLikelyUnsafeImportRequiredError) {
34987 context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
34988 }
34989 }
34990 var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
34991 if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
34992 context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
34993 context.approximateLength += specifier.length + 10; // specifier + import("")
34994 if (!nonRootParts || ts.isEntityName(nonRootParts)) {
34995 if (nonRootParts) {
34996 var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
34997 lastId.typeArguments = undefined;
34998 }
34999 return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
35000 }
35001 else {
35002 var splitNode = getTopmostIndexedAccessType(nonRootParts);
35003 var qualifier = splitNode.objectType.typeName;
35004 return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
35005 }
35006 }
35007 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
35008 if (ts.isIndexedAccessTypeNode(entityName)) {
35009 return entityName; // Indexed accesses can never be `typeof`
35010 }
35011 if (isTypeOf) {
35012 return ts.createTypeQueryNode(entityName);
35013 }
35014 else {
35015 var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
35016 var lastTypeArgs = lastId.typeArguments;
35017 lastId.typeArguments = undefined;
35018 return ts.createTypeReferenceNode(entityName, lastTypeArgs);
35019 }
35020 function createAccessFromSymbolChain(chain, index, stopper) {
35021 var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
35022 var symbol = chain[index];
35023 if (index === 0) {
35024 context.flags |= 16777216 /* InInitialEntityName */;
35025 }
35026 var symbolName = getNameOfSymbolAsWritten(symbol, context);
35027 context.approximateLength += symbolName.length + 1;
35028 if (index === 0) {
35029 context.flags ^= 16777216 /* InInitialEntityName */;
35030 }
35031 var parent = chain[index - 1];
35032 if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) {
35033 // Should use an indexed access
35034 var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
35035 if (ts.isIndexedAccessTypeNode(LHS)) {
35036 return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
35037 }
35038 else {
35039 return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
35040 }
35041 }
35042 var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
35043 identifier.symbol = symbol;
35044 if (index > stopper) {
35045 var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
35046 if (!ts.isEntityName(LHS)) {
35047 return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
35048 }
35049 return ts.createQualifiedName(LHS, identifier);
35050 }
35051 return identifier;
35052 }
35053 }
35054 function symbolToName(symbol, context, meaning, expectsIdentifier) {
35055 var chain = lookupSymbolChain(symbol, context, meaning);
35056 if (expectsIdentifier && chain.length !== 1
35057 && !context.encounteredError
35058 && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
35059 context.encounteredError = true;
35060 }
35061 return createEntityNameFromSymbolChain(chain, chain.length - 1);
35062 function createEntityNameFromSymbolChain(chain, index) {
35063 var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
35064 var symbol = chain[index];
35065 if (index === 0) {
35066 context.flags |= 16777216 /* InInitialEntityName */;
35067 }
35068 var symbolName = getNameOfSymbolAsWritten(symbol, context);
35069 if (index === 0) {
35070 context.flags ^= 16777216 /* InInitialEntityName */;
35071 }
35072 var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
35073 identifier.symbol = symbol;
35074 return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
35075 }
35076 }
35077 function symbolToExpression(symbol, context, meaning) {
35078 var chain = lookupSymbolChain(symbol, context, meaning);
35079 return createExpressionFromSymbolChain(chain, chain.length - 1);
35080 function createExpressionFromSymbolChain(chain, index) {
35081 var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
35082 var symbol = chain[index];
35083 if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
35084 return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context));
35085 }
35086 if (index === 0) {
35087 context.flags |= 16777216 /* InInitialEntityName */;
35088 }
35089 var symbolName = getNameOfSymbolAsWritten(symbol, context);
35090 if (index === 0) {
35091 context.flags ^= 16777216 /* InInitialEntityName */;
35092 }
35093 var firstChar = symbolName.charCodeAt(0);
35094 var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion);
35095 if (index === 0 || canUsePropertyAccess) {
35096 var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
35097 identifier.symbol = symbol;
35098 return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
35099 }
35100 else {
35101 if (firstChar === 91 /* openBracket */) {
35102 symbolName = symbolName.substring(1, symbolName.length - 1);
35103 firstChar = symbolName.charCodeAt(0);
35104 }
35105 var expression = void 0;
35106 if (ts.isSingleOrDoubleQuote(firstChar)) {
35107 expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); }));
35108 expression.singleQuote = firstChar === 39 /* singleQuote */;
35109 }
35110 else if (("" + +symbolName) === symbolName) {
35111 expression = ts.createLiteral(+symbolName);
35112 }
35113 if (!expression) {
35114 expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
35115 expression.symbol = symbol;
35116 }
35117 return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression);
35118 }
35119 }
35120 }
35121 }
35122 function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
35123 if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
35124 return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
35125 function typePredicateToStringWorker(writer) {
35126 var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
35127 var printer = ts.createPrinter({ removeComments: true });
35128 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
35129 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
35130 return writer;
35131 }
35132 }
35133 function formatUnionTypes(types) {
35134 var result = [];
35135 var flags = 0;
35136 for (var i = 0; i < types.length; i++) {
35137 var t = types[i];
35138 flags |= t.flags;
35139 if (!(t.flags & 98304 /* Nullable */)) {
35140 if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
35141 var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
35142 if (baseType.flags & 1048576 /* Union */) {
35143 var count = baseType.types.length;
35144 if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
35145 result.push(baseType);
35146 i += count - 1;
35147 continue;
35148 }
35149 }
35150 }
35151 result.push(t);
35152 }
35153 }
35154 if (flags & 65536 /* Null */)
35155 result.push(nullType);
35156 if (flags & 32768 /* Undefined */)
35157 result.push(undefinedType);
35158 return result || types;
35159 }
35160 function visibilityToString(flags) {
35161 if (flags === 8 /* Private */) {
35162 return "private";
35163 }
35164 if (flags === 16 /* Protected */) {
35165 return "protected";
35166 }
35167 return "public";
35168 }
35169 function getTypeAliasForTypeLiteral(type) {
35170 if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
35171 var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 177 /* ParenthesizedType */; });
35172 if (node.kind === 242 /* TypeAliasDeclaration */) {
35173 return getSymbolOfNode(node);
35174 }
35175 }
35176 return undefined;
35177 }
35178 function isTopLevelInExternalModuleAugmentation(node) {
35179 return node && node.parent &&
35180 node.parent.kind === 245 /* ModuleBlock */ &&
35181 ts.isExternalModuleAugmentation(node.parent.parent);
35182 }
35183 function isDefaultBindingContext(location) {
35184 return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
35185 }
35186 function getNameOfSymbolFromNameType(symbol, context) {
35187 var nameType = symbol.nameType;
35188 if (nameType) {
35189 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
35190 var name = "" + nameType.value;
35191 if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
35192 return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
35193 }
35194 return name;
35195 }
35196 if (nameType.flags & 8192 /* UniqueESSymbol */) {
35197 return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
35198 }
35199 }
35200 }
35201 /**
35202 * Gets a human-readable name for a symbol.
35203 * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
35204 *
35205 * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
35206 * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
35207 */
35208 function getNameOfSymbolAsWritten(symbol, context) {
35209 if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
35210 // If it's not the first part of an entity name, it must print as `default`
35211 (!(context.flags & 16777216 /* InInitialEntityName */) ||
35212 // if the symbol is synthesized, it will only be referenced externally it must print as `default`
35213 !symbol.declarations ||
35214 // if not in the same binding context (source file, module declaration), it must print as `default`
35215 (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
35216 return "default";
35217 }
35218 if (symbol.declarations && symbol.declarations.length) {
35219 var declaration = symbol.declarations[0];
35220 var name_2 = ts.getNameOfDeclaration(declaration);
35221 if (name_2) {
35222 if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
35223 return ts.symbolName(symbol);
35224 }
35225 if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 2048 /* Late */) && symbol.nameType && symbol.nameType.flags & 384 /* StringOrNumberLiteral */) {
35226 // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
35227 var result = getNameOfSymbolFromNameType(symbol, context);
35228 if (result !== undefined) {
35229 return result;
35230 }
35231 }
35232 return ts.declarationNameToString(name_2);
35233 }
35234 if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) {
35235 return ts.declarationNameToString(declaration.parent.name);
35236 }
35237 switch (declaration.kind) {
35238 case 209 /* ClassExpression */:
35239 case 196 /* FunctionExpression */:
35240 case 197 /* ArrowFunction */:
35241 if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
35242 context.encounteredError = true;
35243 }
35244 return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
35245 }
35246 }
35247 var name = getNameOfSymbolFromNameType(symbol, context);
35248 return name !== undefined ? name : ts.symbolName(symbol);
35249 }
35250 function isDeclarationVisible(node) {
35251 if (node) {
35252 var links = getNodeLinks(node);
35253 if (links.isVisible === undefined) {
35254 links.isVisible = !!determineIfDeclarationIsVisible();
35255 }
35256 return links.isVisible;
35257 }
35258 return false;
35259 function determineIfDeclarationIsVisible() {
35260 switch (node.kind) {
35261 case 302 /* JSDocCallbackTag */:
35262 case 309 /* JSDocTypedefTag */:
35263 // Top-level jsdoc type aliases are considered exported
35264 // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
35265 return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
35266 case 186 /* BindingElement */:
35267 return isDeclarationVisible(node.parent.parent);
35268 case 237 /* VariableDeclaration */:
35269 if (ts.isBindingPattern(node.name) &&
35270 !node.name.elements.length) {
35271 // If the binding pattern is empty, this variable declaration is not visible
35272 return false;
35273 }
35274 // falls through
35275 case 244 /* ModuleDeclaration */:
35276 case 240 /* ClassDeclaration */:
35277 case 241 /* InterfaceDeclaration */:
35278 case 242 /* TypeAliasDeclaration */:
35279 case 239 /* FunctionDeclaration */:
35280 case 243 /* EnumDeclaration */:
35281 case 248 /* ImportEqualsDeclaration */:
35282 // external module augmentation is always visible
35283 if (ts.isExternalModuleAugmentation(node)) {
35284 return true;
35285 }
35286 var parent = getDeclarationContainer(node);
35287 // If the node is not exported or it is not ambient module element (except import declaration)
35288 if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
35289 !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
35290 return isGlobalSourceFile(parent);
35291 }
35292 // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
35293 return isDeclarationVisible(parent);
35294 case 154 /* PropertyDeclaration */:
35295 case 153 /* PropertySignature */:
35296 case 158 /* GetAccessor */:
35297 case 159 /* SetAccessor */:
35298 case 156 /* MethodDeclaration */:
35299 case 155 /* MethodSignature */:
35300 if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) {
35301 // Private/protected properties/methods are not visible
35302 return false;
35303 }
35304 // Public properties/methods are visible if its parents are visible, so:
35305 // falls through
35306 case 157 /* Constructor */:
35307 case 161 /* ConstructSignature */:
35308 case 160 /* CallSignature */:
35309 case 162 /* IndexSignature */:
35310 case 151 /* Parameter */:
35311 case 245 /* ModuleBlock */:
35312 case 165 /* FunctionType */:
35313 case 166 /* ConstructorType */:
35314 case 168 /* TypeLiteral */:
35315 case 164 /* TypeReference */:
35316 case 169 /* ArrayType */:
35317 case 170 /* TupleType */:
35318 case 173 /* UnionType */:
35319 case 174 /* IntersectionType */:
35320 case 177 /* ParenthesizedType */:
35321 return isDeclarationVisible(node.parent);
35322 // Default binding, import specifier and namespace import is visible
35323 // only on demand so by default it is not visible
35324 case 250 /* ImportClause */:
35325 case 251 /* NamespaceImport */:
35326 case 253 /* ImportSpecifier */:
35327 return false;
35328 // Type parameters are always visible
35329 case 150 /* TypeParameter */:
35330 // Source file and namespace export are always visible
35331 case 284 /* SourceFile */:
35332 case 247 /* NamespaceExportDeclaration */:
35333 return true;
35334 // Export assignments do not create name bindings outside the module
35335 case 254 /* ExportAssignment */:
35336 return false;
35337 default:
35338 return false;
35339 }
35340 }
35341 }
35342 function collectLinkedAliases(node, setVisibility) {
35343 var exportSymbol;
35344 if (node.parent && node.parent.kind === 254 /* ExportAssignment */) {
35345 exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
35346 }
35347 else if (node.parent.kind === 257 /* ExportSpecifier */) {
35348 exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
35349 }
35350 var result;
35351 if (exportSymbol) {
35352 buildVisibleNodeList(exportSymbol.declarations);
35353 }
35354 return result;
35355 function buildVisibleNodeList(declarations) {
35356 ts.forEach(declarations, function (declaration) {
35357 var resultNode = getAnyImportSyntax(declaration) || declaration;
35358 if (setVisibility) {
35359 getNodeLinks(declaration).isVisible = true;
35360 }
35361 else {
35362 result = result || [];
35363 ts.pushIfUnique(result, resultNode);
35364 }
35365 if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
35366 // Add the referenced top container visible
35367 var internalModuleReference = declaration.moduleReference;
35368 var firstIdentifier = getFirstIdentifier(internalModuleReference);
35369 var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
35370 if (importSymbol) {
35371 buildVisibleNodeList(importSymbol.declarations);
35372 }
35373 }
35374 });
35375 }
35376 }
35377 /**
35378 * Push an entry on the type resolution stack. If an entry with the given target and the given property name
35379 * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
35380 * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
35381 * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
35382 * In order to see if the same query has already been done before, the target object and the propertyName both
35383 * must match the one passed in.
35384 *
35385 * @param target The symbol, type, or signature whose type is being queried
35386 * @param propertyName The property name that should be used to query the target for its type
35387 */
35388 function pushTypeResolution(target, propertyName) {
35389 var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
35390 if (resolutionCycleStartIndex >= 0) {
35391 // A cycle was found
35392 var length_2 = resolutionTargets.length;
35393 for (var i = resolutionCycleStartIndex; i < length_2; i++) {
35394 resolutionResults[i] = false;
35395 }
35396 return false;
35397 }
35398 resolutionTargets.push(target);
35399 resolutionResults.push(/*items*/ true);
35400 resolutionPropertyNames.push(propertyName);
35401 return true;
35402 }
35403 function findResolutionCycleStartIndex(target, propertyName) {
35404 for (var i = resolutionTargets.length - 1; i >= 0; i--) {
35405 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
35406 return -1;
35407 }
35408 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
35409 return i;
35410 }
35411 }
35412 return -1;
35413 }
35414 function hasType(target, propertyName) {
35415 switch (propertyName) {
35416 case 0 /* Type */:
35417 return !!getSymbolLinks(target).type;
35418 case 5 /* EnumTagType */:
35419 return !!(getNodeLinks(target).resolvedEnumType);
35420 case 2 /* DeclaredType */:
35421 return !!getSymbolLinks(target).declaredType;
35422 case 1 /* ResolvedBaseConstructorType */:
35423 return !!target.resolvedBaseConstructorType;
35424 case 3 /* ResolvedReturnType */:
35425 return !!target.resolvedReturnType;
35426 case 4 /* ImmediateBaseConstraint */:
35427 return !!target.immediateBaseConstraint;
35428 case 6 /* JSDocTypeReference */:
35429 return !!getSymbolLinks(target).resolvedJSDocType;
35430 }
35431 return ts.Debug.assertNever(propertyName);
35432 }
35433 // Pop an entry from the type resolution stack and return its associated result value. The result value will
35434 // be true if no circularities were detected, or false if a circularity was found.
35435 function popTypeResolution() {
35436 resolutionTargets.pop();
35437 resolutionPropertyNames.pop();
35438 return resolutionResults.pop();
35439 }
35440 function getDeclarationContainer(node) {
35441 return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
35442 switch (node.kind) {
35443 case 237 /* VariableDeclaration */:
35444 case 238 /* VariableDeclarationList */:
35445 case 253 /* ImportSpecifier */:
35446 case 252 /* NamedImports */:
35447 case 251 /* NamespaceImport */:
35448 case 250 /* ImportClause */:
35449 return false;
35450 default:
35451 return true;
35452 }
35453 }).parent;
35454 }
35455 function getTypeOfPrototypeProperty(prototype) {
35456 // TypeScript 1.0 spec (April 2014): 8.4
35457 // Every class automatically contains a static property member named 'prototype',
35458 // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
35459 // It is an error to explicitly declare a static property member with the name 'prototype'.
35460 var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
35461 return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
35462 }
35463 // Return the type of the given property in the given type, or undefined if no such property exists
35464 function getTypeOfPropertyOfType(type, name) {
35465 var prop = getPropertyOfType(type, name);
35466 return prop ? getTypeOfSymbol(prop) : undefined;
35467 }
35468 function getTypeOfPropertyOrIndexSignature(type, name) {
35469 return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
35470 }
35471 function isTypeAny(type) {
35472 return type && (type.flags & 1 /* Any */) !== 0;
35473 }
35474 // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
35475 // assigned by contextual typing.
35476 function getTypeForBindingElementParent(node) {
35477 var symbol = getSymbolOfNode(node);
35478 return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
35479 }
35480 function isComputedNonLiteralName(name) {
35481 return name.kind === 149 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression);
35482 }
35483 function getRestType(source, properties, symbol) {
35484 source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
35485 if (source.flags & 131072 /* Never */) {
35486 return emptyObjectType;
35487 }
35488 if (source.flags & 1048576 /* Union */) {
35489 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
35490 }
35491 var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
35492 if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
35493 if (omitKeyType.flags & 131072 /* Never */) {
35494 return source;
35495 }
35496 var pickTypeAlias = getGlobalPickSymbol();
35497 var excludeTypeAlias = getGlobalExcludeSymbol();
35498 if (!pickTypeAlias || !excludeTypeAlias) {
35499 return errorType;
35500 }
35501 var pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]);
35502 return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]);
35503 }
35504 var members = ts.createSymbolTable();
35505 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
35506 var prop = _a[_i];
35507 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
35508 && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
35509 && isSpreadableProperty(prop)) {
35510 members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
35511 }
35512 }
35513 var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
35514 var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
35515 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
35516 }
35517 // Determine the control flow type associated with a destructuring declaration or assignment. The following
35518 // forms of destructuring are possible:
35519 // let { x } = obj; // BindingElement
35520 // let [ x ] = obj; // BindingElement
35521 // { x } = obj; // ShorthandPropertyAssignment
35522 // { x: v } = obj; // PropertyAssignment
35523 // [ x ] = obj; // Expression
35524 // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
35525 // flow analyzer doesn't have to handle all the different syntactic forms.
35526 function getFlowTypeOfDestructuring(node, declaredType) {
35527 var reference = getSyntheticElementAccess(node);
35528 return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
35529 }
35530 function getSyntheticElementAccess(node) {
35531 var parentAccess = getParentElementAccess(node);
35532 if (parentAccess && parentAccess.flowNode) {
35533 var propName = getDestructuringPropertyName(node);
35534 if (propName) {
35535 var result = ts.createNode(190 /* ElementAccessExpression */, node.pos, node.end);
35536 result.parent = node;
35537 result.expression = parentAccess;
35538 var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end);
35539 literal.parent = result;
35540 literal.text = propName;
35541 result.argumentExpression = literal;
35542 result.flowNode = parentAccess.flowNode;
35543 return result;
35544 }
35545 }
35546 }
35547 function getParentElementAccess(node) {
35548 var ancestor = node.parent.parent;
35549 switch (ancestor.kind) {
35550 case 186 /* BindingElement */:
35551 case 275 /* PropertyAssignment */:
35552 return getSyntheticElementAccess(ancestor);
35553 case 187 /* ArrayLiteralExpression */:
35554 return getSyntheticElementAccess(node.parent);
35555 case 237 /* VariableDeclaration */:
35556 return ancestor.initializer;
35557 case 204 /* BinaryExpression */:
35558 return ancestor.right;
35559 }
35560 }
35561 function getDestructuringPropertyName(node) {
35562 var parent = node.parent;
35563 if (node.kind === 186 /* BindingElement */ && parent.kind === 184 /* ObjectBindingPattern */) {
35564 return getLiteralPropertyNameText(node.propertyName || node.name);
35565 }
35566 if (node.kind === 275 /* PropertyAssignment */ || node.kind === 276 /* ShorthandPropertyAssignment */) {
35567 return getLiteralPropertyNameText(node.name);
35568 }
35569 return "" + parent.elements.indexOf(node);
35570 }
35571 function getLiteralPropertyNameText(name) {
35572 var type = getLiteralTypeFromPropertyName(name);
35573 return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
35574 }
35575 /** Return the inferred type for a binding element */
35576 function getTypeForBindingElement(declaration) {
35577 var pattern = declaration.parent;
35578 var parentType = getTypeForBindingElementParent(pattern.parent);
35579 // If no type or an any type was inferred for parent, infer that for the binding element
35580 if (!parentType || isTypeAny(parentType)) {
35581 return parentType;
35582 }
35583 // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
35584 if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
35585 parentType = getNonNullableType(parentType);
35586 }
35587 var type;
35588 if (pattern.kind === 184 /* ObjectBindingPattern */) {
35589 if (declaration.dotDotDotToken) {
35590 if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
35591 error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
35592 return errorType;
35593 }
35594 var literalMembers = [];
35595 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
35596 var element = _a[_i];
35597 if (!element.dotDotDotToken) {
35598 literalMembers.push(element.propertyName || element.name);
35599 }
35600 }
35601 type = getRestType(parentType, literalMembers, declaration.symbol);
35602 }
35603 else {
35604 // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
35605 var name = declaration.propertyName || declaration.name;
35606 var indexType = getLiteralTypeFromPropertyName(name);
35607 var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name);
35608 type = getFlowTypeOfDestructuring(declaration, declaredType);
35609 }
35610 }
35611 else {
35612 // This elementType will be used if the specific property corresponding to this index is not
35613 // present (aka the tuple element property). This call also checks that the parentType is in
35614 // fact an iterable or array (depending on target language).
35615 var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false);
35616 var index_1 = pattern.elements.indexOf(declaration);
35617 if (declaration.dotDotDotToken) {
35618 // If the parent is a tuple type, the rest element has a tuple type of the
35619 // remaining tuple element types. Otherwise, the rest element has an array type with same
35620 // element type as the parent type.
35621 type = everyType(parentType, isTupleType) ?
35622 mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) :
35623 createArrayType(elementType);
35624 }
35625 else if (isArrayLikeType(parentType)) {
35626 var indexType = getLiteralType(index_1);
35627 var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, declaration.name), declaration.name);
35628 type = getFlowTypeOfDestructuring(declaration, declaredType);
35629 }
35630 else {
35631 type = elementType;
35632 }
35633 }
35634 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
35635 // undefined from the final type.
35636 if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */)) {
35637 type = getTypeWithFacts(type, 524288 /* NEUndefined */);
35638 }
35639 return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ?
35640 getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) :
35641 type;
35642 }
35643 function getTypeForDeclarationFromJSDocComment(declaration) {
35644 var jsdocType = ts.getJSDocType(declaration);
35645 if (jsdocType) {
35646 return getTypeFromTypeNode(jsdocType);
35647 }
35648 return undefined;
35649 }
35650 function isNullOrUndefined(node) {
35651 var expr = ts.skipParentheses(node);
35652 return expr.kind === 96 /* NullKeyword */ || expr.kind === 72 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
35653 }
35654 function isEmptyArrayLiteral(node) {
35655 var expr = ts.skipParentheses(node);
35656 return expr.kind === 187 /* ArrayLiteralExpression */ && expr.elements.length === 0;
35657 }
35658 function addOptionality(type, optional) {
35659 if (optional === void 0) { optional = true; }
35660 return strictNullChecks && optional ? getOptionalType(type) : type;
35661 }
35662 function isParameterOfContextuallyTypedFunction(node) {
35663 return node.kind === 151 /* Parameter */ &&
35664 (node.parent.kind === 196 /* FunctionExpression */ || node.parent.kind === 197 /* ArrowFunction */) &&
35665 !!getContextualType(node.parent);
35666 }
35667 // Return the inferred type for a variable, parameter, or property declaration
35668 function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
35669 // A variable declared in a for..in statement is of type string, or of type keyof T when the
35670 // right hand expression is of a type parameter type.
35671 if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226 /* ForInStatement */) {
35672 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
35673 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
35674 }
35675 if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 227 /* ForOfStatement */) {
35676 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
35677 // missing properties/signatures required to get its iteratedType (like
35678 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
35679 // or it may have led to an error inside getElementTypeOfIterable.
35680 var forOfStatement = declaration.parent.parent;
35681 return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType;
35682 }
35683 if (ts.isBindingPattern(declaration.parent)) {
35684 return getTypeForBindingElement(declaration);
35685 }
35686 var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
35687 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
35688 // Use type from type annotation if one is present
35689 var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
35690 if (declaredType) {
35691 return addOptionality(declaredType, isOptional);
35692 }
35693 if ((noImplicitAny || ts.isInJSFile(declaration)) &&
35694 declaration.kind === 237 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
35695 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) {
35696 // If --noImplicitAny is on or the declaration is in a Javascript file,
35697 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
35698 // initializer or a 'null' or 'undefined' initializer.
35699 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
35700 return autoType;
35701 }
35702 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
35703 // literal initializer.
35704 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
35705 return autoArrayType;
35706 }
35707 }
35708 if (declaration.kind === 151 /* Parameter */) {
35709 var func = declaration.parent;
35710 // For a parameter of a set accessor, use the type of the get accessor if one is present
35711 if (func.kind === 159 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
35712 var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 158 /* GetAccessor */);
35713 if (getter) {
35714 var getterSignature = getSignatureFromDeclaration(getter);
35715 var thisParameter = getAccessorThisParameter(func);
35716 if (thisParameter && declaration === thisParameter) {
35717 // Use the type from the *getter*
35718 ts.Debug.assert(!thisParameter.type);
35719 return getTypeOfSymbol(getterSignature.thisParameter);
35720 }
35721 return getReturnTypeOfSignature(getterSignature);
35722 }
35723 }
35724 if (ts.isInJSFile(declaration)) {
35725 var typeTag = ts.getJSDocType(func);
35726 if (typeTag && ts.isFunctionTypeNode(typeTag)) {
35727 return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration));
35728 }
35729 }
35730 // Use contextual parameter type if one is available
35731 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
35732 if (type) {
35733 return addOptionality(type, isOptional);
35734 }
35735 }
35736 else if (ts.isInJSFile(declaration)) {
35737 var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
35738 if (containerObjectType) {
35739 return containerObjectType;
35740 }
35741 }
35742 // Use the type of the initializer expression if one is present and the declaration is
35743 // not a parameter of a contextually typed function
35744 if (declaration.initializer && !isParameterOfContextuallyTypedFunction(declaration)) {
35745 var type = checkDeclarationInitializer(declaration);
35746 return addOptionality(type, isOptional);
35747 }
35748 if (ts.isJsxAttribute(declaration)) {
35749 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
35750 // I.e <Elem attr /> is sugar for <Elem attr={true} />
35751 return trueType;
35752 }
35753 // If the declaration specifies a binding pattern and is not a parameter of a contextually
35754 // typed function, use the type implied by the binding pattern
35755 if (ts.isBindingPattern(declaration.name) && !isParameterOfContextuallyTypedFunction(declaration)) {
35756 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
35757 }
35758 // No type specified and nothing can be inferred
35759 return undefined;
35760 }
35761 function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) {
35762 // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
35763 var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
35764 if (container) {
35765 var tag = ts.getJSDocTypeTag(container);
35766 if (tag && tag.typeExpression) {
35767 return getTypeFromTypeNode(tag.typeExpression);
35768 }
35769 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
35770 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
35771 }
35772 var definedInConstructor = false;
35773 var definedInMethod = false;
35774 var jsdocType;
35775 var types;
35776 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
35777 var declaration = _a[_i];
35778 var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
35779 ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
35780 undefined;
35781 if (!expression) {
35782 return errorType;
35783 }
35784 var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression);
35785 if (kind === 4 /* ThisProperty */) {
35786 if (isDeclarationInConstructor(expression)) {
35787 definedInConstructor = true;
35788 }
35789 else {
35790 definedInMethod = true;
35791 }
35792 }
35793 if (!ts.isCallExpression(expression)) {
35794 jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration);
35795 }
35796 if (!jsdocType) {
35797 (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
35798 }
35799 }
35800 var type = jsdocType;
35801 if (!type) {
35802 var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
35803 // use only the constructor types unless they were only assigned null | undefined (including widening variants)
35804 if (definedInMethod) {
35805 var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol);
35806 if (propType) {
35807 (constructorTypes || (constructorTypes = [])).push(propType);
35808 definedInConstructor = true;
35809 }
35810 }
35811 var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
35812 type = getUnionType(sourceTypes, 2 /* Subtype */);
35813 }
35814 var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
35815 if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
35816 reportImplicitAny(symbol.valueDeclaration, anyType);
35817 return anyType;
35818 }
35819 return widened;
35820 }
35821 function getJSContainerObjectType(decl, symbol, init) {
35822 if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
35823 return undefined;
35824 }
35825 var exports = ts.createSymbolTable();
35826 while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
35827 var s_1 = getSymbolOfNode(decl);
35828 if (s_1 && ts.hasEntries(s_1.exports)) {
35829 mergeSymbolTable(exports, s_1.exports);
35830 }
35831 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
35832 }
35833 var s = getSymbolOfNode(decl);
35834 if (s && ts.hasEntries(s.exports)) {
35835 mergeSymbolTable(exports, s.exports);
35836 }
35837 var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
35838 type.objectFlags |= 16384 /* JSLiteral */;
35839 return type;
35840 }
35841 function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) {
35842 var typeNode = ts.getJSDocType(expression.parent);
35843 if (typeNode) {
35844 var type = getWidenedType(getTypeFromTypeNode(typeNode));
35845 if (!declaredType) {
35846 return type;
35847 }
35848 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
35849 errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type);
35850 }
35851 }
35852 return declaredType;
35853 }
35854 /** If we don't have an explicit JSDoc type, get the type from the initializer. */
35855 function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
35856 if (ts.isCallExpression(expression)) {
35857 if (resolvedSymbol) {
35858 return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
35859 }
35860 var objectLitType = checkExpressionCached(expression.arguments[2]);
35861 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
35862 if (valueType) {
35863 return valueType;
35864 }
35865 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
35866 if (getFunc) {
35867 var getSig = getSingleCallSignature(getFunc);
35868 if (getSig) {
35869 return getReturnTypeOfSignature(getSig);
35870 }
35871 }
35872 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
35873 if (setFunc) {
35874 var setSig = getSingleCallSignature(setFunc);
35875 if (setSig) {
35876 return getTypeOfFirstParameterOfSignature(setSig);
35877 }
35878 }
35879 return anyType;
35880 }
35881 var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
35882 if (type.flags & 524288 /* Object */ &&
35883 kind === 2 /* ModuleExports */ &&
35884 symbol.escapedName === "export=" /* ExportEquals */) {
35885 var exportedType_1 = resolveStructuredTypeMembers(type);
35886 var members_3 = ts.createSymbolTable();
35887 ts.copyEntries(exportedType_1.members, members_3);
35888 if (resolvedSymbol && !resolvedSymbol.exports) {
35889 resolvedSymbol.exports = ts.createSymbolTable();
35890 }
35891 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
35892 if (members_3.has(name)) {
35893 var exportedMember = exportedType_1.members.get(name);
35894 var union = createSymbol(s.flags | exportedMember.flags, name);
35895 union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
35896 members_3.set(name, union);
35897 }
35898 else {
35899 members_3.set(name, s);
35900 }
35901 });
35902 var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo);
35903 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
35904 return result;
35905 }
35906 if (isEmptyArrayLiteralType(type)) {
35907 reportImplicitAny(expression, anyArrayType);
35908 return anyArrayType;
35909 }
35910 return type;
35911 }
35912 function isDeclarationInConstructor(expression) {
35913 var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
35914 // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
35915 // Function expressions that are assigned to the prototype count as methods.
35916 return thisContainer.kind === 157 /* Constructor */ ||
35917 thisContainer.kind === 239 /* FunctionDeclaration */ ||
35918 (thisContainer.kind === 196 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
35919 }
35920 function getConstructorDefinedThisAssignmentTypes(types, declarations) {
35921 ts.Debug.assert(types.length === declarations.length);
35922 return types.filter(function (_, i) {
35923 var declaration = declarations[i];
35924 var expression = ts.isBinaryExpression(declaration) ? declaration :
35925 ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
35926 return expression && isDeclarationInConstructor(expression);
35927 });
35928 }
35929 /** check for definition in base class if any declaration is in a class */
35930 function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) {
35931 var parentDeclaration = ts.forEach(property.declarations, function (d) {
35932 var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent;
35933 return ts.isClassLike(parent) && parent;
35934 });
35935 if (parentDeclaration) {
35936 var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration));
35937 var baseClassType = classType && getBaseTypes(classType)[0];
35938 if (baseClassType) {
35939 return getTypeOfPropertyOfType(baseClassType, property.escapedName);
35940 }
35941 }
35942 }
35943 // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
35944 // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
35945 // pattern. Otherwise, it is the type any.
35946 function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
35947 if (element.initializer) {
35948 return addOptionality(checkDeclarationInitializer(element));
35949 }
35950 if (ts.isBindingPattern(element.name)) {
35951 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
35952 }
35953 if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
35954 reportImplicitAny(element, anyType);
35955 }
35956 return anyType;
35957 }
35958 // Return the type implied by an object binding pattern
35959 function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
35960 var members = ts.createSymbolTable();
35961 var stringIndexInfo;
35962 var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
35963 ts.forEach(pattern.elements, function (e) {
35964 var name = e.propertyName || e.name;
35965 if (e.dotDotDotToken) {
35966 stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
35967 return;
35968 }
35969 var exprType = getLiteralTypeFromPropertyName(name);
35970 if (!isTypeUsableAsPropertyName(exprType)) {
35971 // do not include computed properties in the implied type
35972 objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
35973 return;
35974 }
35975 var text = getPropertyNameFromType(exprType);
35976 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
35977 var symbol = createSymbol(flags, text);
35978 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
35979 symbol.bindingElement = e;
35980 members.set(symbol.escapedName, symbol);
35981 });
35982 var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
35983 result.objectFlags |= objectFlags;
35984 if (includePatternInType) {
35985 result.pattern = pattern;
35986 }
35987 return result;
35988 }
35989 // Return the type implied by an array binding pattern
35990 function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
35991 var elements = pattern.elements;
35992 var lastElement = ts.lastOrUndefined(elements);
35993 var hasRestElement = !!(lastElement && lastElement.kind === 186 /* BindingElement */ && lastElement.dotDotDotToken);
35994 if (elements.length === 0 || elements.length === 1 && hasRestElement) {
35995 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
35996 }
35997 var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
35998 var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1;
35999 var result = createTupleType(elementTypes, minLength, hasRestElement);
36000 if (includePatternInType) {
36001 result = cloneTypeReference(result);
36002 result.pattern = pattern;
36003 }
36004 return result;
36005 }
36006 // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
36007 // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
36008 // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
36009 // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
36010 // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
36011 // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
36012 // the parameter.
36013 function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
36014 if (includePatternInType === void 0) { includePatternInType = false; }
36015 if (reportErrors === void 0) { reportErrors = false; }
36016 return pattern.kind === 184 /* ObjectBindingPattern */
36017 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
36018 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
36019 }
36020 // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
36021 // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
36022 // is a bit more involved. For example:
36023 //
36024 // var [x, s = ""] = [1, "one"];
36025 //
36026 // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
36027 // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
36028 // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
36029 function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
36030 return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
36031 }
36032 function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
36033 if (type) {
36034 if (reportErrors) {
36035 reportErrorsFromWidening(declaration, type);
36036 }
36037 // always widen a 'unique symbol' type if the type was created for a different declaration.
36038 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
36039 type = esSymbolType;
36040 }
36041 return getWidenedType(type);
36042 }
36043 // Rest parameters default to type any[], other parameters default to type any
36044 type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
36045 // Report implicit any errors unless this is a private property within an ambient declaration
36046 if (reportErrors) {
36047 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
36048 reportImplicitAny(declaration, type);
36049 }
36050 }
36051 return type;
36052 }
36053 function declarationBelongsToPrivateAmbientMember(declaration) {
36054 var root = ts.getRootDeclaration(declaration);
36055 var memberDeclaration = root.kind === 151 /* Parameter */ ? root.parent : root;
36056 return isPrivateWithinAmbient(memberDeclaration);
36057 }
36058 function tryGetTypeFromEffectiveTypeNode(declaration) {
36059 var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
36060 if (typeNode) {
36061 return getTypeFromTypeNode(typeNode);
36062 }
36063 }
36064 function getTypeOfVariableOrParameterOrProperty(symbol) {
36065 var links = getSymbolLinks(symbol);
36066 if (!links.type) {
36067 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
36068 // For a contextually typed parameter it is possible that a type has already
36069 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
36070 // to preserve this type.
36071 if (!links.type) {
36072 links.type = type;
36073 }
36074 }
36075 return links.type;
36076 }
36077 function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
36078 // Handle prototype property
36079 if (symbol.flags & 4194304 /* Prototype */) {
36080 return getTypeOfPrototypeProperty(symbol);
36081 }
36082 // CommonsJS require and module both have type any.
36083 if (symbol === requireSymbol) {
36084 return anyType;
36085 }
36086 if (symbol.flags & 134217728 /* ModuleExports */) {
36087 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
36088 var members = ts.createSymbolTable();
36089 members.set("exports", fileSymbol);
36090 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
36091 }
36092 // Handle catch clause variables
36093 var declaration = symbol.valueDeclaration;
36094 if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
36095 return anyType;
36096 }
36097 // Handle export default expressions
36098 if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
36099 if (!declaration.statements.length) {
36100 return emptyObjectType;
36101 }
36102 var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression));
36103 if (type_1.flags & 524288 /* Object */) {
36104 return getRegularTypeOfObjectLiteral(type_1);
36105 }
36106 return type_1;
36107 }
36108 // Handle variable, parameter or property
36109 if (!pushTypeResolution(symbol, 0 /* Type */)) {
36110 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
36111 if (symbol.flags & 512 /* ValueModule */) {
36112 return getTypeOfFuncClassEnumModule(symbol);
36113 }
36114 return reportCircularityError(symbol);
36115 }
36116 var type;
36117 if (declaration.kind === 254 /* ExportAssignment */) {
36118 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
36119 }
36120 else if (ts.isInJSFile(declaration) &&
36121 (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) {
36122 type = getWidenedTypeFromAssignmentDeclaration(symbol);
36123 }
36124 else if (ts.isJSDocPropertyLikeTag(declaration)
36125 || ts.isPropertyAccessExpression(declaration)
36126 || ts.isIdentifier(declaration)
36127 || ts.isClassDeclaration(declaration)
36128 || ts.isFunctionDeclaration(declaration)
36129 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
36130 || ts.isMethodSignature(declaration)
36131 || ts.isSourceFile(declaration)) {
36132 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
36133 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
36134 return getTypeOfFuncClassEnumModule(symbol);
36135 }
36136 type = ts.isBinaryExpression(declaration.parent) ?
36137 getWidenedTypeFromAssignmentDeclaration(symbol) :
36138 tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
36139 }
36140 else if (ts.isPropertyAssignment(declaration)) {
36141 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
36142 }
36143 else if (ts.isJsxAttribute(declaration)) {
36144 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
36145 }
36146 else if (ts.isShorthandPropertyAssignment(declaration)) {
36147 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
36148 }
36149 else if (ts.isObjectLiteralMethod(declaration)) {
36150 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
36151 }
36152 else if (ts.isParameter(declaration)
36153 || ts.isPropertyDeclaration(declaration)
36154 || ts.isPropertySignature(declaration)
36155 || ts.isVariableDeclaration(declaration)
36156 || ts.isBindingElement(declaration)) {
36157 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
36158 }
36159 // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
36160 // Re-dispatch based on valueDeclaration.kind instead.
36161 else if (ts.isEnumDeclaration(declaration)) {
36162 type = getTypeOfFuncClassEnumModule(symbol);
36163 }
36164 else if (ts.isEnumMember(declaration)) {
36165 type = getTypeOfEnumMember(symbol);
36166 }
36167 else {
36168 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol));
36169 }
36170 if (!popTypeResolution()) {
36171 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
36172 if (symbol.flags & 512 /* ValueModule */) {
36173 return getTypeOfFuncClassEnumModule(symbol);
36174 }
36175 return reportCircularityError(symbol);
36176 }
36177 return type;
36178 }
36179 function getAnnotatedAccessorTypeNode(accessor) {
36180 if (accessor) {
36181 if (accessor.kind === 158 /* GetAccessor */) {
36182 var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
36183 return getterTypeAnnotation;
36184 }
36185 else {
36186 var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
36187 return setterTypeAnnotation;
36188 }
36189 }
36190 return undefined;
36191 }
36192 function getAnnotatedAccessorType(accessor) {
36193 var node = getAnnotatedAccessorTypeNode(accessor);
36194 return node && getTypeFromTypeNode(node);
36195 }
36196 function getAnnotatedAccessorThisParameter(accessor) {
36197 var parameter = getAccessorThisParameter(accessor);
36198 return parameter && parameter.symbol;
36199 }
36200 function getThisTypeOfDeclaration(declaration) {
36201 return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
36202 }
36203 function getTypeOfAccessors(symbol) {
36204 var links = getSymbolLinks(symbol);
36205 return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
36206 }
36207 function getTypeOfAccessorsWorker(symbol) {
36208 var getter = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */);
36209 var setter = ts.getDeclarationOfKind(symbol, 159 /* SetAccessor */);
36210 if (getter && ts.isInJSFile(getter)) {
36211 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
36212 if (jsDocType) {
36213 return jsDocType;
36214 }
36215 }
36216 if (!pushTypeResolution(symbol, 0 /* Type */)) {
36217 return errorType;
36218 }
36219 var type;
36220 // First try to see if the user specified a return type on the get-accessor.
36221 var getterReturnType = getAnnotatedAccessorType(getter);
36222 if (getterReturnType) {
36223 type = getterReturnType;
36224 }
36225 else {
36226 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
36227 var setterParameterType = getAnnotatedAccessorType(setter);
36228 if (setterParameterType) {
36229 type = setterParameterType;
36230 }
36231 else {
36232 // If there are no specified types, try to infer it from the body of the get accessor if it exists.
36233 if (getter && getter.body) {
36234 type = getReturnTypeFromBody(getter);
36235 }
36236 // Otherwise, fall back to 'any'.
36237 else {
36238 if (setter) {
36239 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
36240 }
36241 else {
36242 ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function");
36243 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
36244 }
36245 type = anyType;
36246 }
36247 }
36248 }
36249 if (!popTypeResolution()) {
36250 type = anyType;
36251 if (noImplicitAny) {
36252 var getter_1 = ts.getDeclarationOfKind(symbol, 158 /* GetAccessor */);
36253 error(getter_1, ts.Diagnostics._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, symbolToString(symbol));
36254 }
36255 }
36256 return type;
36257 }
36258 function getBaseTypeVariableOfClass(symbol) {
36259 var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
36260 return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : undefined;
36261 }
36262 function getTypeOfFuncClassEnumModule(symbol) {
36263 var links = getSymbolLinks(symbol);
36264 var originalLinks = links;
36265 if (!links.type) {
36266 var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration);
36267 if (jsDeclaration) {
36268 var jsSymbol = getSymbolOfNode(jsDeclaration);
36269 if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) {
36270 symbol = cloneSymbol(symbol);
36271 // note:we overwrite links because we just cloned the symbol
36272 links = symbol;
36273 if (ts.hasEntries(jsSymbol.exports)) {
36274 symbol.exports = symbol.exports || ts.createSymbolTable();
36275 mergeSymbolTable(symbol.exports, jsSymbol.exports);
36276 }
36277 if (ts.hasEntries(jsSymbol.members)) {
36278 symbol.members = symbol.members || ts.createSymbolTable();
36279 mergeSymbolTable(symbol.members, jsSymbol.members);
36280 }
36281 }
36282 }
36283 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
36284 }
36285 return links.type;
36286 }
36287 function getTypeOfFuncClassEnumModuleWorker(symbol) {
36288 var declaration = symbol.valueDeclaration;
36289 if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
36290 return anyType;
36291 }
36292 else if (declaration.kind === 204 /* BinaryExpression */ ||
36293 declaration.kind === 189 /* PropertyAccessExpression */ && declaration.parent.kind === 204 /* BinaryExpression */) {
36294 return getWidenedTypeFromAssignmentDeclaration(symbol);
36295 }
36296 else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
36297 var resolvedModule = resolveExternalModuleSymbol(symbol);
36298 if (resolvedModule !== symbol) {
36299 if (!pushTypeResolution(symbol, 0 /* Type */)) {
36300 return errorType;
36301 }
36302 var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
36303 var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
36304 if (!popTypeResolution()) {
36305 return reportCircularityError(symbol);
36306 }
36307 return type_2;
36308 }
36309 }
36310 var type = createObjectType(16 /* Anonymous */, symbol);
36311 if (symbol.flags & 32 /* Class */) {
36312 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
36313 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
36314 }
36315 else {
36316 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
36317 }
36318 }
36319 function getTypeOfEnumMember(symbol) {
36320 var links = getSymbolLinks(symbol);
36321 return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
36322 }
36323 function getTypeOfAlias(symbol) {
36324 var links = getSymbolLinks(symbol);
36325 if (!links.type) {
36326 var targetSymbol = resolveAlias(symbol);
36327 // It only makes sense to get the type of a value symbol. If the result of resolving
36328 // the alias is not a value, then it has no type. To get the type associated with a
36329 // type symbol, call getDeclaredTypeOfSymbol.
36330 // This check is important because without it, a call to getTypeOfSymbol could end
36331 // up recursively calling getTypeOfAlias, causing a stack overflow.
36332 links.type = targetSymbol.flags & 67220415 /* Value */
36333 ? getTypeOfSymbol(targetSymbol)
36334 : errorType;
36335 }
36336 return links.type;
36337 }
36338 function getTypeOfInstantiatedSymbol(symbol) {
36339 var links = getSymbolLinks(symbol);
36340 if (!links.type) {
36341 if (!pushTypeResolution(symbol, 0 /* Type */)) {
36342 return links.type = errorType;
36343 }
36344 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
36345 if (!popTypeResolution()) {
36346 type = reportCircularityError(symbol);
36347 }
36348 links.type = type;
36349 }
36350 return links.type;
36351 }
36352 function reportCircularityError(symbol) {
36353 var declaration = symbol.valueDeclaration;
36354 // Check if variable has type annotation that circularly references the variable itself
36355 if (ts.getEffectiveTypeAnnotationNode(declaration)) {
36356 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
36357 return errorType;
36358 }
36359 // Check if variable has initializer that circularly references the variable itself
36360 if (noImplicitAny && (declaration.kind !== 151 /* Parameter */ || declaration.initializer)) {
36361 error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
36362 }
36363 // Circularities could also result from parameters in function expressions that end up
36364 // having themselves as contextual types following type argument inference. In those cases
36365 // we have already reported an implicit any error so we don't report anything here.
36366 return anyType;
36367 }
36368 function getTypeOfSymbol(symbol) {
36369 if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
36370 return getTypeOfInstantiatedSymbol(symbol);
36371 }
36372 if (ts.getCheckFlags(symbol) & 4096 /* ReverseMapped */) {
36373 return getTypeOfReverseMappedSymbol(symbol);
36374 }
36375 if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
36376 return getTypeOfVariableOrParameterOrProperty(symbol);
36377 }
36378 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
36379 return getTypeOfFuncClassEnumModule(symbol);
36380 }
36381 if (symbol.flags & 8 /* EnumMember */) {
36382 return getTypeOfEnumMember(symbol);
36383 }
36384 if (symbol.flags & 98304 /* Accessor */) {
36385 return getTypeOfAccessors(symbol);
36386 }
36387 if (symbol.flags & 2097152 /* Alias */) {
36388 return getTypeOfAlias(symbol);
36389 }
36390 return errorType;
36391 }
36392 function isReferenceToType(type, target) {
36393 return type !== undefined
36394 && target !== undefined
36395 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
36396 && type.target === target;
36397 }
36398 function getTargetType(type) {
36399 return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
36400 }
36401 // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
36402 function hasBaseType(type, checkBase) {
36403 return check(type);
36404 function check(type) {
36405 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
36406 var target = getTargetType(type);
36407 return target === checkBase || ts.some(getBaseTypes(target), check);
36408 }
36409 else if (type.flags & 2097152 /* Intersection */) {
36410 return ts.some(type.types, check);
36411 }
36412 return false;
36413 }
36414 }
36415 // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
36416 // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
36417 // in-place and returns the same array.
36418 function appendTypeParameters(typeParameters, declarations) {
36419 for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
36420 var declaration = declarations_2[_i];
36421 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
36422 }
36423 return typeParameters;
36424 }
36425 // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
36426 function getOuterTypeParameters(node, includeThisTypes) {
36427 while (true) {
36428 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
36429 if (!node) {
36430 return undefined;
36431 }
36432 switch (node.kind) {
36433 case 240 /* ClassDeclaration */:
36434 case 209 /* ClassExpression */:
36435 case 241 /* InterfaceDeclaration */:
36436 case 160 /* CallSignature */:
36437 case 161 /* ConstructSignature */:
36438 case 155 /* MethodSignature */:
36439 case 165 /* FunctionType */:
36440 case 166 /* ConstructorType */:
36441 case 294 /* JSDocFunctionType */:
36442 case 239 /* FunctionDeclaration */:
36443 case 156 /* MethodDeclaration */:
36444 case 196 /* FunctionExpression */:
36445 case 197 /* ArrowFunction */:
36446 case 242 /* TypeAliasDeclaration */:
36447 case 308 /* JSDocTemplateTag */:
36448 case 309 /* JSDocTypedefTag */:
36449 case 302 /* JSDocCallbackTag */:
36450 case 181 /* MappedType */:
36451 case 175 /* ConditionalType */:
36452 var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
36453 if (node.kind === 181 /* MappedType */) {
36454 return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
36455 }
36456 else if (node.kind === 175 /* ConditionalType */) {
36457 return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
36458 }
36459 var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
36460 var thisType = includeThisTypes &&
36461 (node.kind === 240 /* ClassDeclaration */ || node.kind === 209 /* ClassExpression */ || node.kind === 241 /* InterfaceDeclaration */) &&
36462 getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
36463 return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
36464 }
36465 }
36466 }
36467 // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
36468 function getOuterTypeParametersOfClassOrInterface(symbol) {
36469 var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */);
36470 return getOuterTypeParameters(declaration);
36471 }
36472 // The local type parameters are the combined set of type parameters from all declarations of the class,
36473 // interface, or type alias.
36474 function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
36475 var result;
36476 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
36477 var node = _a[_i];
36478 if (node.kind === 241 /* InterfaceDeclaration */ ||
36479 node.kind === 240 /* ClassDeclaration */ ||
36480 node.kind === 209 /* ClassExpression */ ||
36481 ts.isTypeAlias(node)) {
36482 var declaration = node;
36483 result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
36484 }
36485 }
36486 return result;
36487 }
36488 // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
36489 // its locally declared type parameters.
36490 function getTypeParametersOfClassOrInterface(symbol) {
36491 return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
36492 }
36493 // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
36494 // rest parameter of type any[].
36495 function isMixinConstructorType(type) {
36496 var signatures = getSignaturesOfType(type, 1 /* Construct */);
36497 if (signatures.length === 1) {
36498 var s = signatures[0];
36499 return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType;
36500 }
36501 return false;
36502 }
36503 function isConstructorType(type) {
36504 if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) {
36505 return true;
36506 }
36507 if (type.flags & 8650752 /* TypeVariable */) {
36508 var constraint = getBaseConstraintOfType(type);
36509 return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint);
36510 }
36511 return isJSConstructorType(type);
36512 }
36513 function getBaseTypeNodeOfClass(type) {
36514 return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
36515 }
36516 function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
36517 var typeArgCount = ts.length(typeArgumentNodes);
36518 var isJavascript = ts.isInJSFile(location);
36519 return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
36520 }
36521 function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
36522 var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
36523 var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
36524 return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
36525 }
36526 /**
36527 * The base constructor of a class can resolve to
36528 * * undefinedType if the class has no extends clause,
36529 * * unknownType if an error occurred during resolution of the extends expression,
36530 * * nullType if the extends expression is the null value,
36531 * * anyType if the extends expression has type any, or
36532 * * an object type with at least one construct signature.
36533 */
36534 function getBaseConstructorTypeOfClass(type) {
36535 if (!type.resolvedBaseConstructorType) {
36536 var decl = type.symbol.valueDeclaration;
36537 var extended = ts.getEffectiveBaseTypeNode(decl);
36538 var baseTypeNode = getBaseTypeNodeOfClass(type);
36539 if (!baseTypeNode) {
36540 return type.resolvedBaseConstructorType = undefinedType;
36541 }
36542 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
36543 return errorType;
36544 }
36545 var baseConstructorType = checkExpression(baseTypeNode.expression);
36546 if (extended && baseTypeNode !== extended) {
36547 ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
36548 checkExpression(extended.expression);
36549 }
36550 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
36551 // Resolving the members of a class requires us to resolve the base class of that class.
36552 // We force resolution here such that we catch circularities now.
36553 resolveStructuredTypeMembers(baseConstructorType);
36554 }
36555 if (!popTypeResolution()) {
36556 error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
36557 return type.resolvedBaseConstructorType = errorType;
36558 }
36559 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
36560 var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
36561 if (baseConstructorType.flags & 262144 /* TypeParameter */) {
36562 var constraint = getConstraintFromTypeParameter(baseConstructorType);
36563 var ctorReturn = unknownType;
36564 if (constraint) {
36565 var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
36566 if (ctorSig[0]) {
36567 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
36568 }
36569 }
36570 ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
36571 }
36572 return type.resolvedBaseConstructorType = errorType;
36573 }
36574 type.resolvedBaseConstructorType = baseConstructorType;
36575 }
36576 return type.resolvedBaseConstructorType;
36577 }
36578 function getBaseTypes(type) {
36579 if (!type.resolvedBaseTypes) {
36580 if (type.objectFlags & 8 /* Tuple */) {
36581 type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
36582 }
36583 else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
36584 if (type.symbol.flags & 32 /* Class */) {
36585 resolveBaseTypesOfClass(type);
36586 }
36587 if (type.symbol.flags & 64 /* Interface */) {
36588 resolveBaseTypesOfInterface(type);
36589 }
36590 }
36591 else {
36592 ts.Debug.fail("type must be class or interface");
36593 }
36594 }
36595 return type.resolvedBaseTypes;
36596 }
36597 function resolveBaseTypesOfClass(type) {
36598 type.resolvedBaseTypes = ts.resolvingEmptyArray;
36599 var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
36600 if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
36601 return type.resolvedBaseTypes = ts.emptyArray;
36602 }
36603 var baseTypeNode = getBaseTypeNodeOfClass(type);
36604 var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode);
36605 var baseType;
36606 var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType :
36607 baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) :
36608 undefined;
36609 if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
36610 areAllOuterTypeParametersApplied(originalBaseType)) {
36611 // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the
36612 // class and all return the instance type of the class. There is no need for further checks and we can apply the
36613 // type arguments in the same manner as a type reference to get the same error reporting experience.
36614 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs);
36615 }
36616 else if (baseConstructorType.flags & 1 /* Any */) {
36617 baseType = baseConstructorType;
36618 }
36619 else if (isJSConstructorType(baseConstructorType)) {
36620 baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType;
36621 }
36622 else {
36623 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
36624 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
36625 // we check that all instantiated signatures return the same type.
36626 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
36627 if (!constructors.length) {
36628 error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
36629 return type.resolvedBaseTypes = ts.emptyArray;
36630 }
36631 baseType = getReturnTypeOfSignature(constructors[0]);
36632 }
36633 if (baseType === errorType) {
36634 return type.resolvedBaseTypes = ts.emptyArray;
36635 }
36636 if (!isValidBaseType(baseType)) {
36637 error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType));
36638 return type.resolvedBaseTypes = ts.emptyArray;
36639 }
36640 if (type === baseType || hasBaseType(baseType, type)) {
36641 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
36642 return type.resolvedBaseTypes = ts.emptyArray;
36643 }
36644 if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
36645 // Circular reference, likely through instantiation of default parameters
36646 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
36647 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
36648 // partial instantiation of the members without the base types fully resolved
36649 type.members = undefined;
36650 }
36651 return type.resolvedBaseTypes = [baseType];
36652 }
36653 function areAllOuterTypeParametersApplied(type) {
36654 // An unapplied type parameter has its symbol still the same as the matching argument symbol.
36655 // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
36656 var outerTypeParameters = type.outerTypeParameters;
36657 if (outerTypeParameters) {
36658 var last_1 = outerTypeParameters.length - 1;
36659 var typeArguments = type.typeArguments;
36660 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
36661 }
36662 return true;
36663 }
36664 // A valid base type is `any`, any non-generic object type or intersection of non-generic
36665 // object types.
36666 function isValidBaseType(type) {
36667 return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) ||
36668 !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType);
36669 }
36670 function resolveBaseTypesOfInterface(type) {
36671 type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
36672 for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
36673 var declaration = _a[_i];
36674 if (declaration.kind === 241 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
36675 for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
36676 var node = _c[_b];
36677 var baseType = getTypeFromTypeNode(node);
36678 if (baseType !== errorType) {
36679 if (isValidBaseType(baseType)) {
36680 if (type !== baseType && !hasBaseType(baseType, type)) {
36681 if (type.resolvedBaseTypes === ts.emptyArray) {
36682 type.resolvedBaseTypes = [baseType];
36683 }
36684 else {
36685 type.resolvedBaseTypes.push(baseType);
36686 }
36687 }
36688 else {
36689 error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
36690 }
36691 }
36692 else {
36693 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
36694 }
36695 }
36696 }
36697 }
36698 }
36699 }
36700 /**
36701 * Returns true if the interface given by the symbol is free of "this" references.
36702 *
36703 * Specifically, the result is true if the interface itself contains no references
36704 * to "this" in its body, if all base types are interfaces,
36705 * and if none of the base interfaces have a "this" type.
36706 */
36707 function isThislessInterface(symbol) {
36708 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
36709 var declaration = _a[_i];
36710 if (declaration.kind === 241 /* InterfaceDeclaration */) {
36711 if (declaration.flags & 64 /* ContainsThis */) {
36712 return false;
36713 }
36714 var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
36715 if (baseTypeNodes) {
36716 for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
36717 var node = baseTypeNodes_1[_b];
36718 if (ts.isEntityNameExpression(node.expression)) {
36719 var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true);
36720 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
36721 return false;
36722 }
36723 }
36724 }
36725 }
36726 }
36727 }
36728 return true;
36729 }
36730 function getDeclaredTypeOfClassOrInterface(symbol) {
36731 var links = getSymbolLinks(symbol);
36732 if (!links.declaredType) {
36733 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
36734 var type = links.declaredType = createObjectType(kind, symbol);
36735 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
36736 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
36737 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
36738 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
36739 // property types inferred from initializers and method return types inferred from return statements are very hard
36740 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
36741 // "this" references.
36742 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
36743 type.objectFlags |= 4 /* Reference */;
36744 type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
36745 type.outerTypeParameters = outerTypeParameters;
36746 type.localTypeParameters = localTypeParameters;
36747 type.instantiations = ts.createMap();
36748 type.instantiations.set(getTypeListId(type.typeParameters), type);
36749 type.target = type;
36750 type.typeArguments = type.typeParameters;
36751 type.thisType = createTypeParameter(symbol);
36752 type.thisType.isThisType = true;
36753 type.thisType.constraint = type;
36754 }
36755 }
36756 return links.declaredType;
36757 }
36758 function getDeclaredTypeOfTypeAlias(symbol) {
36759 var links = getSymbolLinks(symbol);
36760 if (!links.declaredType) {
36761 // Note that we use the links object as the target here because the symbol object is used as the unique
36762 // identity for resolution of the 'type' property in SymbolLinks.
36763 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
36764 return errorType;
36765 }
36766 var declaration = ts.find(symbol.declarations, function (d) {
36767 return ts.isJSDocTypeAlias(d) || d.kind === 242 /* TypeAliasDeclaration */;
36768 });
36769 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
36770 // If typeNode is missing, we will error in checkJSDocTypedefTag.
36771 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
36772 if (popTypeResolution()) {
36773 var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
36774 if (typeParameters) {
36775 // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
36776 // an instantiation of the type alias with the type parameters supplied as type arguments.
36777 links.typeParameters = typeParameters;
36778 links.instantiations = ts.createMap();
36779 links.instantiations.set(getTypeListId(typeParameters), type);
36780 }
36781 }
36782 else {
36783 type = errorType;
36784 error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
36785 }
36786 links.declaredType = type;
36787 }
36788 return links.declaredType;
36789 }
36790 function isStringConcatExpression(expr) {
36791 if (expr.kind === 10 /* StringLiteral */) {
36792 return true;
36793 }
36794 else if (expr.kind === 204 /* BinaryExpression */) {
36795 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
36796 }
36797 return false;
36798 }
36799 function isLiteralEnumMember(member) {
36800 var expr = member.initializer;
36801 if (!expr) {
36802 return !(member.flags & 4194304 /* Ambient */);
36803 }
36804 switch (expr.kind) {
36805 case 10 /* StringLiteral */:
36806 case 8 /* NumericLiteral */:
36807 return true;
36808 case 202 /* PrefixUnaryExpression */:
36809 return expr.operator === 39 /* MinusToken */ &&
36810 expr.operand.kind === 8 /* NumericLiteral */;
36811 case 72 /* Identifier */:
36812 return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
36813 case 204 /* BinaryExpression */:
36814 return isStringConcatExpression(expr);
36815 default:
36816 return false;
36817 }
36818 }
36819 function getEnumKind(symbol) {
36820 var links = getSymbolLinks(symbol);
36821 if (links.enumKind !== undefined) {
36822 return links.enumKind;
36823 }
36824 var hasNonLiteralMember = false;
36825 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
36826 var declaration = _a[_i];
36827 if (declaration.kind === 243 /* EnumDeclaration */) {
36828 for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
36829 var member = _c[_b];
36830 if (member.initializer && member.initializer.kind === 10 /* StringLiteral */) {
36831 return links.enumKind = 1 /* Literal */;
36832 }
36833 if (!isLiteralEnumMember(member)) {
36834 hasNonLiteralMember = true;
36835 }
36836 }
36837 }
36838 }
36839 return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
36840 }
36841 function getBaseTypeOfEnumLiteralType(type) {
36842 return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
36843 }
36844 function getDeclaredTypeOfEnum(symbol) {
36845 var links = getSymbolLinks(symbol);
36846 if (links.declaredType) {
36847 return links.declaredType;
36848 }
36849 if (getEnumKind(symbol) === 1 /* Literal */) {
36850 enumCount++;
36851 var memberTypeList = [];
36852 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
36853 var declaration = _a[_i];
36854 if (declaration.kind === 243 /* EnumDeclaration */) {
36855 for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
36856 var member = _c[_b];
36857 var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217
36858 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
36859 memberTypeList.push(getRegularTypeOfLiteralType(memberType));
36860 }
36861 }
36862 }
36863 if (memberTypeList.length) {
36864 var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
36865 if (enumType_1.flags & 1048576 /* Union */) {
36866 enumType_1.flags |= 1024 /* EnumLiteral */;
36867 enumType_1.symbol = symbol;
36868 }
36869 return links.declaredType = enumType_1;
36870 }
36871 }
36872 var enumType = createType(32 /* Enum */);
36873 enumType.symbol = symbol;
36874 return links.declaredType = enumType;
36875 }
36876 function getDeclaredTypeOfEnumMember(symbol) {
36877 var links = getSymbolLinks(symbol);
36878 if (!links.declaredType) {
36879 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
36880 if (!links.declaredType) {
36881 links.declaredType = enumType;
36882 }
36883 }
36884 return links.declaredType;
36885 }
36886 function getDeclaredTypeOfTypeParameter(symbol) {
36887 var links = getSymbolLinks(symbol);
36888 return links.declaredType || (links.declaredType = createTypeParameter(symbol));
36889 }
36890 function getDeclaredTypeOfAlias(symbol) {
36891 var links = getSymbolLinks(symbol);
36892 return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
36893 }
36894 function getDeclaredTypeOfSymbol(symbol) {
36895 return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
36896 }
36897 function tryGetDeclaredTypeOfSymbol(symbol) {
36898 if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
36899 return getDeclaredTypeOfClassOrInterface(symbol);
36900 }
36901 if (symbol.flags & 524288 /* TypeAlias */) {
36902 return getDeclaredTypeOfTypeAlias(symbol);
36903 }
36904 if (symbol.flags & 262144 /* TypeParameter */) {
36905 return getDeclaredTypeOfTypeParameter(symbol);
36906 }
36907 if (symbol.flags & 384 /* Enum */) {
36908 return getDeclaredTypeOfEnum(symbol);
36909 }
36910 if (symbol.flags & 8 /* EnumMember */) {
36911 return getDeclaredTypeOfEnumMember(symbol);
36912 }
36913 if (symbol.flags & 2097152 /* Alias */) {
36914 return getDeclaredTypeOfAlias(symbol);
36915 }
36916 return undefined;
36917 }
36918 /**
36919 * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
36920 * literal type, an array with an element type that is free of this references, or a type reference that is
36921 * free of this references.
36922 */
36923 function isThislessType(node) {
36924 switch (node.kind) {
36925 case 120 /* AnyKeyword */:
36926 case 143 /* UnknownKeyword */:
36927 case 138 /* StringKeyword */:
36928 case 135 /* NumberKeyword */:
36929 case 146 /* BigIntKeyword */:
36930 case 123 /* BooleanKeyword */:
36931 case 139 /* SymbolKeyword */:
36932 case 136 /* ObjectKeyword */:
36933 case 106 /* VoidKeyword */:
36934 case 141 /* UndefinedKeyword */:
36935 case 96 /* NullKeyword */:
36936 case 132 /* NeverKeyword */:
36937 case 182 /* LiteralType */:
36938 return true;
36939 case 169 /* ArrayType */:
36940 return isThislessType(node.elementType);
36941 case 164 /* TypeReference */:
36942 return !node.typeArguments || node.typeArguments.every(isThislessType);
36943 }
36944 return false;
36945 }
36946 /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
36947 function isThislessTypeParameter(node) {
36948 var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
36949 return !constraint || isThislessType(constraint);
36950 }
36951 /**
36952 * A variable-like declaration is free of this references if it has a type annotation
36953 * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
36954 */
36955 function isThislessVariableLikeDeclaration(node) {
36956 var typeNode = ts.getEffectiveTypeAnnotationNode(node);
36957 return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
36958 }
36959 /**
36960 * A function-like declaration is considered free of `this` references if it has a return type
36961 * annotation that is free of this references and if each parameter is thisless and if
36962 * each type parameter (if present) is thisless.
36963 */
36964 function isThislessFunctionLikeDeclaration(node) {
36965 var returnType = ts.getEffectiveReturnTypeNode(node);
36966 var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
36967 return (node.kind === 157 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
36968 node.parameters.every(isThislessVariableLikeDeclaration) &&
36969 typeParameters.every(isThislessTypeParameter);
36970 }
36971 /**
36972 * Returns true if the class or interface member given by the symbol is free of "this" references. The
36973 * function may return false for symbols that are actually free of "this" references because it is not
36974 * feasible to perform a complete analysis in all cases. In particular, property members with types
36975 * inferred from their initializers and function members with inferred return types are conservatively
36976 * assumed not to be free of "this" references.
36977 */
36978 function isThisless(symbol) {
36979 if (symbol.declarations && symbol.declarations.length === 1) {
36980 var declaration = symbol.declarations[0];
36981 if (declaration) {
36982 switch (declaration.kind) {
36983 case 154 /* PropertyDeclaration */:
36984 case 153 /* PropertySignature */:
36985 return isThislessVariableLikeDeclaration(declaration);
36986 case 156 /* MethodDeclaration */:
36987 case 155 /* MethodSignature */:
36988 case 157 /* Constructor */:
36989 case 158 /* GetAccessor */:
36990 case 159 /* SetAccessor */:
36991 return isThislessFunctionLikeDeclaration(declaration);
36992 }
36993 }
36994 }
36995 return false;
36996 }
36997 // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
36998 // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
36999 function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
37000 var result = ts.createSymbolTable();
37001 for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
37002 var symbol = symbols_2[_i];
37003 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
37004 }
37005 return result;
37006 }
37007 function addInheritedMembers(symbols, baseSymbols) {
37008 for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
37009 var s = baseSymbols_1[_i];
37010 if (!symbols.has(s.escapedName)) {
37011 symbols.set(s.escapedName, s);
37012 }
37013 }
37014 }
37015 function resolveDeclaredMembers(type) {
37016 if (!type.declaredProperties) {
37017 var symbol = type.symbol;
37018 var members = getMembersOfSymbol(symbol);
37019 type.declaredProperties = getNamedMembers(members);
37020 // Start with signatures at empty array in case of recursive types
37021 type.declaredCallSignatures = ts.emptyArray;
37022 type.declaredConstructSignatures = ts.emptyArray;
37023 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
37024 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
37025 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
37026 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
37027 }
37028 return type;
37029 }
37030 /**
37031 * Indicates whether a type can be used as a property name.
37032 */
37033 function isTypeUsableAsPropertyName(type) {
37034 return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
37035 }
37036 /**
37037 * Indicates whether a declaration name is definitely late-bindable.
37038 * A declaration name is only late-bindable if:
37039 * - It is a `ComputedPropertyName`.
37040 * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
37041 * `ElementAccessExpression` consisting only of these same three types of nodes.
37042 * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
37043 */
37044 function isLateBindableName(node) {
37045 return ts.isComputedPropertyName(node)
37046 && ts.isEntityNameExpression(node.expression)
37047 && isTypeUsableAsPropertyName(checkComputedPropertyName(node));
37048 }
37049 function isLateBoundName(name) {
37050 return name.charCodeAt(0) === 95 /* _ */ &&
37051 name.charCodeAt(1) === 95 /* _ */ &&
37052 name.charCodeAt(2) === 64 /* at */;
37053 }
37054 /**
37055 * Indicates whether a declaration has a late-bindable dynamic name.
37056 */
37057 function hasLateBindableName(node) {
37058 var name = ts.getNameOfDeclaration(node);
37059 return !!name && isLateBindableName(name);
37060 }
37061 /**
37062 * Indicates whether a declaration has a dynamic name that cannot be late-bound.
37063 */
37064 function hasNonBindableDynamicName(node) {
37065 return ts.hasDynamicName(node) && !hasLateBindableName(node);
37066 }
37067 /**
37068 * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
37069 */
37070 function isNonBindableDynamicName(node) {
37071 return ts.isDynamicName(node) && !isLateBindableName(node);
37072 }
37073 /**
37074 * Gets the symbolic name for a member from its type.
37075 */
37076 function getPropertyNameFromType(type) {
37077 if (type.flags & 8192 /* UniqueESSymbol */) {
37078 return type.escapedName;
37079 }
37080 if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
37081 return ts.escapeLeadingUnderscores("" + type.value);
37082 }
37083 return ts.Debug.fail();
37084 }
37085 /**
37086 * Adds a declaration to a late-bound dynamic member. This performs the same function for
37087 * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
37088 * members.
37089 */
37090 function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
37091 ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 2048 /* Late */), "Expected a late-bound symbol.");
37092 symbol.flags |= symbolFlags;
37093 getSymbolLinks(member.symbol).lateSymbol = symbol;
37094 if (!symbol.declarations) {
37095 symbol.declarations = [member];
37096 }
37097 else {
37098 symbol.declarations.push(member);
37099 }
37100 if (symbolFlags & 67220415 /* Value */) {
37101 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
37102 symbol.valueDeclaration = member;
37103 }
37104 }
37105 }
37106 /**
37107 * Performs late-binding of a dynamic member. This performs the same function for
37108 * late-bound members that `declareSymbol` in binder.ts performs for early-bound
37109 * members.
37110 *
37111 * If a symbol is a dynamic name from a computed property, we perform an additional "late"
37112 * binding phase to attempt to resolve the name for the symbol from the type of the computed
37113 * property's expression. If the type of the expression is a string-literal, numeric-literal,
37114 * or unique symbol type, we can use that type as the name of the symbol.
37115 *
37116 * For example, given:
37117 *
37118 * const x = Symbol();
37119 *
37120 * interface I {
37121 * [x]: number;
37122 * }
37123 *
37124 * The binder gives the property `[x]: number` a special symbol with the name "__computed".
37125 * In the late-binding phase we can type-check the expression `x` and see that it has a
37126 * unique symbol type which we can then use as the name of the member. This allows users
37127 * to define custom symbols that can be used in the members of an object type.
37128 *
37129 * @param parent The containing symbol for the member.
37130 * @param earlySymbols The early-bound symbols of the parent.
37131 * @param lateSymbols The late-bound symbols of the parent.
37132 * @param decl The member to bind.
37133 */
37134 function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
37135 ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
37136 var links = getNodeLinks(decl);
37137 if (!links.resolvedSymbol) {
37138 // In the event we attempt to resolve the late-bound name of this member recursively,
37139 // fall back to the early-bound name of this member.
37140 links.resolvedSymbol = decl.symbol;
37141 var type = checkComputedPropertyName(decl.name);
37142 if (isTypeUsableAsPropertyName(type)) {
37143 var memberName = getPropertyNameFromType(type);
37144 var symbolFlags = decl.symbol.flags;
37145 // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
37146 var lateSymbol = lateSymbols.get(memberName);
37147 if (!lateSymbol)
37148 lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */));
37149 // Report an error if a late-bound member has the same name as an early-bound member,
37150 // or if we have another early-bound symbol declaration with the same name and
37151 // conflicting flags.
37152 var earlySymbol = earlySymbols && earlySymbols.get(memberName);
37153 if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
37154 // If we have an existing early-bound member, combine its declarations so that we can
37155 // report an error at each declaration.
37156 var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
37157 var name_3 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(decl.name);
37158 ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_3); });
37159 error(decl.name || decl, ts.Diagnostics.Duplicate_property_0, name_3);
37160 lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */);
37161 }
37162 lateSymbol.nameType = type;
37163 addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
37164 if (lateSymbol.parent) {
37165 ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
37166 }
37167 else {
37168 lateSymbol.parent = parent;
37169 }
37170 return links.resolvedSymbol = lateSymbol;
37171 }
37172 }
37173 return links.resolvedSymbol;
37174 }
37175 function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
37176 var links = getSymbolLinks(symbol);
37177 if (!links[resolutionKind]) {
37178 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
37179 var earlySymbols = !isStatic ? symbol.members :
37180 symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
37181 symbol.exports;
37182 // In the event we recursively resolve the members/exports of the symbol, we
37183 // set the initial value of resolvedMembers/resolvedExports to the early-bound
37184 // members/exports of the symbol.
37185 links[resolutionKind] = earlySymbols || emptySymbols;
37186 // fill in any as-yet-unresolved late-bound members.
37187 var lateSymbols = ts.createSymbolTable();
37188 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
37189 var decl = _a[_i];
37190 var members = ts.getMembersOfDeclaration(decl);
37191 if (members) {
37192 for (var _b = 0, members_4 = members; _b < members_4.length; _b++) {
37193 var member = members_4[_b];
37194 if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
37195 lateBindMember(symbol, earlySymbols, lateSymbols, member);
37196 }
37197 }
37198 }
37199 }
37200 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
37201 }
37202 return links[resolutionKind];
37203 }
37204 /**
37205 * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
37206 *
37207 * For a description of late-binding, see `lateBindMember`.
37208 */
37209 function getMembersOfSymbol(symbol) {
37210 return symbol.flags & 6240 /* LateBindingContainer */
37211 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
37212 : symbol.members || emptySymbols;
37213 }
37214 /**
37215 * If a symbol is the dynamic name of the member of an object type, get the late-bound
37216 * symbol of the member.
37217 *
37218 * For a description of late-binding, see `lateBindMember`.
37219 */
37220 function getLateBoundSymbol(symbol) {
37221 if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
37222 var links = getSymbolLinks(symbol);
37223 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
37224 // force late binding of members/exports. This will set the late-bound symbol
37225 if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
37226 getExportsOfSymbol(symbol.parent);
37227 }
37228 else {
37229 getMembersOfSymbol(symbol.parent);
37230 }
37231 }
37232 return links.lateSymbol || (links.lateSymbol = symbol);
37233 }
37234 return symbol;
37235 }
37236 function getTypeWithThisArgument(type, thisArgument, needApparentType) {
37237 if (ts.getObjectFlags(type) & 4 /* Reference */) {
37238 var target = type.target;
37239 var typeArguments = type.typeArguments;
37240 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
37241 var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
37242 return needApparentType ? getApparentType(ref) : ref;
37243 }
37244 }
37245 else if (type.flags & 2097152 /* Intersection */) {
37246 return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
37247 }
37248 return needApparentType ? getApparentType(type) : type;
37249 }
37250 function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
37251 var mapper;
37252 var members;
37253 var callSignatures;
37254 var constructSignatures;
37255 var stringIndexInfo;
37256 var numberIndexInfo;
37257 if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
37258 mapper = identityMapper;
37259 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
37260 callSignatures = source.declaredCallSignatures;
37261 constructSignatures = source.declaredConstructSignatures;
37262 stringIndexInfo = source.declaredStringIndexInfo;
37263 numberIndexInfo = source.declaredNumberIndexInfo;
37264 }
37265 else {
37266 mapper = createTypeMapper(typeParameters, typeArguments);
37267 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
37268 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
37269 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
37270 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
37271 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
37272 }
37273 var baseTypes = getBaseTypes(source);
37274 if (baseTypes.length) {
37275 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
37276 members = ts.createSymbolTable(source.declaredProperties);
37277 }
37278 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37279 var thisArgument = ts.lastOrUndefined(typeArguments);
37280 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
37281 var baseType = baseTypes_1[_i];
37282 var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
37283 addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
37284 callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
37285 constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
37286 if (!stringIndexInfo) {
37287 stringIndexInfo = instantiatedBaseType === anyType ?
37288 createIndexInfo(anyType, /*isReadonly*/ false) :
37289 getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
37290 }
37291 numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
37292 }
37293 }
37294 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37295 }
37296 function resolveClassOrInterfaceMembers(type) {
37297 resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
37298 }
37299 function resolveTypeReferenceMembers(type) {
37300 var source = resolveDeclaredMembers(type.target);
37301 var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
37302 var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ?
37303 type.typeArguments : ts.concatenate(type.typeArguments, [type]);
37304 resolveObjectTypeMembers(type, source, typeParameters, typeArguments);
37305 }
37306 function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) {
37307 var sig = new Signature(checker);
37308 sig.declaration = declaration;
37309 sig.typeParameters = typeParameters;
37310 sig.parameters = parameters;
37311 sig.thisParameter = thisParameter;
37312 sig.resolvedReturnType = resolvedReturnType;
37313 sig.resolvedTypePredicate = resolvedTypePredicate;
37314 sig.minArgumentCount = minArgumentCount;
37315 sig.hasRestParameter = hasRestParameter;
37316 sig.hasLiteralTypes = hasLiteralTypes;
37317 sig.target = undefined;
37318 sig.mapper = undefined;
37319 return sig;
37320 }
37321 function cloneSignature(sig) {
37322 var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
37323 /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes);
37324 result.target = sig.target;
37325 result.mapper = sig.mapper;
37326 return result;
37327 }
37328 function createUnionSignature(signature, unionSignatures) {
37329 var result = cloneSignature(signature);
37330 result.unionSignatures = unionSignatures;
37331 result.target = undefined;
37332 result.mapper = undefined;
37333 return result;
37334 }
37335 function getExpandedParameters(sig) {
37336 if (sig.hasRestParameter) {
37337 var restIndex_1 = sig.parameters.length - 1;
37338 var restParameter = sig.parameters[restIndex_1];
37339 var restType = getTypeOfSymbol(restParameter);
37340 if (isTupleType(restType)) {
37341 var elementTypes = restType.typeArguments || ts.emptyArray;
37342 var minLength_1 = restType.target.minLength;
37343 var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1;
37344 var restParams = ts.map(elementTypes, function (t, i) {
37345 var name = getParameterNameAtPosition(sig, restIndex_1 + i);
37346 var checkFlags = i === tupleRestIndex_1 ? 16384 /* RestParameter */ :
37347 i >= minLength_1 ? 8192 /* OptionalParameter */ : 0;
37348 var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
37349 symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t;
37350 return symbol;
37351 });
37352 return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams);
37353 }
37354 }
37355 return sig.parameters;
37356 }
37357 function getDefaultConstructSignatures(classType) {
37358 var baseConstructorType = getBaseConstructorTypeOfClass(classType);
37359 var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
37360 if (baseSignatures.length === 0) {
37361 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217
37362 }
37363 var baseTypeNode = getBaseTypeNodeOfClass(classType);
37364 var isJavaScript = ts.isInJSFile(baseTypeNode);
37365 var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
37366 var typeArgCount = ts.length(typeArguments);
37367 var result = [];
37368 for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
37369 var baseSig = baseSignatures_1[_i];
37370 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
37371 var typeParamCount = ts.length(baseSig.typeParameters);
37372 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
37373 var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
37374 sig.typeParameters = classType.localTypeParameters;
37375 sig.resolvedReturnType = classType;
37376 result.push(sig);
37377 }
37378 }
37379 return result;
37380 }
37381 function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
37382 for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
37383 var s = signatureList_1[_i];
37384 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
37385 return s;
37386 }
37387 }
37388 }
37389 function findMatchingSignatures(signatureLists, signature, listIndex) {
37390 if (signature.typeParameters) {
37391 // We require an exact match for generic signatures, so we only return signatures from the first
37392 // signature list and only if they have exact matches in the other signature lists.
37393 if (listIndex > 0) {
37394 return undefined;
37395 }
37396 for (var i = 1; i < signatureLists.length; i++) {
37397 if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
37398 return undefined;
37399 }
37400 }
37401 return [signature];
37402 }
37403 var result;
37404 for (var i = 0; i < signatureLists.length; i++) {
37405 // Allow matching non-generic signatures to have excess parameters and different return types
37406 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true);
37407 if (!match) {
37408 return undefined;
37409 }
37410 result = ts.appendIfUnique(result, match);
37411 }
37412 return result;
37413 }
37414 // The signatures of a union type are those signatures that are present in each of the constituent types.
37415 // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
37416 // parameters and may differ in return types. When signatures differ in return types, the resulting return
37417 // type is the union of the constituent return types.
37418 function getUnionSignatures(signatureLists) {
37419 var result;
37420 var indexWithLengthOverOne;
37421 for (var i = 0; i < signatureLists.length; i++) {
37422 if (signatureLists[i].length === 0)
37423 return ts.emptyArray;
37424 if (signatureLists[i].length > 1) {
37425 indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
37426 }
37427 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
37428 var signature = _a[_i];
37429 // Only process signatures with parameter lists that aren't already in the result list
37430 if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) {
37431 var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
37432 if (unionSignatures) {
37433 var s = signature;
37434 // Union the result types when more than one signature matches
37435 if (unionSignatures.length > 1) {
37436 var thisParameter = signature.thisParameter;
37437 if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) {
37438 // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do
37439 var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */);
37440 thisParameter = createSymbolWithType(signature.thisParameter, thisType);
37441 }
37442 s = createUnionSignature(signature, unionSignatures);
37443 s.thisParameter = thisParameter;
37444 }
37445 (result || (result = [])).push(s);
37446 }
37447 }
37448 }
37449 }
37450 if (!ts.length(result) && indexWithLengthOverOne !== -1) {
37451 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
37452 // signature that handles all over them. We only do this when there are overloads in only one constituent.
37453 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
37454 // signatures from the type, whose ordering would be non-obvious)
37455 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
37456 var results = masterList.slice();
37457 var _loop_5 = function (signatures) {
37458 if (signatures !== masterList) {
37459 var signature_1 = signatures[0];
37460 ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
37461 results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
37462 if (!results) {
37463 return "break";
37464 }
37465 }
37466 };
37467 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
37468 var signatures = signatureLists_1[_b];
37469 var state_2 = _loop_5(signatures);
37470 if (state_2 === "break")
37471 break;
37472 }
37473 result = results;
37474 }
37475 return result || ts.emptyArray;
37476 }
37477 function combineUnionThisParam(left, right) {
37478 if (!left || !right) {
37479 return left || right;
37480 }
37481 // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
37482 // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
37483 // permissive when calling, for now, we'll union the `this` types just like the overlapping-union-signature check does
37484 var thisType = getUnionType([getTypeOfSymbol(left), getTypeOfSymbol(right)], 2 /* Subtype */);
37485 return createSymbolWithType(left, thisType);
37486 }
37487 function combineUnionParameters(left, right) {
37488 var longest = getParameterCount(left) >= getParameterCount(right) ? left : right;
37489 var shorter = longest === left ? right : left;
37490 var longestCount = getParameterCount(longest);
37491 var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
37492 var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
37493 var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
37494 for (var i = 0; i < longestCount; i++) {
37495 var longestParamType = tryGetTypeAtPosition(longest, i);
37496 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
37497 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
37498 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
37499 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
37500 var leftName = getParameterNameAtPosition(left, i);
37501 var rightName = getParameterNameAtPosition(right, i);
37502 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), leftName === rightName ? leftName : "arg" + i);
37503 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
37504 params[i] = paramSymbol;
37505 }
37506 if (needsExtraRestElement) {
37507 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
37508 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
37509 params[longestCount] = restParamSymbol;
37510 }
37511 return params;
37512 }
37513 function combineSignaturesOfUnionMembers(left, right) {
37514 var declaration = left.declaration;
37515 var params = combineUnionParameters(left, right);
37516 var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
37517 var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
37518 var hasRestParam = left.hasRestParameter || right.hasRestParameter;
37519 var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes;
37520 var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params,
37521 /*resolvedReturnType*/ undefined,
37522 /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes);
37523 result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
37524 return result;
37525 }
37526 function getUnionIndexInfo(types, kind) {
37527 var indexTypes = [];
37528 var isAnyReadonly = false;
37529 for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
37530 var type = types_2[_i];
37531 var indexInfo = getIndexInfoOfType(type, kind);
37532 if (!indexInfo) {
37533 return undefined;
37534 }
37535 indexTypes.push(indexInfo.type);
37536 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
37537 }
37538 return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
37539 }
37540 function resolveUnionTypeMembers(type) {
37541 // The members and properties collections are empty for union types. To get all properties of a union
37542 // type use getPropertiesOfType (only the language service uses this).
37543 var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
37544 var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
37545 var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
37546 var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
37547 setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37548 }
37549 function intersectTypes(type1, type2) {
37550 return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
37551 }
37552 function intersectIndexInfos(info1, info2) {
37553 return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
37554 }
37555 function unionSpreadIndexInfos(info1, info2) {
37556 return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
37557 }
37558 function findMixins(types) {
37559 var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
37560 var mixinFlags = ts.map(types, isMixinConstructorType);
37561 if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
37562 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
37563 mixinFlags[firstMixinIndex] = false;
37564 }
37565 return mixinFlags;
37566 }
37567 function includeMixinType(type, types, mixinFlags, index) {
37568 var mixedTypes = [];
37569 for (var i = 0; i < types.length; i++) {
37570 if (i === index) {
37571 mixedTypes.push(type);
37572 }
37573 else if (mixinFlags[i]) {
37574 mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
37575 }
37576 }
37577 return getIntersectionType(mixedTypes);
37578 }
37579 function resolveIntersectionTypeMembers(type) {
37580 // The members and properties collections are empty for intersection types. To get all properties of an
37581 // intersection type use getPropertiesOfType (only the language service uses this).
37582 var callSignatures = ts.emptyArray;
37583 var constructSignatures = ts.emptyArray;
37584 var stringIndexInfo;
37585 var numberIndexInfo;
37586 var types = type.types;
37587 var mixinFlags = findMixins(types);
37588 var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
37589 var _loop_6 = function (i) {
37590 var t = type.types[i];
37591 // When an intersection type contains mixin constructor types, the construct signatures from
37592 // those types are discarded and their return types are mixed into the return types of all
37593 // other construct signatures in the intersection type. For example, the intersection type
37594 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
37595 // 'new(s: string) => A & B'.
37596 if (!mixinFlags[i]) {
37597 var signatures = getSignaturesOfType(t, 1 /* Construct */);
37598 if (signatures.length && mixinCount > 0) {
37599 signatures = ts.map(signatures, function (s) {
37600 var clone = cloneSignature(s);
37601 clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
37602 return clone;
37603 });
37604 }
37605 constructSignatures = ts.concatenate(constructSignatures, signatures);
37606 }
37607 callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */));
37608 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
37609 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
37610 };
37611 for (var i = 0; i < types.length; i++) {
37612 _loop_6(i);
37613 }
37614 setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37615 }
37616 /**
37617 * Converts an AnonymousType to a ResolvedType.
37618 */
37619 function resolveAnonymousTypeMembers(type) {
37620 var symbol = type.symbol;
37621 if (type.target) {
37622 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
37623 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
37624 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
37625 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
37626 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
37627 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
37628 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37629 }
37630 else if (symbol.flags & 2048 /* TypeLiteral */) {
37631 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
37632 var members = getMembersOfSymbol(symbol);
37633 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
37634 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
37635 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
37636 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
37637 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37638 }
37639 else {
37640 // Combinations of function, class, enum and module
37641 var members = emptySymbols;
37642 var stringIndexInfo = void 0;
37643 if (symbol.exports) {
37644 members = getExportsOfSymbol(symbol);
37645 if (symbol === globalThisSymbol) {
37646 var varsOnly_1 = ts.createMap();
37647 members.forEach(function (p) {
37648 if (!(p.flags & 418 /* BlockScoped */)) {
37649 varsOnly_1.set(p.escapedName, p);
37650 }
37651 });
37652 members = varsOnly_1;
37653 }
37654 }
37655 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
37656 if (symbol.flags & 32 /* Class */) {
37657 var classType = getDeclaredTypeOfClassOrInterface(symbol);
37658 var baseConstructorType = getBaseConstructorTypeOfClass(classType);
37659 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
37660 members = ts.createSymbolTable(getNamedMembers(members));
37661 addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
37662 }
37663 else if (baseConstructorType === anyType) {
37664 stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
37665 }
37666 }
37667 var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined;
37668 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
37669 // We resolve the members before computing the signatures because a signature may use
37670 // typeof with a qualified name expression that circularly references the type we are
37671 // in the process of resolving (see issue #6072). The temporarily empty signature list
37672 // will never be observed because a qualified name can't reference signatures.
37673 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
37674 type.callSignatures = getSignaturesOfSymbol(symbol);
37675 type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); });
37676 }
37677 // And likewise for construct signatures for classes
37678 if (symbol.flags & 32 /* Class */) {
37679 var classType = getDeclaredTypeOfClassOrInterface(symbol);
37680 var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */));
37681 if (!constructSignatures.length) {
37682 constructSignatures = getDefaultConstructSignatures(classType);
37683 }
37684 type.constructSignatures = constructSignatures;
37685 }
37686 }
37687 }
37688 function resolveReverseMappedTypeMembers(type) {
37689 var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
37690 var modifiers = getMappedTypeModifiers(type.mappedType);
37691 var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
37692 var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
37693 var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
37694 var members = ts.createSymbolTable();
37695 for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
37696 var prop = _a[_i];
37697 var checkFlags = 4096 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
37698 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
37699 inferredProp.declarations = prop.declarations;
37700 inferredProp.nameType = prop.nameType;
37701 inferredProp.propertyType = getTypeOfSymbol(prop);
37702 inferredProp.mappedType = type.mappedType;
37703 inferredProp.constraintType = type.constraintType;
37704 members.set(prop.escapedName, inferredProp);
37705 }
37706 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
37707 }
37708 // Return the lower bound of the key type in a mapped type. Intuitively, the lower
37709 // bound includes those keys that are known to always be present, for example because
37710 // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
37711 function getLowerBoundOfKeyType(type) {
37712 if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) {
37713 return type;
37714 }
37715 if (type.flags & 4194304 /* Index */) {
37716 return getIndexType(getApparentType(type.type));
37717 }
37718 if (type.flags & 16777216 /* Conditional */) {
37719 return getLowerBoundOfConditionalType(type);
37720 }
37721 if (type.flags & 1048576 /* Union */) {
37722 return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
37723 }
37724 if (type.flags & 2097152 /* Intersection */) {
37725 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
37726 }
37727 return neverType;
37728 }
37729 function getLowerBoundOfConditionalType(type) {
37730 if (type.root.isDistributive) {
37731 var constraint = getLowerBoundOfKeyType(type.checkType);
37732 if (constraint !== type.checkType) {
37733 var mapper = makeUnaryTypeMapper(type.root.checkType, constraint);
37734 return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
37735 }
37736 }
37737 return type;
37738 }
37739 /** Resolve the members of a mapped type { [P in K]: T } */
37740 function resolveMappedTypeMembers(type) {
37741 var members = ts.createSymbolTable();
37742 var stringIndexInfo;
37743 var numberIndexInfo;
37744 // Resolve upfront such that recursive references see an empty object type.
37745 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
37746 // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
37747 // and T as the template type.
37748 var typeParameter = getTypeParameterFromMappedType(type);
37749 var constraintType = getConstraintTypeFromMappedType(type);
37750 var templateType = getTemplateTypeFromMappedType(type.target || type);
37751 var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
37752 var templateModifiers = getMappedTypeModifiers(type);
37753 var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
37754 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
37755 // We have a { [P in keyof T]: X }
37756 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
37757 var prop = _a[_i];
37758 addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
37759 }
37760 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
37761 addMemberForKeyType(stringType);
37762 }
37763 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
37764 addMemberForKeyType(numberType);
37765 }
37766 }
37767 else {
37768 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
37769 }
37770 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
37771 function addMemberForKeyType(t) {
37772 // Create a mapper from T to the current iteration type constituent. Then, if the
37773 // mapped type is itself an instantiated type, combine the iteration mapper with the
37774 // instantiation mapper.
37775 var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t]));
37776 var propType = instantiateType(templateType, templateMapper);
37777 // If the current iteration type constituent is a string literal type, create a property.
37778 // Otherwise, for type string create a string index signature.
37779 if (isTypeUsableAsPropertyName(t)) {
37780 var propName = getPropertyNameFromType(t);
37781 var modifiersProp = getPropertyOfType(modifiersType, propName);
37782 var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
37783 !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
37784 var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
37785 !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
37786 var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0);
37787 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
37788 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
37789 // mode, if the underlying property is optional we remove 'undefined' from the type.
37790 prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) :
37791 strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
37792 propType;
37793 if (modifiersProp) {
37794 prop.syntheticOrigin = modifiersProp;
37795 prop.declarations = modifiersProp.declarations;
37796 }
37797 prop.nameType = t;
37798 members.set(propName, prop);
37799 }
37800 else if (t.flags & (1 /* Any */ | 4 /* String */)) {
37801 stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
37802 }
37803 else if (t.flags & 8 /* Number */) {
37804 numberIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
37805 }
37806 }
37807 }
37808 function getTypeParameterFromMappedType(type) {
37809 return type.typeParameter ||
37810 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
37811 }
37812 function getConstraintTypeFromMappedType(type) {
37813 return type.constraintType ||
37814 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
37815 }
37816 function getTemplateTypeFromMappedType(type) {
37817 return type.templateType ||
37818 (type.templateType = type.declaration.type ?
37819 instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) :
37820 errorType);
37821 }
37822 function getConstraintDeclarationForMappedType(type) {
37823 return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
37824 }
37825 function isMappedTypeWithKeyofConstraintDeclaration(type) {
37826 var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
37827 return constraintDeclaration.kind === 179 /* TypeOperator */ &&
37828 constraintDeclaration.operator === 129 /* KeyOfKeyword */;
37829 }
37830 function getModifiersTypeFromMappedType(type) {
37831 if (!type.modifiersType) {
37832 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
37833 // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
37834 // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
37835 // 'keyof T' to a literal union type and we can't recover T from that type.
37836 type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper);
37837 }
37838 else {
37839 // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
37840 // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
37841 // the modifiers type is T. Otherwise, the modifiers type is {}.
37842 var declaredType = getTypeFromMappedTypeNode(type.declaration);
37843 var constraint = getConstraintTypeFromMappedType(declaredType);
37844 var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
37845 type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType;
37846 }
37847 }
37848 return type.modifiersType;
37849 }
37850 function getMappedTypeModifiers(type) {
37851 var declaration = type.declaration;
37852 return (declaration.readonlyToken ? declaration.readonlyToken.kind === 39 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
37853 (declaration.questionToken ? declaration.questionToken.kind === 39 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
37854 }
37855 function getMappedTypeOptionality(type) {
37856 var modifiers = getMappedTypeModifiers(type);
37857 return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
37858 }
37859 function getCombinedMappedTypeOptionality(type) {
37860 var optionality = getMappedTypeOptionality(type);
37861 var modifiersType = getModifiersTypeFromMappedType(type);
37862 return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
37863 }
37864 function isPartialMappedType(type) {
37865 return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
37866 }
37867 function isGenericMappedType(type) {
37868 return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
37869 }
37870 function resolveStructuredTypeMembers(type) {
37871 if (!type.members) {
37872 if (type.flags & 524288 /* Object */) {
37873 if (type.objectFlags & 4 /* Reference */) {
37874 resolveTypeReferenceMembers(type);
37875 }
37876 else if (type.objectFlags & 3 /* ClassOrInterface */) {
37877 resolveClassOrInterfaceMembers(type);
37878 }
37879 else if (type.objectFlags & 2048 /* ReverseMapped */) {
37880 resolveReverseMappedTypeMembers(type);
37881 }
37882 else if (type.objectFlags & 16 /* Anonymous */) {
37883 resolveAnonymousTypeMembers(type);
37884 }
37885 else if (type.objectFlags & 32 /* Mapped */) {
37886 resolveMappedTypeMembers(type);
37887 }
37888 }
37889 else if (type.flags & 1048576 /* Union */) {
37890 resolveUnionTypeMembers(type);
37891 }
37892 else if (type.flags & 2097152 /* Intersection */) {
37893 resolveIntersectionTypeMembers(type);
37894 }
37895 }
37896 return type;
37897 }
37898 /** Return properties of an object type or an empty array for other types */
37899 function getPropertiesOfObjectType(type) {
37900 if (type.flags & 524288 /* Object */) {
37901 return resolveStructuredTypeMembers(type).properties;
37902 }
37903 return ts.emptyArray;
37904 }
37905 /** If the given type is an object type and that type has a property by the given name,
37906 * return the symbol for that property. Otherwise return undefined.
37907 */
37908 function getPropertyOfObjectType(type, name) {
37909 if (type.flags & 524288 /* Object */) {
37910 var resolved = resolveStructuredTypeMembers(type);
37911 var symbol = resolved.members.get(name);
37912 if (symbol && symbolIsValue(symbol)) {
37913 return symbol;
37914 }
37915 }
37916 }
37917 function getPropertiesOfUnionOrIntersectionType(type) {
37918 if (!type.resolvedProperties) {
37919 var members = ts.createSymbolTable();
37920 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
37921 var current = _a[_i];
37922 for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
37923 var prop = _c[_b];
37924 if (!members.has(prop.escapedName)) {
37925 var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
37926 if (combinedProp) {
37927 members.set(prop.escapedName, combinedProp);
37928 }
37929 }
37930 }
37931 // The properties of a union type are those that are present in all constituent types, so
37932 // we only need to check the properties of the first type
37933 if (type.flags & 1048576 /* Union */) {
37934 break;
37935 }
37936 }
37937 type.resolvedProperties = getNamedMembers(members);
37938 }
37939 return type.resolvedProperties;
37940 }
37941 function getPropertiesOfType(type) {
37942 type = getApparentType(type);
37943 return type.flags & 3145728 /* UnionOrIntersection */ ?
37944 getPropertiesOfUnionOrIntersectionType(type) :
37945 getPropertiesOfObjectType(type);
37946 }
37947 function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
37948 var list = obj.properties;
37949 return list.some(function (property) {
37950 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
37951 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
37952 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
37953 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
37954 });
37955 }
37956 function getAllPossiblePropertiesOfTypes(types) {
37957 var unionType = getUnionType(types);
37958 if (!(unionType.flags & 1048576 /* Union */)) {
37959 return getAugmentedPropertiesOfType(unionType);
37960 }
37961 var props = ts.createSymbolTable();
37962 for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
37963 var memberType = types_3[_i];
37964 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
37965 var escapedName = _b[_a].escapedName;
37966 if (!props.has(escapedName)) {
37967 var prop = createUnionOrIntersectionProperty(unionType, escapedName);
37968 // May be undefined if the property is private
37969 if (prop)
37970 props.set(escapedName, prop);
37971 }
37972 }
37973 }
37974 return ts.arrayFrom(props.values());
37975 }
37976 function getConstraintOfType(type) {
37977 return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
37978 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
37979 type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
37980 getBaseConstraintOfType(type);
37981 }
37982 function getConstraintOfTypeParameter(typeParameter) {
37983 return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
37984 }
37985 function getConstraintOfIndexedAccess(type) {
37986 return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
37987 }
37988 function getConstraintFromIndexedAccess(type) {
37989 var objectType = getConstraintOfType(type.objectType) || type.objectType;
37990 if (objectType !== type.objectType) {
37991 var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType);
37992 if (constraint && constraint !== errorType) {
37993 return constraint;
37994 }
37995 }
37996 var baseConstraint = getBaseConstraintOfType(type);
37997 return baseConstraint && baseConstraint !== type ? baseConstraint : undefined;
37998 }
37999 function getDefaultConstraintOfConditionalType(type) {
38000 if (!type.resolvedDefaultConstraint) {
38001 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
38002 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
38003 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
38004 // in effect treating `any` like `never` rather than `unknown` in this location.
38005 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
38006 var falseConstraint = type.falseType;
38007 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
38008 }
38009 return type.resolvedDefaultConstraint;
38010 }
38011 function getConstraintOfDistributiveConditionalType(type) {
38012 // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
38013 // type parameter. If so, create an instantiation of the conditional type where T is replaced
38014 // with its constraint. We do this because if the constraint is a union type it will be distributed
38015 // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
38016 // removes 'undefined' from T.
38017 // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
38018 // as the constraint for all type params (check type included) have been replace with `unknown`, which
38019 // is going to produce even more false positive/negative results than the distribute constraint already does.
38020 // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
38021 // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
38022 // likely doesn't need to exist.
38023 if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
38024 var simplified = getSimplifiedType(type.checkType);
38025 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
38026 if (constraint && constraint !== type.checkType) {
38027 var mapper = makeUnaryTypeMapper(type.root.checkType, constraint);
38028 var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
38029 if (!(instantiated.flags & 131072 /* Never */)) {
38030 return instantiated;
38031 }
38032 }
38033 }
38034 return undefined;
38035 }
38036 function getConstraintFromConditionalType(type) {
38037 return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
38038 }
38039 function getConstraintOfConditionalType(type) {
38040 return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
38041 }
38042 function getUnionConstraintOfIntersection(type, targetIsUnion) {
38043 var constraints;
38044 var hasDisjointDomainType = false;
38045 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
38046 var t = _a[_i];
38047 if (t.flags & 63176704 /* Instantiable */) {
38048 // We keep following constraints as long as we have an instantiable type that is known
38049 // not to be circular or infinite (hence we stop on index access types).
38050 var constraint = getConstraintOfType(t);
38051 while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
38052 constraint = getConstraintOfType(constraint);
38053 }
38054 if (constraint) {
38055 // A constraint that isn't a union type implies that the final type would be a non-union
38056 // type as well. Since non-union constraints are of no interest, we can exit here.
38057 if (!(constraint.flags & 1048576 /* Union */)) {
38058 return undefined;
38059 }
38060 constraints = ts.append(constraints, constraint);
38061 }
38062 }
38063 else if (t.flags & 67238908 /* DisjointDomains */) {
38064 hasDisjointDomainType = true;
38065 }
38066 }
38067 // If the target is a union type or if we are intersecting with types belonging to one of the
38068 // disjoint domans, we may end up producing a constraint that hasn't been examined before.
38069 if (constraints && (targetIsUnion || hasDisjointDomainType)) {
38070 if (hasDisjointDomainType) {
38071 // We add any types belong to one of the disjoint domans because they might cause the final
38072 // intersection operation to reduce the union constraints.
38073 for (var _b = 0, _c = type.types; _b < _c.length; _b++) {
38074 var t = _c[_b];
38075 if (t.flags & 67238908 /* DisjointDomains */) {
38076 constraints = ts.append(constraints, t);
38077 }
38078 }
38079 }
38080 return getIntersectionType(constraints);
38081 }
38082 return undefined;
38083 }
38084 function getBaseConstraintOfType(type) {
38085 if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) {
38086 var constraint = getResolvedBaseConstraint(type);
38087 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
38088 }
38089 return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
38090 }
38091 /**
38092 * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
38093 * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
38094 */
38095 function getBaseConstraintOrType(type) {
38096 return getBaseConstraintOfType(type) || type;
38097 }
38098 function hasNonCircularBaseConstraint(type) {
38099 return getResolvedBaseConstraint(type) !== circularConstraintType;
38100 }
38101 /**
38102 * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
38103 * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
38104 * circularly references the type variable.
38105 */
38106 function getResolvedBaseConstraint(type) {
38107 var nonTerminating = false;
38108 return type.resolvedBaseConstraint ||
38109 (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
38110 function getImmediateBaseConstraint(t) {
38111 if (!t.immediateBaseConstraint) {
38112 if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
38113 return circularConstraintType;
38114 }
38115 if (constraintDepth >= 50) {
38116 // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
38117 // very high likelyhood we're dealing with an infinite generic type that perpetually generates
38118 // new type identities as we descend into it. We stop the recursion here and mark this type
38119 // and the outer types as having circular constraints.
38120 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
38121 nonTerminating = true;
38122 return t.immediateBaseConstraint = noConstraintType;
38123 }
38124 constraintDepth++;
38125 var result = computeBaseConstraint(getSimplifiedType(t));
38126 constraintDepth--;
38127 if (!popTypeResolution()) {
38128 if (t.flags & 262144 /* TypeParameter */) {
38129 var errorNode = getConstraintDeclaration(t);
38130 if (errorNode) {
38131 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
38132 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
38133 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
38134 }
38135 }
38136 }
38137 result = circularConstraintType;
38138 }
38139 if (nonTerminating) {
38140 result = circularConstraintType;
38141 }
38142 t.immediateBaseConstraint = result || noConstraintType;
38143 }
38144 return t.immediateBaseConstraint;
38145 }
38146 function getBaseConstraint(t) {
38147 var c = getImmediateBaseConstraint(t);
38148 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
38149 }
38150 function computeBaseConstraint(t) {
38151 if (t.flags & 262144 /* TypeParameter */) {
38152 var constraint = getConstraintFromTypeParameter(t);
38153 return t.isThisType || !constraint ?
38154 constraint :
38155 getBaseConstraint(constraint);
38156 }
38157 if (t.flags & 3145728 /* UnionOrIntersection */) {
38158 var types = t.types;
38159 var baseTypes = [];
38160 for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
38161 var type_3 = types_4[_i];
38162 var baseType = getBaseConstraint(type_3);
38163 if (baseType) {
38164 baseTypes.push(baseType);
38165 }
38166 }
38167 return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
38168 t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
38169 undefined;
38170 }
38171 if (t.flags & 4194304 /* Index */) {
38172 return keyofConstraintType;
38173 }
38174 if (t.flags & 8388608 /* IndexedAccess */) {
38175 var baseObjectType = getBaseConstraint(t.objectType);
38176 var baseIndexType = getBaseConstraint(t.indexType);
38177 var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined;
38178 return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined;
38179 }
38180 if (t.flags & 16777216 /* Conditional */) {
38181 var constraint = getConstraintFromConditionalType(t);
38182 constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
38183 var result = constraint && getBaseConstraint(constraint);
38184 constraintDepth--;
38185 return result;
38186 }
38187 if (t.flags & 33554432 /* Substitution */) {
38188 return getBaseConstraint(t.substitute);
38189 }
38190 return t;
38191 }
38192 }
38193 function getApparentTypeOfIntersectionType(type) {
38194 return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
38195 }
38196 function getResolvedTypeParameterDefault(typeParameter) {
38197 if (!typeParameter.default) {
38198 if (typeParameter.target) {
38199 var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
38200 typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
38201 }
38202 else {
38203 // To block recursion, set the initial value to the resolvingDefaultType.
38204 typeParameter.default = resolvingDefaultType;
38205 var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
38206 var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
38207 if (typeParameter.default === resolvingDefaultType) {
38208 // If we have not been called recursively, set the correct default type.
38209 typeParameter.default = defaultType;
38210 }
38211 }
38212 }
38213 else if (typeParameter.default === resolvingDefaultType) {
38214 // If we are called recursively for this type parameter, mark the default as circular.
38215 typeParameter.default = circularConstraintType;
38216 }
38217 return typeParameter.default;
38218 }
38219 /**
38220 * Gets the default type for a type parameter.
38221 *
38222 * If the type parameter is the result of an instantiation, this gets the instantiated
38223 * default type of its target. If the type parameter has no default type or the default is
38224 * circular, `undefined` is returned.
38225 */
38226 function getDefaultFromTypeParameter(typeParameter) {
38227 var defaultType = getResolvedTypeParameterDefault(typeParameter);
38228 return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
38229 }
38230 function hasNonCircularTypeParameterDefault(typeParameter) {
38231 return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
38232 }
38233 /**
38234 * Indicates whether the declaration of a typeParameter has a default type.
38235 */
38236 function hasTypeParameterDefault(typeParameter) {
38237 return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
38238 }
38239 function getApparentTypeOfMappedType(type) {
38240 return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
38241 }
38242 function getResolvedApparentTypeOfMappedType(type) {
38243 var typeVariable = getHomomorphicTypeVariable(type);
38244 if (typeVariable) {
38245 var constraint = getConstraintOfTypeParameter(typeVariable);
38246 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
38247 var mapper = makeUnaryTypeMapper(typeVariable, constraint);
38248 return instantiateType(type, combineTypeMappers(mapper, type.mapper));
38249 }
38250 }
38251 return type;
38252 }
38253 /**
38254 * For a type parameter, return the base constraint of the type parameter. For the string, number,
38255 * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
38256 * type itself. Note that the apparent type of a union type is the union type itself.
38257 */
38258 function getApparentType(type) {
38259 var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type;
38260 return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
38261 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
38262 t.flags & 132 /* StringLike */ ? globalStringType :
38263 t.flags & 296 /* NumberLike */ ? globalNumberType :
38264 t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ESNext */) :
38265 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
38266 t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
38267 t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
38268 t.flags & 4194304 /* Index */ ? keyofConstraintType :
38269 t;
38270 }
38271 function createUnionOrIntersectionProperty(containingType, name) {
38272 var propSet = ts.createMap();
38273 var indexTypes;
38274 var isUnion = containingType.flags & 1048576 /* Union */;
38275 var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0;
38276 // Flags we want to propagate to the result if they exist in all source symbols
38277 var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */;
38278 var syntheticFlag = 4 /* SyntheticMethod */;
38279 var checkFlags = 0;
38280 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
38281 var current = _a[_i];
38282 var type = getApparentType(current);
38283 if (type !== errorType) {
38284 var prop = getPropertyOfType(type, name);
38285 var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
38286 if (prop && !(modifiers & excludeModifiers)) {
38287 commonFlags &= prop.flags;
38288 var id = "" + getSymbolId(prop);
38289 if (!propSet.has(id)) {
38290 propSet.set(id, prop);
38291 }
38292 checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
38293 (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) |
38294 (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) |
38295 (modifiers & 8 /* Private */ ? 512 /* ContainsPrivate */ : 0) |
38296 (modifiers & 32 /* Static */ ? 1024 /* ContainsStatic */ : 0);
38297 if (!isPrototypeProperty(prop)) {
38298 syntheticFlag = 2 /* SyntheticProperty */;
38299 }
38300 }
38301 else if (isUnion) {
38302 var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
38303 if (indexInfo) {
38304 checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0;
38305 indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
38306 }
38307 else {
38308 checkFlags |= 16 /* Partial */;
38309 }
38310 }
38311 }
38312 }
38313 if (!propSet.size) {
38314 return undefined;
38315 }
38316 var props = ts.arrayFrom(propSet.values());
38317 if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) {
38318 return props[0];
38319 }
38320 var declarations;
38321 var firstType;
38322 var nameType;
38323 var propTypes = [];
38324 var firstValueDeclaration;
38325 var hasNonUniformValueDeclaration = false;
38326 for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
38327 var prop = props_1[_b];
38328 if (!firstValueDeclaration) {
38329 firstValueDeclaration = prop.valueDeclaration;
38330 }
38331 else if (prop.valueDeclaration !== firstValueDeclaration) {
38332 hasNonUniformValueDeclaration = true;
38333 }
38334 declarations = ts.addRange(declarations, prop.declarations);
38335 var type = getTypeOfSymbol(prop);
38336 if (!firstType) {
38337 firstType = type;
38338 nameType = prop.nameType;
38339 }
38340 else if (type !== firstType) {
38341 checkFlags |= 32 /* HasNonUniformType */;
38342 }
38343 if (isLiteralType(type)) {
38344 checkFlags |= 64 /* HasLiteralType */;
38345 }
38346 propTypes.push(type);
38347 }
38348 ts.addRange(propTypes, indexTypes);
38349 var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags);
38350 result.containingType = containingType;
38351 if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
38352 result.valueDeclaration = firstValueDeclaration;
38353 // Inherit information about parent type.
38354 if (firstValueDeclaration.symbol.parent) {
38355 result.parent = firstValueDeclaration.symbol.parent;
38356 }
38357 }
38358 result.declarations = declarations;
38359 result.nameType = nameType;
38360 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
38361 return result;
38362 }
38363 // Return the symbol for a given property in a union or intersection type, or undefined if the property
38364 // does not exist in any constituent type. Note that the returned property may only be present in some
38365 // constituents, in which case the isPartial flag is set when the containing type is union type. We need
38366 // these partial properties when identifying discriminant properties, but otherwise they are filtered out
38367 // and do not appear to be present in the union type.
38368 function getUnionOrIntersectionProperty(type, name) {
38369 var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
38370 var property = properties.get(name);
38371 if (!property) {
38372 property = createUnionOrIntersectionProperty(type, name);
38373 if (property) {
38374 properties.set(name, property);
38375 }
38376 }
38377 return property;
38378 }
38379 function getPropertyOfUnionOrIntersectionType(type, name) {
38380 var property = getUnionOrIntersectionProperty(type, name);
38381 // We need to filter out partial properties in union types
38382 return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined;
38383 }
38384 /**
38385 * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
38386 * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
38387 * Object and Function as appropriate.
38388 *
38389 * @param type a type to look up property from
38390 * @param name a name of property to look up in a given type
38391 */
38392 function getPropertyOfType(type, name) {
38393 type = getApparentType(type);
38394 if (type.flags & 524288 /* Object */) {
38395 var resolved = resolveStructuredTypeMembers(type);
38396 var symbol = resolved.members.get(name);
38397 if (symbol && symbolIsValue(symbol)) {
38398 return symbol;
38399 }
38400 var functionType = resolved === anyFunctionType ? globalFunctionType :
38401 resolved.callSignatures.length ? globalCallableFunctionType :
38402 resolved.constructSignatures.length ? globalNewableFunctionType :
38403 undefined;
38404 if (functionType) {
38405 var symbol_1 = getPropertyOfObjectType(functionType, name);
38406 if (symbol_1) {
38407 return symbol_1;
38408 }
38409 }
38410 return getPropertyOfObjectType(globalObjectType, name);
38411 }
38412 if (type.flags & 3145728 /* UnionOrIntersection */) {
38413 return getPropertyOfUnionOrIntersectionType(type, name);
38414 }
38415 return undefined;
38416 }
38417 function getSignaturesOfStructuredType(type, kind) {
38418 if (type.flags & 3670016 /* StructuredType */) {
38419 var resolved = resolveStructuredTypeMembers(type);
38420 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
38421 }
38422 return ts.emptyArray;
38423 }
38424 /**
38425 * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
38426 * maps primitive types and type parameters are to their apparent types.
38427 */
38428 function getSignaturesOfType(type, kind) {
38429 return getSignaturesOfStructuredType(getApparentType(type), kind);
38430 }
38431 function getIndexInfoOfStructuredType(type, kind) {
38432 if (type.flags & 3670016 /* StructuredType */) {
38433 var resolved = resolveStructuredTypeMembers(type);
38434 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
38435 }
38436 }
38437 function getIndexTypeOfStructuredType(type, kind) {
38438 var info = getIndexInfoOfStructuredType(type, kind);
38439 return info && info.type;
38440 }
38441 // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
38442 // maps primitive types and type parameters are to their apparent types.
38443 function getIndexInfoOfType(type, kind) {
38444 return getIndexInfoOfStructuredType(getApparentType(type), kind);
38445 }
38446 // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
38447 // maps primitive types and type parameters are to their apparent types.
38448 function getIndexTypeOfType(type, kind) {
38449 return getIndexTypeOfStructuredType(getApparentType(type), kind);
38450 }
38451 function getImplicitIndexTypeOfType(type, kind) {
38452 if (isObjectTypeWithInferableIndex(type)) {
38453 var propTypes = [];
38454 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
38455 var prop = _a[_i];
38456 if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
38457 propTypes.push(getTypeOfSymbol(prop));
38458 }
38459 }
38460 if (propTypes.length) {
38461 return getUnionType(propTypes, 2 /* Subtype */);
38462 }
38463 }
38464 return undefined;
38465 }
38466 // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
38467 // type checking functions).
38468 function getTypeParametersFromDeclaration(declaration) {
38469 var result;
38470 for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
38471 var node = _a[_i];
38472 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
38473 }
38474 return result;
38475 }
38476 function symbolsToArray(symbols) {
38477 var result = [];
38478 symbols.forEach(function (symbol, id) {
38479 if (!isReservedMemberName(id)) {
38480 result.push(symbol);
38481 }
38482 });
38483 return result;
38484 }
38485 function isJSDocOptionalParameter(node) {
38486 return ts.isInJSFile(node) && (
38487 // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
38488 node.type && node.type.kind === 293 /* JSDocOptionalType */
38489 || ts.getJSDocParameterTags(node).some(function (_a) {
38490 var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
38491 return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
38492 }));
38493 }
38494 function tryFindAmbientModule(moduleName, withAugmentations) {
38495 if (ts.isExternalModuleNameRelative(moduleName)) {
38496 return undefined;
38497 }
38498 var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
38499 // merged symbol is module declaration symbol combined with all augmentations
38500 return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
38501 }
38502 function isOptionalParameter(node) {
38503 if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
38504 return true;
38505 }
38506 if (node.initializer) {
38507 var signature = getSignatureFromDeclaration(node.parent);
38508 var parameterIndex = node.parent.parameters.indexOf(node);
38509 ts.Debug.assert(parameterIndex >= 0);
38510 return parameterIndex >= getMinArgumentCount(signature);
38511 }
38512 var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
38513 if (iife) {
38514 return !node.type &&
38515 !node.dotDotDotToken &&
38516 node.parent.parameters.indexOf(node) >= iife.arguments.length;
38517 }
38518 return false;
38519 }
38520 function isOptionalJSDocParameterTag(node) {
38521 if (!ts.isJSDocParameterTag(node)) {
38522 return false;
38523 }
38524 var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
38525 return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
38526 }
38527 function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
38528 return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
38529 }
38530 function createThisTypePredicate(type) {
38531 return { kind: 0 /* This */, type: type };
38532 }
38533 /**
38534 * Gets the minimum number of type arguments needed to satisfy all non-optional type
38535 * parameters.
38536 */
38537 function getMinTypeArgumentCount(typeParameters) {
38538 var minTypeArgumentCount = 0;
38539 if (typeParameters) {
38540 for (var i = 0; i < typeParameters.length; i++) {
38541 if (!hasTypeParameterDefault(typeParameters[i])) {
38542 minTypeArgumentCount = i + 1;
38543 }
38544 }
38545 }
38546 return minTypeArgumentCount;
38547 }
38548 function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
38549 var numTypeParameters = ts.length(typeParameters);
38550 if (!numTypeParameters) {
38551 return [];
38552 }
38553 var numTypeArguments = ts.length(typeArguments);
38554 if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
38555 var result = typeArguments ? typeArguments.slice() : [];
38556 // Map invalid forward references in default types to the error type
38557 for (var i = numTypeArguments; i < numTypeParameters; i++) {
38558 result[i] = errorType;
38559 }
38560 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
38561 for (var i = numTypeArguments; i < numTypeParameters; i++) {
38562 var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
38563 if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) {
38564 defaultType = anyType;
38565 }
38566 result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
38567 }
38568 result.length = typeParameters.length;
38569 return result;
38570 }
38571 return typeArguments && typeArguments.slice();
38572 }
38573 function getSignatureFromDeclaration(declaration) {
38574 var links = getNodeLinks(declaration);
38575 if (!links.resolvedSignature) {
38576 var parameters = [];
38577 var hasLiteralTypes = false;
38578 var minArgumentCount = 0;
38579 var thisParameter = void 0;
38580 var hasThisParameter = false;
38581 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
38582 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
38583 var isUntypedSignatureInJSFile = !iife &&
38584 ts.isInJSFile(declaration) &&
38585 ts.isValueSignatureDeclaration(declaration) &&
38586 !ts.hasJSDocParameterTags(declaration) &&
38587 !ts.getJSDocType(declaration);
38588 // If this is a JSDoc construct signature, then skip the first parameter in the
38589 // parameter list. The first parameter represents the return type of the construct
38590 // signature.
38591 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
38592 var param = declaration.parameters[i];
38593 var paramSymbol = param.symbol;
38594 var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
38595 // Include parameter symbol instead of property symbol in the signature
38596 if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
38597 var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false);
38598 paramSymbol = resolvedSymbol;
38599 }
38600 if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
38601 hasThisParameter = true;
38602 thisParameter = param.symbol;
38603 }
38604 else {
38605 parameters.push(paramSymbol);
38606 }
38607 if (type && type.kind === 182 /* LiteralType */) {
38608 hasLiteralTypes = true;
38609 }
38610 // Record a new minimum argument count if this is not an optional parameter
38611 var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
38612 param.initializer || param.questionToken || param.dotDotDotToken ||
38613 iife && parameters.length > iife.arguments.length && !type ||
38614 isUntypedSignatureInJSFile ||
38615 isJSDocOptionalParameter(param);
38616 if (!isOptionalParameter_1) {
38617 minArgumentCount = parameters.length;
38618 }
38619 }
38620 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
38621 if ((declaration.kind === 158 /* GetAccessor */ || declaration.kind === 159 /* SetAccessor */) &&
38622 !hasNonBindableDynamicName(declaration) &&
38623 (!hasThisParameter || !thisParameter)) {
38624 var otherKind = declaration.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */;
38625 var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
38626 if (other) {
38627 thisParameter = getAnnotatedAccessorThisParameter(other);
38628 }
38629 }
38630 var classType = declaration.kind === 157 /* Constructor */ ?
38631 getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
38632 : undefined;
38633 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
38634 var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters);
38635 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters,
38636 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes);
38637 }
38638 return links.resolvedSignature;
38639 }
38640 /**
38641 * A JS function gets a synthetic rest parameter if it references `arguments` AND:
38642 * 1. It has no parameters but at least one `@param` with a type that starts with `...`
38643 * OR
38644 * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
38645 */
38646 function maybeAddJsSyntheticRestParameter(declaration, parameters) {
38647 if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
38648 return false;
38649 }
38650 var lastParam = ts.lastOrUndefined(declaration.parameters);
38651 var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
38652 var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
38653 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
38654 });
38655 var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 16384 /* RestParameter */);
38656 syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
38657 if (lastParamVariadicType) {
38658 // Replace the last parameter with a rest parameter.
38659 parameters.pop();
38660 }
38661 parameters.push(syntheticArgsSymbol);
38662 return true;
38663 }
38664 function getSignatureOfTypeTag(node) {
38665 var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
38666 var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
38667 return signature && getErasedSignature(signature);
38668 }
38669 function getReturnTypeOfTypeTag(node) {
38670 var signature = getSignatureOfTypeTag(node);
38671 return signature && getReturnTypeOfSignature(signature);
38672 }
38673 function containsArgumentsReference(declaration) {
38674 var links = getNodeLinks(declaration);
38675 if (links.containsArgumentsReference === undefined) {
38676 if (links.flags & 8192 /* CaptureArguments */) {
38677 links.containsArgumentsReference = true;
38678 }
38679 else {
38680 links.containsArgumentsReference = traverse(declaration.body);
38681 }
38682 }
38683 return links.containsArgumentsReference;
38684 function traverse(node) {
38685 if (!node)
38686 return false;
38687 switch (node.kind) {
38688 case 72 /* Identifier */:
38689 return node.escapedText === "arguments" && ts.isExpressionNode(node);
38690 case 154 /* PropertyDeclaration */:
38691 case 156 /* MethodDeclaration */:
38692 case 158 /* GetAccessor */:
38693 case 159 /* SetAccessor */:
38694 return node.name.kind === 149 /* ComputedPropertyName */
38695 && traverse(node.name);
38696 default:
38697 return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
38698 }
38699 }
38700 }
38701 function getSignaturesOfSymbol(symbol) {
38702 if (!symbol)
38703 return ts.emptyArray;
38704 var result = [];
38705 for (var i = 0; i < symbol.declarations.length; i++) {
38706 var decl = symbol.declarations[i];
38707 if (!ts.isFunctionLike(decl))
38708 continue;
38709 // Don't include signature if node is the implementation of an overloaded function. A node is considered
38710 // an implementation node if it has a body and the previous node is of the same kind and immediately
38711 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
38712 if (i > 0 && decl.body) {
38713 var previous = symbol.declarations[i - 1];
38714 if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
38715 continue;
38716 }
38717 }
38718 result.push(getSignatureFromDeclaration(decl));
38719 }
38720 return result;
38721 }
38722 function resolveExternalModuleTypeByLiteral(name) {
38723 var moduleSym = resolveExternalModuleName(name, name);
38724 if (moduleSym) {
38725 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
38726 if (resolvedModuleSymbol) {
38727 return getTypeOfSymbol(resolvedModuleSymbol);
38728 }
38729 }
38730 return anyType;
38731 }
38732 function getThisTypeOfSignature(signature) {
38733 if (signature.thisParameter) {
38734 return getTypeOfSymbol(signature.thisParameter);
38735 }
38736 }
38737 function signatureHasTypePredicate(signature) {
38738 return getTypePredicateOfSignature(signature) !== undefined;
38739 }
38740 function getTypePredicateOfSignature(signature) {
38741 if (!signature.resolvedTypePredicate) {
38742 if (signature.target) {
38743 var targetTypePredicate = getTypePredicateOfSignature(signature.target);
38744 signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
38745 }
38746 else if (signature.unionSignatures) {
38747 signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
38748 }
38749 else {
38750 var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
38751 var jsdocPredicate = void 0;
38752 if (!type && ts.isInJSFile(signature.declaration)) {
38753 var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
38754 if (jsdocSignature && signature !== jsdocSignature) {
38755 jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
38756 }
38757 }
38758 signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
38759 createTypePredicateFromTypePredicateNode(type, signature) :
38760 jsdocPredicate || noTypePredicate;
38761 }
38762 ts.Debug.assert(!!signature.resolvedTypePredicate);
38763 }
38764 return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
38765 }
38766 function createTypePredicateFromTypePredicateNode(node, signature) {
38767 var parameterName = node.parameterName;
38768 var type = getTypeFromTypeNode(node.type);
38769 if (parameterName.kind === 72 /* Identifier */) {
38770 return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
38771 }
38772 else {
38773 return createThisTypePredicate(type);
38774 }
38775 }
38776 function getReturnTypeOfSignature(signature) {
38777 if (!signature.resolvedReturnType) {
38778 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
38779 return errorType;
38780 }
38781 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
38782 signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
38783 getReturnTypeFromAnnotation(signature.declaration) ||
38784 isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) ||
38785 (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
38786 if (!popTypeResolution()) {
38787 if (signature.declaration) {
38788 var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
38789 if (typeNode) {
38790 error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
38791 }
38792 else if (noImplicitAny) {
38793 var declaration = signature.declaration;
38794 var name = ts.getNameOfDeclaration(declaration);
38795 if (name) {
38796 error(name, ts.Diagnostics._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, ts.declarationNameToString(name));
38797 }
38798 else {
38799 error(declaration, ts.Diagnostics.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);
38800 }
38801 }
38802 }
38803 type = anyType;
38804 }
38805 signature.resolvedReturnType = type;
38806 }
38807 return signature.resolvedReturnType;
38808 }
38809 function getReturnTypeFromAnnotation(declaration) {
38810 if (declaration.kind === 157 /* Constructor */) {
38811 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
38812 }
38813 if (ts.isJSDocConstructSignature(declaration)) {
38814 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
38815 }
38816 var typeNode = ts.getEffectiveReturnTypeNode(declaration);
38817 if (typeNode) {
38818 return getTypeFromTypeNode(typeNode);
38819 }
38820 if (declaration.kind === 158 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
38821 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
38822 if (jsDocType) {
38823 return jsDocType;
38824 }
38825 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 159 /* SetAccessor */);
38826 var setterType = getAnnotatedAccessorType(setter);
38827 if (setterType) {
38828 return setterType;
38829 }
38830 }
38831 return getReturnTypeOfTypeTag(declaration);
38832 }
38833 function isResolvingReturnTypeOfSignature(signature) {
38834 return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
38835 }
38836 function getRestTypeOfSignature(signature) {
38837 return tryGetRestTypeOfSignature(signature) || anyType;
38838 }
38839 function tryGetRestTypeOfSignature(signature) {
38840 if (signature.hasRestParameter) {
38841 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
38842 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
38843 return restType && getIndexTypeOfType(restType, 1 /* Number */);
38844 }
38845 return undefined;
38846 }
38847 function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
38848 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
38849 if (inferredTypeParameters) {
38850 var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
38851 if (returnSignature) {
38852 var newReturnSignature = cloneSignature(returnSignature);
38853 newReturnSignature.typeParameters = inferredTypeParameters;
38854 var newInstantiatedSignature = cloneSignature(instantiatedSignature);
38855 newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
38856 return newInstantiatedSignature;
38857 }
38858 }
38859 return instantiatedSignature;
38860 }
38861 function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
38862 var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
38863 var id = getTypeListId(typeArguments);
38864 var instantiation = instantiations.get(id);
38865 if (!instantiation) {
38866 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
38867 }
38868 return instantiation;
38869 }
38870 function createSignatureInstantiation(signature, typeArguments) {
38871 return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
38872 }
38873 function createSignatureTypeMapper(signature, typeArguments) {
38874 return createTypeMapper(signature.typeParameters, typeArguments);
38875 }
38876 function getErasedSignature(signature) {
38877 return signature.typeParameters ?
38878 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
38879 signature;
38880 }
38881 function createErasedSignature(signature) {
38882 // Create an instantiation of the signature where all type arguments are the any type.
38883 return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
38884 }
38885 function getCanonicalSignature(signature) {
38886 return signature.typeParameters ?
38887 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
38888 signature;
38889 }
38890 function createCanonicalSignature(signature) {
38891 // Create an instantiation of the signature where each unconstrained type parameter is replaced with
38892 // its original. When a generic class or interface is instantiated, each generic method in the class or
38893 // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
38894 // where different generations of the same type parameter are in scope). This leads to a lot of new type
38895 // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
38896 // that uses the original type identities for all unconstrained type parameters.
38897 return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
38898 }
38899 function getBaseSignature(signature) {
38900 var typeParameters = signature.typeParameters;
38901 if (typeParameters) {
38902 var typeEraser_1 = createTypeEraser(typeParameters);
38903 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; });
38904 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
38905 }
38906 return signature;
38907 }
38908 function getOrCreateTypeFromSignature(signature) {
38909 // There are two ways to declare a construct signature, one is by declaring a class constructor
38910 // using the constructor keyword, and the other is declaring a bare construct signature in an
38911 // object type literal or interface (using the new keyword). Each way of declaring a constructor
38912 // will result in a different declaration kind.
38913 if (!signature.isolatedSignatureType) {
38914 var isConstructor = signature.declaration.kind === 157 /* Constructor */ || signature.declaration.kind === 161 /* ConstructSignature */; // TODO: GH#18217
38915 var type = createObjectType(16 /* Anonymous */);
38916 type.members = emptySymbols;
38917 type.properties = ts.emptyArray;
38918 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
38919 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
38920 signature.isolatedSignatureType = type;
38921 }
38922 return signature.isolatedSignatureType;
38923 }
38924 function getIndexSymbol(symbol) {
38925 return symbol.members.get("__index" /* Index */);
38926 }
38927 function getIndexDeclarationOfSymbol(symbol, kind) {
38928 var syntaxKind = kind === 1 /* Number */ ? 135 /* NumberKeyword */ : 138 /* StringKeyword */;
38929 var indexSymbol = getIndexSymbol(symbol);
38930 if (indexSymbol) {
38931 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
38932 var decl = _a[_i];
38933 var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
38934 if (node.parameters.length === 1) {
38935 var parameter = node.parameters[0];
38936 if (parameter.type && parameter.type.kind === syntaxKind) {
38937 return node;
38938 }
38939 }
38940 }
38941 }
38942 return undefined;
38943 }
38944 function createIndexInfo(type, isReadonly, declaration) {
38945 return { type: type, isReadonly: isReadonly, declaration: declaration };
38946 }
38947 function getIndexInfoOfSymbol(symbol, kind) {
38948 var declaration = getIndexDeclarationOfSymbol(symbol, kind);
38949 if (declaration) {
38950 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration);
38951 }
38952 return undefined;
38953 }
38954 function getConstraintDeclaration(type) {
38955 var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 150 /* TypeParameter */);
38956 return decl && ts.getEffectiveConstraintOfTypeParameter(decl);
38957 }
38958 function getInferredTypeParameterConstraint(typeParameter) {
38959 var inferences;
38960 if (typeParameter.symbol) {
38961 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
38962 var declaration = _a[_i];
38963 if (declaration.parent.kind === 176 /* InferType */) {
38964 // When an 'infer T' declaration is immediately contained in a type reference node
38965 // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
38966 // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
38967 // present, we form an intersection of the inferred constraint types.
38968 var grandParent = declaration.parent.parent;
38969 if (grandParent.kind === 164 /* TypeReference */) {
38970 var typeReference = grandParent;
38971 var typeParameters = getTypeParametersForTypeReference(typeReference);
38972 if (typeParameters) {
38973 var index = typeReference.typeArguments.indexOf(declaration.parent);
38974 if (index < typeParameters.length) {
38975 var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
38976 if (declaredConstraint) {
38977 // Type parameter constraints can reference other type parameters so
38978 // constraints need to be instantiated. If instantiation produces the
38979 // type parameter itself, we discard that inference. For example, in
38980 // type Foo<T extends string, U extends T> = [T, U];
38981 // type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
38982 // the instantiated constraint for U is X, so we discard that inference.
38983 var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
38984 var constraint = instantiateType(declaredConstraint, mapper);
38985 if (constraint !== typeParameter) {
38986 inferences = ts.append(inferences, constraint);
38987 }
38988 }
38989 }
38990 }
38991 }
38992 // When an 'infer T' declaration is immediately contained in a rest parameter
38993 // declaration, we infer an 'unknown[]' constraint.
38994 else if (grandParent.kind === 151 /* Parameter */ && grandParent.dotDotDotToken) {
38995 inferences = ts.append(inferences, createArrayType(unknownType));
38996 }
38997 }
38998 }
38999 }
39000 return inferences && getIntersectionType(inferences);
39001 }
39002 /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
39003 function getConstraintFromTypeParameter(typeParameter) {
39004 if (!typeParameter.constraint) {
39005 if (typeParameter.target) {
39006 var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
39007 typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
39008 }
39009 else {
39010 var constraintDeclaration = getConstraintDeclaration(typeParameter);
39011 typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) :
39012 getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
39013 }
39014 }
39015 return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
39016 }
39017 function getParentSymbolOfTypeParameter(typeParameter) {
39018 var tp = ts.getDeclarationOfKind(typeParameter.symbol, 150 /* TypeParameter */);
39019 var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
39020 return host && getSymbolOfNode(host);
39021 }
39022 function getTypeListId(types) {
39023 var result = "";
39024 if (types) {
39025 var length_3 = types.length;
39026 var i = 0;
39027 while (i < length_3) {
39028 var startId = types[i].id;
39029 var count = 1;
39030 while (i + count < length_3 && types[i + count].id === startId + count) {
39031 count++;
39032 }
39033 if (result.length) {
39034 result += ",";
39035 }
39036 result += startId;
39037 if (count > 1) {
39038 result += ":" + count;
39039 }
39040 i += count;
39041 }
39042 }
39043 return result;
39044 }
39045 // This function is used to propagate certain flags when creating new object type references and union types.
39046 // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
39047 // of an object literal or the anyFunctionType. This is because there are operations in the type checker
39048 // that care about the presence of such types at arbitrary depth in a containing type.
39049 function getPropagatingFlagsOfTypes(types, excludeKinds) {
39050 var result = 0;
39051 for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
39052 var type = types_5[_i];
39053 if (!(type.flags & excludeKinds)) {
39054 result |= ts.getObjectFlags(type);
39055 }
39056 }
39057 return result & 917504 /* PropagatingFlags */;
39058 }
39059 function createTypeReference(target, typeArguments) {
39060 var id = getTypeListId(typeArguments);
39061 var type = target.instantiations.get(id);
39062 if (!type) {
39063 type = createObjectType(4 /* Reference */, target.symbol);
39064 target.instantiations.set(id, type);
39065 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
39066 type.target = target;
39067 type.typeArguments = typeArguments;
39068 }
39069 return type;
39070 }
39071 function cloneTypeReference(source) {
39072 var type = createType(source.flags);
39073 type.symbol = source.symbol;
39074 type.objectFlags = source.objectFlags;
39075 type.target = source.target;
39076 type.typeArguments = source.typeArguments;
39077 return type;
39078 }
39079 function getTypeReferenceArity(type) {
39080 return ts.length(type.target.typeParameters);
39081 }
39082 /**
39083 * Get type from type-reference that reference to class or interface
39084 */
39085 function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) {
39086 var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
39087 var typeParameters = type.localTypeParameters;
39088 if (typeParameters) {
39089 var numTypeArguments = ts.length(node.typeArguments);
39090 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
39091 var isJs = ts.isInJSFile(node);
39092 var isJsImplicitAny = !noImplicitAny && isJs;
39093 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
39094 var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
39095 var diag = minTypeArgumentCount === typeParameters.length
39096 ? missingAugmentsTag
39097 ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag
39098 : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s
39099 : missingAugmentsTag
39100 ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag
39101 : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
39102 var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
39103 error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
39104 if (!isJs) {
39105 // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
39106 return errorType;
39107 }
39108 }
39109 // In a type reference, the outer type parameters of the referenced class or interface are automatically
39110 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
39111 // of the class or interface.
39112 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs));
39113 return createTypeReference(type, typeArguments);
39114 }
39115 return checkNoTypeArguments(node, symbol) ? type : errorType;
39116 }
39117 function getTypeAliasInstantiation(symbol, typeArguments) {
39118 var type = getDeclaredTypeOfSymbol(symbol);
39119 var links = getSymbolLinks(symbol);
39120 var typeParameters = links.typeParameters;
39121 var id = getTypeListId(typeArguments);
39122 var instantiation = links.instantiations.get(id);
39123 if (!instantiation) {
39124 links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
39125 }
39126 return instantiation;
39127 }
39128 /**
39129 * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
39130 * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
39131 * declared type. Instantiations are cached using the type identities of the type arguments as the key.
39132 */
39133 function getTypeFromTypeAliasReference(node, symbol, typeArguments) {
39134 var type = getDeclaredTypeOfSymbol(symbol);
39135 var typeParameters = getSymbolLinks(symbol).typeParameters;
39136 if (typeParameters) {
39137 var numTypeArguments = ts.length(node.typeArguments);
39138 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
39139 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
39140 error(node, minTypeArgumentCount === typeParameters.length
39141 ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s
39142 : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
39143 return errorType;
39144 }
39145 return getTypeAliasInstantiation(symbol, typeArguments);
39146 }
39147 return checkNoTypeArguments(node, symbol) ? type : errorType;
39148 }
39149 function getTypeReferenceName(node) {
39150 switch (node.kind) {
39151 case 164 /* TypeReference */:
39152 return node.typeName;
39153 case 211 /* ExpressionWithTypeArguments */:
39154 // We only support expressions that are simple qualified names. For other
39155 // expressions this produces undefined.
39156 var expr = node.expression;
39157 if (ts.isEntityNameExpression(expr)) {
39158 return expr;
39159 }
39160 // fall through;
39161 }
39162 return undefined;
39163 }
39164 function resolveTypeReferenceName(typeReferenceName, meaning) {
39165 if (!typeReferenceName) {
39166 return unknownSymbol;
39167 }
39168 return resolveEntityName(typeReferenceName, meaning) || unknownSymbol;
39169 }
39170 function getTypeReferenceType(node, symbol) {
39171 var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced.
39172 if (symbol === unknownSymbol) {
39173 return errorType;
39174 }
39175 var type = getTypeReferenceTypeWorker(node, symbol, typeArguments);
39176 if (type) {
39177 return type;
39178 }
39179 // JS enums are 'string' or 'number', not an enum type.
39180 var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration);
39181 if (enumTag) {
39182 var links = getNodeLinks(enumTag);
39183 if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) {
39184 return errorType;
39185 }
39186 var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType;
39187 if (!popTypeResolution()) {
39188 type_4 = errorType;
39189 error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol));
39190 }
39191 return (links.resolvedEnumType = type_4);
39192 }
39193 // Get type from reference to named type that cannot be generic (enum or type parameter)
39194 var res = tryGetDeclaredTypeOfSymbol(symbol);
39195 if (res) {
39196 return checkNoTypeArguments(node, symbol) ?
39197 res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) :
39198 errorType;
39199 }
39200 if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) {
39201 return errorType;
39202 }
39203 var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
39204 if (jsdocType) {
39205 return jsdocType;
39206 }
39207 // Resolve the type reference as a Type for the purpose of reporting errors.
39208 resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */);
39209 return getTypeOfSymbol(symbol);
39210 }
39211 /**
39212 * A jsdoc TypeReference may have resolved to a value (as opposed to a type). If
39213 * the symbol is a constructor function, return the inferred class type; otherwise,
39214 * the type of this reference is just the type of the value we resolved to.
39215 */
39216 function getJSDocTypeReference(node, symbol, typeArguments) {
39217 // In the case of an assignment of a function expression (binary expressions, variable declarations, etc.), we will get the
39218 // correct instance type for the symbol on the LHS by finding the type for RHS. For example if we want to get the type of the symbol `foo`:
39219 // var foo = function() {}
39220 // We will find the static type of the assigned anonymous function.
39221 var staticType = getTypeOfSymbol(symbol);
39222 var instanceType = staticType.symbol &&
39223 staticType.symbol !== symbol && // Make sure this is an assignment like expression by checking that symbol -> type -> symbol doesn't roundtrips.
39224 getTypeReferenceTypeWorker(node, staticType.symbol, typeArguments); // Get the instance type of the RHS symbol.
39225 if (instanceType) {
39226 return getSymbolLinks(symbol).resolvedJSDocType = instanceType;
39227 }
39228 }
39229 function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
39230 if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
39231 if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
39232 var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
39233 if (jsdocType) {
39234 return jsdocType;
39235 }
39236 }
39237 return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments);
39238 }
39239 if (symbol.flags & 524288 /* TypeAlias */) {
39240 return getTypeFromTypeAliasReference(node, symbol, typeArguments);
39241 }
39242 if (symbol.flags & 16 /* Function */ &&
39243 isJSDocTypeReference(node) &&
39244 isJSConstructor(symbol.valueDeclaration)) {
39245 var resolved = resolveStructuredTypeMembers(getTypeOfSymbol(symbol));
39246 if (resolved.callSignatures.length === 1) {
39247 return getReturnTypeOfSignature(resolved.callSignatures[0]);
39248 }
39249 }
39250 }
39251 function getSubstitutionType(typeVariable, substitute) {
39252 if (substitute.flags & 3 /* AnyOrUnknown */) {
39253 return typeVariable;
39254 }
39255 var result = createType(33554432 /* Substitution */);
39256 result.typeVariable = typeVariable;
39257 result.substitute = substitute;
39258 return result;
39259 }
39260 function isUnaryTupleTypeNode(node) {
39261 return node.kind === 170 /* TupleType */ && node.elementTypes.length === 1;
39262 }
39263 function getImpliedConstraint(typeVariable, checkNode, extendsNode) {
39264 return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) :
39265 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) :
39266 undefined;
39267 }
39268 function getConstrainedTypeVariable(typeVariable, node) {
39269 var constraints;
39270 while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
39271 var parent = node.parent;
39272 if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
39273 var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
39274 if (constraint) {
39275 constraints = ts.append(constraints, constraint);
39276 }
39277 }
39278 node = parent;
39279 }
39280 return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable;
39281 }
39282 function isJSDocTypeReference(node) {
39283 return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 164 /* TypeReference */ || node.kind === 183 /* ImportType */);
39284 }
39285 function checkNoTypeArguments(node, symbol) {
39286 if (node.typeArguments) {
39287 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : "(anonymous)");
39288 return false;
39289 }
39290 return true;
39291 }
39292 function getIntendedTypeFromJSDocTypeReference(node) {
39293 if (ts.isIdentifier(node.typeName)) {
39294 var typeArgs = node.typeArguments;
39295 switch (node.typeName.escapedText) {
39296 case "String":
39297 checkNoTypeArguments(node);
39298 return stringType;
39299 case "Number":
39300 checkNoTypeArguments(node);
39301 return numberType;
39302 case "Boolean":
39303 checkNoTypeArguments(node);
39304 return booleanType;
39305 case "Void":
39306 checkNoTypeArguments(node);
39307 return voidType;
39308 case "Undefined":
39309 checkNoTypeArguments(node);
39310 return undefinedType;
39311 case "Null":
39312 checkNoTypeArguments(node);
39313 return nullType;
39314 case "Function":
39315 case "function":
39316 checkNoTypeArguments(node);
39317 return globalFunctionType;
39318 case "Array":
39319 case "array":
39320 return !typeArgs || !typeArgs.length ? anyArrayType : undefined;
39321 case "Promise":
39322 case "promise":
39323 return !typeArgs || !typeArgs.length ? createPromiseType(anyType) : undefined;
39324 case "Object":
39325 if (typeArgs && typeArgs.length === 2) {
39326 if (ts.isJSDocIndexSignature(node)) {
39327 var indexed = getTypeFromTypeNode(typeArgs[0]);
39328 var target = getTypeFromTypeNode(typeArgs[1]);
39329 var index = createIndexInfo(target, /*isReadonly*/ false);
39330 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
39331 }
39332 return anyType;
39333 }
39334 checkNoTypeArguments(node);
39335 return anyType;
39336 }
39337 }
39338 }
39339 function getTypeFromJSDocNullableTypeNode(node) {
39340 var type = getTypeFromTypeNode(node.type);
39341 return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
39342 }
39343 function getTypeFromTypeReference(node) {
39344 var links = getNodeLinks(node);
39345 if (!links.resolvedType) {
39346 var symbol = void 0;
39347 var type = void 0;
39348 var meaning = 67897832 /* Type */;
39349 if (isJSDocTypeReference(node)) {
39350 type = getIntendedTypeFromJSDocTypeReference(node);
39351 meaning |= 67220415 /* Value */;
39352 }
39353 if (!type) {
39354 symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
39355 type = getTypeReferenceType(node, symbol);
39356 }
39357 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
39358 // type reference in checkTypeReferenceNode.
39359 links.resolvedSymbol = symbol;
39360 links.resolvedType = type;
39361 }
39362 return links.resolvedType;
39363 }
39364 function typeArgumentsFromTypeReferenceNode(node) {
39365 return ts.map(node.typeArguments, getTypeFromTypeNode);
39366 }
39367 function getTypeFromTypeQueryNode(node) {
39368 var links = getNodeLinks(node);
39369 if (!links.resolvedType) {
39370 // TypeScript 1.0 spec (April 2014): 3.6.3
39371 // The expression is processed as an identifier expression (section 4.3)
39372 // or property access expression(section 4.10),
39373 // the widened type(section 3.9) of which becomes the result.
39374 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
39375 }
39376 return links.resolvedType;
39377 }
39378 function getTypeOfGlobalSymbol(symbol, arity) {
39379 function getTypeDeclaration(symbol) {
39380 var declarations = symbol.declarations;
39381 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
39382 var declaration = declarations_3[_i];
39383 switch (declaration.kind) {
39384 case 240 /* ClassDeclaration */:
39385 case 241 /* InterfaceDeclaration */:
39386 case 243 /* EnumDeclaration */:
39387 return declaration;
39388 }
39389 }
39390 }
39391 if (!symbol) {
39392 return arity ? emptyGenericType : emptyObjectType;
39393 }
39394 var type = getDeclaredTypeOfSymbol(symbol);
39395 if (!(type.flags & 524288 /* Object */)) {
39396 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
39397 return arity ? emptyGenericType : emptyObjectType;
39398 }
39399 if (ts.length(type.typeParameters) !== arity) {
39400 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
39401 return arity ? emptyGenericType : emptyObjectType;
39402 }
39403 return type;
39404 }
39405 function getGlobalValueSymbol(name, reportErrors) {
39406 return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
39407 }
39408 function getGlobalTypeSymbol(name, reportErrors) {
39409 return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
39410 }
39411 function getGlobalSymbol(name, meaning, diagnostic) {
39412 // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
39413 return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
39414 }
39415 function getGlobalType(name, arity, reportErrors) {
39416 var symbol = getGlobalTypeSymbol(name, reportErrors);
39417 return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
39418 }
39419 function getGlobalTypedPropertyDescriptorType() {
39420 return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
39421 }
39422 function getGlobalTemplateStringsArrayType() {
39423 return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
39424 }
39425 function getGlobalImportMetaType() {
39426 return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
39427 }
39428 function getGlobalESSymbolConstructorSymbol(reportErrors) {
39429 return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
39430 }
39431 function getGlobalESSymbolType(reportErrors) {
39432 return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
39433 }
39434 function getGlobalPromiseType(reportErrors) {
39435 return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
39436 }
39437 function getGlobalPromiseLikeType(reportErrors) {
39438 return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
39439 }
39440 function getGlobalPromiseConstructorSymbol(reportErrors) {
39441 return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
39442 }
39443 function getGlobalPromiseConstructorLikeType(reportErrors) {
39444 return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
39445 }
39446 function getGlobalAsyncIterableType(reportErrors) {
39447 return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
39448 }
39449 function getGlobalAsyncIteratorType(reportErrors) {
39450 return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
39451 }
39452 function getGlobalAsyncIterableIteratorType(reportErrors) {
39453 return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
39454 }
39455 function getGlobalIterableType(reportErrors) {
39456 return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
39457 }
39458 function getGlobalIteratorType(reportErrors) {
39459 return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
39460 }
39461 function getGlobalIterableIteratorType(reportErrors) {
39462 return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
39463 }
39464 function getGlobalTypeOrUndefined(name, arity) {
39465 if (arity === void 0) { arity = 0; }
39466 var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined);
39467 return symbol && getTypeOfGlobalSymbol(symbol, arity);
39468 }
39469 function getGlobalExtractSymbol() {
39470 return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
39471 }
39472 function getGlobalExcludeSymbol() {
39473 return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
39474 }
39475 function getGlobalPickSymbol() {
39476 return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
39477 }
39478 function getGlobalBigIntType(reportErrors) {
39479 return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
39480 }
39481 /**
39482 * Instantiates a global type that is generic with some element type, and returns that instantiation.
39483 */
39484 function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
39485 return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
39486 }
39487 function createTypedPropertyDescriptorType(propertyType) {
39488 return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
39489 }
39490 function createAsyncIterableType(iteratedType) {
39491 return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]);
39492 }
39493 function createAsyncIterableIteratorType(iteratedType) {
39494 return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
39495 }
39496 function createIterableType(iteratedType) {
39497 return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
39498 }
39499 function createIterableIteratorType(iteratedType) {
39500 return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
39501 }
39502 function createArrayType(elementType, readonly) {
39503 return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
39504 }
39505 function getTypeFromArrayTypeNode(node) {
39506 var links = getNodeLinks(node);
39507 if (!links.resolvedType) {
39508 links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType), isReadonlyTypeOperator(node.parent));
39509 }
39510 return links.resolvedType;
39511 }
39512 function isReadonlyTypeOperator(node) {
39513 return ts.isTypeOperatorNode(node) && node.operator === 133 /* ReadonlyKeyword */;
39514 }
39515 // We represent tuple types as type references to synthesized generic interface types created by
39516 // this function. The types are of the form:
39517 //
39518 // interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
39519 //
39520 // Note that the generic type created by this function has no symbol associated with it. The same
39521 // is true for each of the synthesized type parameters.
39522 function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
39523 var typeParameters;
39524 var properties = [];
39525 var maxLength = hasRestElement ? arity - 1 : arity;
39526 if (arity) {
39527 typeParameters = new Array(arity);
39528 for (var i = 0; i < arity; i++) {
39529 var typeParameter = typeParameters[i] = createTypeParameter();
39530 if (i < maxLength) {
39531 var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
39532 property.type = typeParameter;
39533 properties.push(property);
39534 }
39535 }
39536 }
39537 var literalTypes = [];
39538 for (var i = minLength; i <= maxLength; i++)
39539 literalTypes.push(getLiteralType(i));
39540 var lengthSymbol = createSymbol(4 /* Property */, "length");
39541 lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes);
39542 properties.push(lengthSymbol);
39543 var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
39544 type.typeParameters = typeParameters;
39545 type.outerTypeParameters = undefined;
39546 type.localTypeParameters = typeParameters;
39547 type.instantiations = ts.createMap();
39548 type.instantiations.set(getTypeListId(type.typeParameters), type);
39549 type.target = type;
39550 type.typeArguments = type.typeParameters;
39551 type.thisType = createTypeParameter();
39552 type.thisType.isThisType = true;
39553 type.thisType.constraint = type;
39554 type.declaredProperties = properties;
39555 type.declaredCallSignatures = ts.emptyArray;
39556 type.declaredConstructSignatures = ts.emptyArray;
39557 type.declaredStringIndexInfo = undefined;
39558 type.declaredNumberIndexInfo = undefined;
39559 type.minLength = minLength;
39560 type.hasRestElement = hasRestElement;
39561 type.readonly = readonly;
39562 type.associatedNames = associatedNames;
39563 return type;
39564 }
39565 function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
39566 var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
39567 var type = tupleTypes.get(key);
39568 if (!type) {
39569 tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
39570 }
39571 return type;
39572 }
39573 function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
39574 if (minLength === void 0) { minLength = elementTypes.length; }
39575 if (hasRestElement === void 0) { hasRestElement = false; }
39576 if (readonly === void 0) { readonly = false; }
39577 var arity = elementTypes.length;
39578 if (arity === 1 && hasRestElement) {
39579 return createArrayType(elementTypes[0], readonly);
39580 }
39581 var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
39582 return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
39583 }
39584 function getTypeFromTupleTypeNode(node) {
39585 var links = getNodeLinks(node);
39586 if (!links.resolvedType) {
39587 var lastElement = ts.lastOrUndefined(node.elementTypes);
39588 var restElement_1 = lastElement && lastElement.kind === 172 /* RestType */ ? lastElement : undefined;
39589 var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 171 /* OptionalType */ && n !== restElement_1; }) + 1;
39590 var elementTypes = ts.map(node.elementTypes, function (n) {
39591 var type = getTypeFromTypeNode(n);
39592 return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type;
39593 });
39594 links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1, isReadonlyTypeOperator(node.parent));
39595 }
39596 return links.resolvedType;
39597 }
39598 function sliceTupleType(type, index) {
39599 var tuple = type.target;
39600 if (tuple.hasRestElement) {
39601 // don't slice off rest element
39602 index = Math.min(index, getTypeReferenceArity(type) - 1);
39603 }
39604 return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
39605 }
39606 function getTypeFromOptionalTypeNode(node) {
39607 var type = getTypeFromTypeNode(node.type);
39608 return strictNullChecks ? getOptionalType(type) : type;
39609 }
39610 function getTypeId(type) {
39611 return type.id;
39612 }
39613 function containsType(types, type) {
39614 return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
39615 }
39616 function insertType(types, type) {
39617 var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
39618 if (index < 0) {
39619 types.splice(~index, 0, type);
39620 return true;
39621 }
39622 return false;
39623 }
39624 // Return true if the given intersection type contains
39625 // more than one unit type or,
39626 // an object type and a nullable type (null or undefined), or
39627 // a string-like type and a type known to be non-string-like, or
39628 // a number-like type and a type known to be non-number-like, or
39629 // a symbol-like type and a type known to be non-symbol-like, or
39630 // a void-like type and a type known to be non-void-like, or
39631 // a non-primitive type and a type known to be primitive.
39632 function isEmptyIntersectionType(type) {
39633 var combined = 0;
39634 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
39635 var t = _a[_i];
39636 if (t.flags & 109440 /* Unit */ && combined & 109440 /* Unit */) {
39637 return true;
39638 }
39639 combined |= t.flags;
39640 if (combined & 98304 /* Nullable */ && combined & (524288 /* Object */ | 67108864 /* NonPrimitive */) ||
39641 combined & 67108864 /* NonPrimitive */ && combined & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
39642 combined & 132 /* StringLike */ && combined & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) ||
39643 combined & 296 /* NumberLike */ && combined & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) ||
39644 combined & 2112 /* BigIntLike */ && combined & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
39645 combined & 12288 /* ESSymbolLike */ && combined & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
39646 combined & 49152 /* VoidLike */ && combined & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
39647 return true;
39648 }
39649 }
39650 return false;
39651 }
39652 function addTypeToUnion(typeSet, includes, type) {
39653 var flags = type.flags;
39654 if (flags & 1048576 /* Union */) {
39655 return addTypesToUnion(typeSet, includes, type.types);
39656 }
39657 // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are
39658 // another form of 'never' (in that they have an empty value domain). We could in theory turn
39659 // intersections of unit types into 'never' upon construction, but deferring the reduction makes it
39660 // easier to reason about their origin.
39661 if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) {
39662 includes |= flags & 1835007 /* IncludesMask */;
39663 if (flags & 66846720 /* StructuredOrInstantiable */)
39664 includes |= 262144 /* IncludesStructuredOrInstantiable */;
39665 if (type === wildcardType)
39666 includes |= 4194304 /* IncludesWildcard */;
39667 if (!strictNullChecks && flags & 98304 /* Nullable */) {
39668 if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */))
39669 includes |= 2097152 /* IncludesNonWideningType */;
39670 }
39671 else {
39672 var len = typeSet.length;
39673 var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
39674 if (index < 0) {
39675 typeSet.splice(~index, 0, type);
39676 }
39677 }
39678 }
39679 return includes;
39680 }
39681 // Add the given types to the given type set. Order is preserved, duplicates are removed,
39682 // and nested types of the given kind are flattened into the set.
39683 function addTypesToUnion(typeSet, includes, types) {
39684 for (var _i = 0, types_6 = types; _i < types_6.length; _i++) {
39685 var type = types_6[_i];
39686 includes = addTypeToUnion(typeSet, includes, type);
39687 }
39688 return includes;
39689 }
39690 function isSetOfLiteralsFromSameEnum(types) {
39691 var first = types[0];
39692 if (first.flags & 1024 /* EnumLiteral */) {
39693 var firstEnum = getParentOfSymbol(first.symbol);
39694 for (var i = 1; i < types.length; i++) {
39695 var other = types[i];
39696 if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
39697 return false;
39698 }
39699 }
39700 return true;
39701 }
39702 return false;
39703 }
39704 function removeSubtypes(types, primitivesOnly) {
39705 var len = types.length;
39706 if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
39707 return true;
39708 }
39709 var i = len;
39710 var count = 0;
39711 while (i > 0) {
39712 i--;
39713 var source = types[i];
39714 for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
39715 var target = types_7[_i];
39716 if (source !== target) {
39717 if (count === 100000) {
39718 // After 100000 subtype checks we estimate the remaining amount of work by assuming the
39719 // same ratio of checks per element. If the estimated number of remaining type checks is
39720 // greater than an upper limit we deem the union type too complex to represent. The
39721 // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
39722 // caps union types at 5000 unique literal types and 1000 unique object types.
39723 var estimatedCount = (count / (len - i)) * len;
39724 if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
39725 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
39726 return false;
39727 }
39728 }
39729 count++;
39730 if (isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
39731 !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
39732 isTypeDerivedFrom(source, target))) {
39733 ts.orderedRemoveItemAt(types, i);
39734 break;
39735 }
39736 }
39737 }
39738 }
39739 return true;
39740 }
39741 function removeRedundantLiteralTypes(types, includes) {
39742 var i = types.length;
39743 while (i > 0) {
39744 i--;
39745 var t = types[i];
39746 var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
39747 t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
39748 t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
39749 t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
39750 isFreshLiteralType(t) && containsType(types, t.regularType);
39751 if (remove) {
39752 ts.orderedRemoveItemAt(types, i);
39753 }
39754 }
39755 }
39756 // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
39757 // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
39758 // of other types. Subtype reduction is expensive for large union types and is possible only when union
39759 // types are known not to circularly reference themselves (as is the case with union types created by
39760 // expression constructs such as array literals and the || and ?: operators). Named types can
39761 // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
39762 // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
39763 function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
39764 if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
39765 if (types.length === 0) {
39766 return neverType;
39767 }
39768 if (types.length === 1) {
39769 return types[0];
39770 }
39771 var typeSet = [];
39772 var includes = addTypesToUnion(typeSet, 0, types);
39773 if (unionReduction !== 0 /* None */) {
39774 if (includes & 3 /* AnyOrUnknown */) {
39775 return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
39776 }
39777 switch (unionReduction) {
39778 case 1 /* Literal */:
39779 if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
39780 removeRedundantLiteralTypes(typeSet, includes);
39781 }
39782 break;
39783 case 2 /* Subtype */:
39784 if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
39785 return errorType;
39786 }
39787 break;
39788 }
39789 if (typeSet.length === 0) {
39790 return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType :
39791 includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
39792 neverType;
39793 }
39794 }
39795 return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments);
39796 }
39797 function getUnionTypePredicate(signatures) {
39798 var first;
39799 var types = [];
39800 for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
39801 var sig = signatures_2[_i];
39802 var pred = getTypePredicateOfSignature(sig);
39803 if (!pred) {
39804 continue;
39805 }
39806 if (first) {
39807 if (!typePredicateKindsMatch(first, pred)) {
39808 // No common type predicate.
39809 return undefined;
39810 }
39811 }
39812 else {
39813 first = pred;
39814 }
39815 types.push(pred.type);
39816 }
39817 if (!first) {
39818 // No union signatures had a type predicate.
39819 return undefined;
39820 }
39821 var unionType = getUnionType(types);
39822 return ts.isIdentifierTypePredicate(first)
39823 ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType)
39824 : createThisTypePredicate(unionType);
39825 }
39826 function typePredicateKindsMatch(a, b) {
39827 return ts.isIdentifierTypePredicate(a)
39828 ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex
39829 : !ts.isIdentifierTypePredicate(b);
39830 }
39831 // This function assumes the constituent type list is sorted and deduplicated.
39832 function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
39833 if (types.length === 0) {
39834 return neverType;
39835 }
39836 if (types.length === 1) {
39837 return types[0];
39838 }
39839 var id = getTypeListId(types);
39840 var type = unionTypes.get(id);
39841 if (!type) {
39842 type = createType(1048576 /* Union */);
39843 unionTypes.set(id, type);
39844 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
39845 type.types = types;
39846 /*
39847 Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
39848 For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
39849 (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
39850 It's important that we create equivalent union types only once, so that's an unfortunate side effect.
39851 */
39852 type.aliasSymbol = aliasSymbol;
39853 type.aliasTypeArguments = aliasTypeArguments;
39854 }
39855 return type;
39856 }
39857 function getTypeFromUnionTypeNode(node) {
39858 var links = getNodeLinks(node);
39859 if (!links.resolvedType) {
39860 var aliasSymbol = getAliasSymbolForTypeNode(node);
39861 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
39862 }
39863 return links.resolvedType;
39864 }
39865 function addTypeToIntersection(typeSet, includes, type) {
39866 var flags = type.flags;
39867 if (flags & 2097152 /* Intersection */) {
39868 return addTypesToIntersection(typeSet, includes, type.types);
39869 }
39870 if (isEmptyAnonymousObjectType(type)) {
39871 if (!(includes & 8388608 /* IncludesEmptyObject */)) {
39872 includes |= 8388608 /* IncludesEmptyObject */;
39873 typeSet.push(type);
39874 }
39875 }
39876 else {
39877 includes |= flags & 1835007 /* IncludesMask */;
39878 if (flags & 3 /* AnyOrUnknown */) {
39879 if (type === wildcardType)
39880 includes |= 4194304 /* IncludesWildcard */;
39881 }
39882 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) {
39883 typeSet.push(type);
39884 }
39885 }
39886 return includes;
39887 }
39888 // Add the given types to the given type set. Order is preserved, freshness is removed from literal
39889 // types, duplicates are removed, and nested types of the given kind are flattened into the set.
39890 function addTypesToIntersection(typeSet, includes, types) {
39891 for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
39892 var type = types_8[_i];
39893 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
39894 }
39895 return includes;
39896 }
39897 function removeRedundantPrimitiveTypes(types, includes) {
39898 var i = types.length;
39899 while (i > 0) {
39900 i--;
39901 var t = types[i];
39902 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
39903 t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
39904 t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
39905 t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
39906 if (remove) {
39907 ts.orderedRemoveItemAt(types, i);
39908 }
39909 }
39910 }
39911 // Check that the given type has a match in every union. A given type is matched by
39912 // an identical type, and a literal type is additionally matched by its corresponding
39913 // primitive type.
39914 function eachUnionContains(unionTypes, type) {
39915 for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
39916 var u = unionTypes_1[_i];
39917 if (!containsType(u.types, type)) {
39918 var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
39919 type.flags & 256 /* NumberLiteral */ ? numberType :
39920 type.flags & 2048 /* BigIntLiteral */ ? bigintType :
39921 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
39922 undefined;
39923 if (!primitive || !containsType(u.types, primitive)) {
39924 return false;
39925 }
39926 }
39927 }
39928 return true;
39929 }
39930 // If the given list of types contains more than one union of primitive types, replace the
39931 // first with a union containing an intersection of those primitive types, then remove the
39932 // other unions and return true. Otherwise, do nothing and return false.
39933 function intersectUnionsOfPrimitiveTypes(types) {
39934 var unionTypes;
39935 var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); });
39936 if (index < 0) {
39937 return false;
39938 }
39939 var i = index + 1;
39940 // Remove all but the first union of primitive types and collect them in
39941 // the unionTypes array.
39942 while (i < types.length) {
39943 var t = types[i];
39944 if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) {
39945 (unionTypes || (unionTypes = [types[index]])).push(t);
39946 ts.orderedRemoveItemAt(types, i);
39947 }
39948 else {
39949 i++;
39950 }
39951 }
39952 // Return false if there was only one union of primitive types
39953 if (!unionTypes) {
39954 return false;
39955 }
39956 // We have more than one union of primitive types, now intersect them. For each
39957 // type in each union we check if the type is matched in every union and if so
39958 // we include it in the result.
39959 var checked = [];
39960 var result = [];
39961 for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
39962 var u = unionTypes_2[_i];
39963 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
39964 var t = _b[_a];
39965 if (insertType(checked, t)) {
39966 if (eachUnionContains(unionTypes, t)) {
39967 insertType(result, t);
39968 }
39969 }
39970 }
39971 }
39972 // Finally replace the first union with the result
39973 types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */);
39974 return true;
39975 }
39976 // We normalize combinations of intersection and union types based on the distributive property of the '&'
39977 // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
39978 // types with union type constituents into equivalent union types with intersection type constituents and
39979 // effectively ensure that union types are always at the top level in type representations.
39980 //
39981 // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
39982 // type operator and we can't reduce those because we want to support recursive intersection types. For example,
39983 // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
39984 // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
39985 // for intersections of types with signatures can be deterministic.
39986 function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
39987 var typeSet = [];
39988 var includes = addTypesToIntersection(typeSet, 0, types);
39989 if (includes & 131072 /* Never */) {
39990 return neverType;
39991 }
39992 if (includes & 1 /* Any */) {
39993 return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType;
39994 }
39995 if (!strictNullChecks && includes & 98304 /* Nullable */) {
39996 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
39997 }
39998 if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
39999 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
40000 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
40001 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
40002 removeRedundantPrimitiveTypes(typeSet, includes);
40003 }
40004 if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
40005 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
40006 }
40007 if (typeSet.length === 0) {
40008 return unknownType;
40009 }
40010 if (typeSet.length === 1) {
40011 return typeSet[0];
40012 }
40013 if (includes & 1048576 /* Union */) {
40014 if (intersectUnionsOfPrimitiveTypes(typeSet)) {
40015 // When the intersection creates a reduced set (which might mean that *all* union types have
40016 // disappeared), we restart the operation to get a new set of combined flags. Once we have
40017 // reduced we'll never reduce again, so this occurs at most once.
40018 return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
40019 }
40020 // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
40021 // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
40022 var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
40023 var unionType = typeSet[unionIndex_1];
40024 return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
40025 }
40026 var id = getTypeListId(typeSet);
40027 var type = intersectionTypes.get(id);
40028 if (!type) {
40029 type = createType(2097152 /* Intersection */);
40030 intersectionTypes.set(id, type);
40031 type.objectFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
40032 type.types = typeSet;
40033 type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
40034 type.aliasTypeArguments = aliasTypeArguments;
40035 }
40036 return type;
40037 }
40038 function getTypeFromIntersectionTypeNode(node) {
40039 var links = getNodeLinks(node);
40040 if (!links.resolvedType) {
40041 var aliasSymbol = getAliasSymbolForTypeNode(node);
40042 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
40043 }
40044 return links.resolvedType;
40045 }
40046 function createIndexType(type, stringsOnly) {
40047 var result = createType(4194304 /* Index */);
40048 result.type = type;
40049 result.stringsOnly = stringsOnly;
40050 return result;
40051 }
40052 function getIndexTypeForGenericType(type, stringsOnly) {
40053 return stringsOnly ?
40054 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
40055 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
40056 }
40057 function getLiteralTypeFromPropertyName(name) {
40058 return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
40059 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
40060 }
40061 function getBigIntLiteralType(node) {
40062 return getLiteralType({
40063 negative: false,
40064 base10Value: ts.parsePseudoBigInt(node.text)
40065 });
40066 }
40067 function getLiteralTypeFromProperty(prop, include) {
40068 if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
40069 var type = getLateBoundSymbol(prop).nameType;
40070 if (!type && !ts.isKnownSymbol(prop)) {
40071 if (prop.escapedName === "default" /* Default */) {
40072 type = getLiteralType("default");
40073 }
40074 else {
40075 var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
40076 type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
40077 }
40078 }
40079 if (type && type.flags & include) {
40080 return type;
40081 }
40082 }
40083 return neverType;
40084 }
40085 function getLiteralTypeFromProperties(type, include) {
40086 return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
40087 }
40088 function getNonEnumNumberIndexInfo(type) {
40089 var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
40090 return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
40091 }
40092 function getIndexType(type, stringsOnly) {
40093 if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
40094 return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) :
40095 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) :
40096 maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) :
40097 ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) :
40098 type === wildcardType ? wildcardType :
40099 type.flags & 1 /* Any */ ? keyofConstraintType :
40100 stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
40101 getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
40102 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
40103 getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
40104 }
40105 function getExtractStringType(type) {
40106 if (keyofStringsOnly) {
40107 return type;
40108 }
40109 var extractTypeAlias = getGlobalExtractSymbol();
40110 return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
40111 }
40112 function getIndexTypeOrString(type) {
40113 var indexType = getExtractStringType(getIndexType(type));
40114 return indexType.flags & 131072 /* Never */ ? stringType : indexType;
40115 }
40116 function getTypeFromTypeOperatorNode(node) {
40117 var links = getNodeLinks(node);
40118 if (!links.resolvedType) {
40119 switch (node.operator) {
40120 case 129 /* KeyOfKeyword */:
40121 links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
40122 break;
40123 case 142 /* UniqueKeyword */:
40124 links.resolvedType = node.type.kind === 139 /* SymbolKeyword */
40125 ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
40126 : errorType;
40127 break;
40128 case 133 /* ReadonlyKeyword */:
40129 links.resolvedType = getTypeFromTypeNode(node.type);
40130 break;
40131 }
40132 }
40133 return links.resolvedType; // TODO: GH#18217
40134 }
40135 function createIndexedAccessType(objectType, indexType) {
40136 var type = createType(8388608 /* IndexedAccess */);
40137 type.objectType = objectType;
40138 type.indexType = indexType;
40139 return type;
40140 }
40141 /**
40142 * Returns if a type is or consists of a JSLiteral object type
40143 * In addition to objects which are directly literals,
40144 * * unions where every element is a jsliteral
40145 * * intersections where at least one element is a jsliteral
40146 * * and instantiable types constrained to a jsliteral
40147 * Should all count as literals and not print errors on access or assignment of possibly existing properties.
40148 * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
40149 */
40150 function isJSLiteralType(type) {
40151 if (noImplicitAny) {
40152 return false; // Flag is meaningless under `noImplicitAny` mode
40153 }
40154 if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
40155 return true;
40156 }
40157 if (type.flags & 1048576 /* Union */) {
40158 return ts.every(type.types, isJSLiteralType);
40159 }
40160 if (type.flags & 2097152 /* Intersection */) {
40161 return ts.some(type.types, isJSLiteralType);
40162 }
40163 if (type.flags & 63176704 /* Instantiable */) {
40164 return isJSLiteralType(getResolvedBaseConstraint(type));
40165 }
40166 return false;
40167 }
40168 function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) {
40169 var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined;
40170 var propName = isTypeUsableAsPropertyName(indexType) ?
40171 getPropertyNameFromType(indexType) :
40172 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
40173 ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
40174 accessNode && ts.isPropertyName(accessNode) ?
40175 // late bound names are handled in the first branch, so here we only need to handle normal names
40176 ts.getPropertyNameForPropertyNameNode(accessNode) :
40177 undefined;
40178 if (propName !== undefined) {
40179 var prop = getPropertyOfType(objectType, propName);
40180 if (prop) {
40181 if (accessExpression) {
40182 markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */);
40183 if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) {
40184 error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
40185 return missingType;
40186 }
40187 if (cacheSymbol) {
40188 getNodeLinks(accessNode).resolvedSymbol = prop;
40189 }
40190 }
40191 var propType = getTypeOfSymbol(prop);
40192 return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
40193 getFlowTypeOfReference(accessExpression, propType) :
40194 propType;
40195 }
40196 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
40197 if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) {
40198 var indexNode = getIndexNodeForAccessExpression(accessNode);
40199 if (isTupleType(objectType)) {
40200 error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
40201 }
40202 else {
40203 error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
40204 }
40205 }
40206 return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
40207 }
40208 }
40209 if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
40210 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
40211 return objectType;
40212 }
40213 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) ||
40214 getIndexInfoOfType(objectType, 0 /* String */) ||
40215 undefined;
40216 if (indexInfo) {
40217 if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
40218 var indexNode = getIndexNodeForAccessExpression(accessNode);
40219 error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
40220 }
40221 else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
40222 error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
40223 }
40224 return indexInfo.type;
40225 }
40226 if (indexType.flags & 131072 /* Never */) {
40227 return neverType;
40228 }
40229 if (isJSLiteralType(objectType)) {
40230 return anyType;
40231 }
40232 if (accessExpression && !isConstEnumObjectType(objectType)) {
40233 if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
40234 error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
40235 }
40236 else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
40237 if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
40238 error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
40239 }
40240 else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
40241 error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
40242 }
40243 else {
40244 var suggestion = void 0;
40245 if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
40246 if (suggestion !== undefined) {
40247 error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
40248 }
40249 }
40250 else {
40251 error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType));
40252 }
40253 }
40254 }
40255 return missingType;
40256 }
40257 }
40258 if (isJSLiteralType(objectType)) {
40259 return anyType;
40260 }
40261 if (accessNode) {
40262 var indexNode = getIndexNodeForAccessExpression(accessNode);
40263 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
40264 error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
40265 }
40266 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
40267 error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
40268 }
40269 else {
40270 error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
40271 }
40272 }
40273 if (isTypeAny(indexType)) {
40274 return indexType;
40275 }
40276 return missingType;
40277 }
40278 function getIndexNodeForAccessExpression(accessNode) {
40279 return accessNode.kind === 190 /* ElementAccessExpression */
40280 ? accessNode.argumentExpression
40281 : accessNode.kind === 180 /* IndexedAccessType */
40282 ? accessNode.indexType
40283 : accessNode.kind === 149 /* ComputedPropertyName */
40284 ? accessNode.expression
40285 : accessNode;
40286 }
40287 function isGenericObjectType(type) {
40288 return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 131072 /* GenericMappedType */);
40289 }
40290 function isGenericIndexType(type) {
40291 return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */);
40292 }
40293 function getSimplifiedType(type) {
40294 return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type;
40295 }
40296 function distributeIndexOverObjectType(objectType, indexType) {
40297 // (T | U)[K] -> T[K] | U[K]
40298 if (objectType.flags & 1048576 /* Union */) {
40299 return mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); });
40300 }
40301 // (T & U)[K] -> T[K] & U[K]
40302 if (objectType.flags & 2097152 /* Intersection */) {
40303 return getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }));
40304 }
40305 }
40306 // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
40307 // the type itself if no transformation is possible.
40308 function getSimplifiedIndexedAccessType(type) {
40309 if (type.simplified) {
40310 return type.simplified === circularConstraintType ? type : type.simplified;
40311 }
40312 type.simplified = circularConstraintType;
40313 // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
40314 // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
40315 var objectType = getSimplifiedType(type.objectType);
40316 var indexType = getSimplifiedType(type.indexType);
40317 // T[A | B] -> T[A] | T[B]
40318 if (indexType.flags & 1048576 /* Union */) {
40319 return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); });
40320 }
40321 // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
40322 if (!(indexType.flags & 63176704 /* Instantiable */)) {
40323 var simplified = distributeIndexOverObjectType(objectType, indexType);
40324 if (simplified) {
40325 return type.simplified = simplified;
40326 }
40327 }
40328 // So ultimately:
40329 // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2]
40330 // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
40331 // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
40332 // construct the type Box<T[X]>.
40333 if (isGenericMappedType(objectType)) {
40334 return type.simplified = mapType(substituteIndexedMappedType(objectType, type.indexType), getSimplifiedType);
40335 }
40336 return type.simplified = type;
40337 }
40338 function substituteIndexedMappedType(objectType, index) {
40339 var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
40340 var templateMapper = combineTypeMappers(objectType.mapper, mapper);
40341 return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
40342 }
40343 function getIndexedAccessType(objectType, indexType, accessNode, missingType) {
40344 if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; }
40345 if (objectType === wildcardType || indexType === wildcardType) {
40346 return wildcardType;
40347 }
40348 // If the index type is generic, or if the object type is generic and doesn't originate in an expression,
40349 // we are performing a higher-order index access where we cannot meaningfully access the properties of the
40350 // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
40351 // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]'
40352 // has always been resolved eagerly using the constraint type of 'this' at the given location.
40353 if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 180 /* IndexedAccessType */) && isGenericObjectType(objectType)) {
40354 if (objectType.flags & 3 /* AnyOrUnknown */) {
40355 return objectType;
40356 }
40357 // Defer the operation by creating an indexed access type.
40358 var id = objectType.id + "," + indexType.id;
40359 var type = indexedAccessTypes.get(id);
40360 if (!type) {
40361 indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType));
40362 }
40363 return type;
40364 }
40365 // In the following we resolve T[K] to the type of the property in T selected by K.
40366 // We treat boolean as different from other unions to improve errors;
40367 // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
40368 var apparentObjectType = getApparentType(objectType);
40369 if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
40370 var propTypes = [];
40371 var wasMissingProp = false;
40372 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
40373 var t = _a[_i];
40374 var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType);
40375 if (propType === missingType) {
40376 if (!accessNode) {
40377 // If there's no error node, we can immeditely stop, since error reporting is off
40378 return missingType;
40379 }
40380 else {
40381 // Otherwise we set a flag and return at the end of the loop so we still mark all errors
40382 wasMissingProp = true;
40383 }
40384 }
40385 propTypes.push(propType);
40386 }
40387 if (wasMissingProp) {
40388 return missingType;
40389 }
40390 return getUnionType(propTypes);
40391 }
40392 return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType);
40393 }
40394 function getTypeFromIndexedAccessTypeNode(node) {
40395 var links = getNodeLinks(node);
40396 if (!links.resolvedType) {
40397 var objectType = getTypeFromTypeNode(node.objectType);
40398 var indexType = getTypeFromTypeNode(node.indexType);
40399 var resolved = getIndexedAccessType(objectType, indexType, node);
40400 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
40401 resolved.objectType === objectType &&
40402 resolved.indexType === indexType ?
40403 getConstrainedTypeVariable(resolved, node) : resolved;
40404 }
40405 return links.resolvedType;
40406 }
40407 function getTypeFromMappedTypeNode(node) {
40408 var links = getNodeLinks(node);
40409 if (!links.resolvedType) {
40410 var type = createObjectType(32 /* Mapped */, node.symbol);
40411 type.declaration = node;
40412 type.aliasSymbol = getAliasSymbolForTypeNode(node);
40413 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
40414 links.resolvedType = type;
40415 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
40416 // references itself through one or more type aliases.
40417 getConstraintTypeFromMappedType(type);
40418 }
40419 return links.resolvedType;
40420 }
40421 function getActualTypeVariable(type) {
40422 return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type;
40423 }
40424 /**
40425 * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
40426 */
40427 function isIntersectionEmpty(type1, type2) {
40428 return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
40429 }
40430 function getConditionalType(root, mapper) {
40431 var checkType = instantiateType(root.checkType, mapper);
40432 var extendsType = instantiateType(root.extendsType, mapper);
40433 if (checkType === wildcardType || extendsType === wildcardType) {
40434 return wildcardType;
40435 }
40436 var trueType = instantiateType(root.trueType, mapper);
40437 var falseType = instantiateType(root.falseType, mapper);
40438 var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType);
40439 var result = conditionalTypes.get(instantiationId);
40440 if (result) {
40441 return result;
40442 }
40443 var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType);
40444 conditionalTypes.set(instantiationId, newResult);
40445 return newResult;
40446 }
40447 function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) {
40448 // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
40449 if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
40450 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
40451 return trueType;
40452 }
40453 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
40454 return neverType;
40455 }
40456 }
40457 else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
40458 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
40459 return neverType;
40460 }
40461 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
40462 return falseType;
40463 }
40464 }
40465 var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */);
40466 var combinedMapper;
40467 if (root.inferTypeParameters) {
40468 var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
40469 if (!checkTypeInstantiable) {
40470 // We don't want inferences from constraints as they may cause us to eagerly resolve the
40471 // conditional type instead of deferring resolution. Also, we always want strict function
40472 // types rules (i.e. proper contravariance) for inferences.
40473 inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
40474 }
40475 combinedMapper = combineTypeMappers(mapper, context.mapper);
40476 }
40477 // Instantiate the extends type including inferences for 'infer T' type parameters
40478 var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
40479 // We attempt to resolve the conditional type only when the check and extends types are non-generic
40480 if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) {
40481 if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) {
40482 return trueType;
40483 }
40484 // Return union of trueType and falseType for 'any' since it matches anything
40485 if (checkType.flags & 1 /* Any */) {
40486 return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]);
40487 }
40488 // Return falseType for a definitely false extends check. We check an instantiations of the two
40489 // types with type parameters mapped to the wildcard type, the most permissive instantiations
40490 // possible (the wildcard type is assignable to and from all types). If those are not related,
40491 // then no instantiations will be and we can just return the false branch type.
40492 if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) {
40493 return falseType;
40494 }
40495 // Return trueType for a definitely true extends check. We check instantiations of the two
40496 // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
40497 // that has no constraint. This ensures that, for example, the type
40498 // type Foo<T extends { x: any }> = T extends { x: string } ? string : number
40499 // doesn't immediately resolve to 'string' instead of being deferred.
40500 if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
40501 return instantiateType(root.trueType, combinedMapper || mapper);
40502 }
40503 }
40504 // Return a deferred type for a check that is neither definitely true nor definitely false
40505 return getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType);
40506 }
40507 function getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType) {
40508 var erasedCheckType = getActualTypeVariable(checkType);
40509 var result = createType(16777216 /* Conditional */);
40510 result.root = root;
40511 result.checkType = erasedCheckType;
40512 result.extendsType = extendsType;
40513 result.mapper = mapper;
40514 result.combinedMapper = combinedMapper;
40515 result.trueType = trueType;
40516 result.falseType = falseType;
40517 result.aliasSymbol = root.aliasSymbol;
40518 result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
40519 return result;
40520 }
40521 function getInferredTrueTypeFromConditionalType(type) {
40522 return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper));
40523 }
40524 function getInferTypeParameters(node) {
40525 var result;
40526 if (node.locals) {
40527 node.locals.forEach(function (symbol) {
40528 if (symbol.flags & 262144 /* TypeParameter */) {
40529 result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
40530 }
40531 });
40532 }
40533 return result;
40534 }
40535 function isPossiblyReferencedInConditionalType(tp, node) {
40536 if (isTypeParameterPossiblyReferenced(tp, node)) {
40537 return true;
40538 }
40539 while (node) {
40540 if (node.kind === 175 /* ConditionalType */) {
40541 if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) {
40542 return true;
40543 }
40544 }
40545 node = node.parent;
40546 }
40547 return false;
40548 }
40549 function getTypeFromConditionalTypeNode(node) {
40550 var links = getNodeLinks(node);
40551 if (!links.resolvedType) {
40552 var checkType = getTypeFromTypeNode(node.checkType);
40553 var aliasSymbol = getAliasSymbolForTypeNode(node);
40554 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
40555 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
40556 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); });
40557 var root = {
40558 node: node,
40559 checkType: checkType,
40560 extendsType: getTypeFromTypeNode(node.extendsType),
40561 trueType: getTypeFromTypeNode(node.trueType),
40562 falseType: getTypeFromTypeNode(node.falseType),
40563 isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
40564 inferTypeParameters: getInferTypeParameters(node),
40565 outerTypeParameters: outerTypeParameters,
40566 instantiations: undefined,
40567 aliasSymbol: aliasSymbol,
40568 aliasTypeArguments: aliasTypeArguments
40569 };
40570 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
40571 if (outerTypeParameters) {
40572 root.instantiations = ts.createMap();
40573 root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
40574 }
40575 }
40576 return links.resolvedType;
40577 }
40578 function getTypeFromInferTypeNode(node) {
40579 var links = getNodeLinks(node);
40580 if (!links.resolvedType) {
40581 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
40582 }
40583 return links.resolvedType;
40584 }
40585 function getIdentifierChain(node) {
40586 if (ts.isIdentifier(node)) {
40587 return [node];
40588 }
40589 else {
40590 return ts.append(getIdentifierChain(node.left), node.right);
40591 }
40592 }
40593 function getTypeFromImportTypeNode(node) {
40594 var links = getNodeLinks(node);
40595 if (!links.resolvedType) {
40596 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
40597 error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
40598 links.resolvedSymbol = unknownSymbol;
40599 return links.resolvedType = errorType;
40600 }
40601 if (!ts.isLiteralImportTypeNode(node)) {
40602 error(node.argument, ts.Diagnostics.String_literal_expected);
40603 links.resolvedSymbol = unknownSymbol;
40604 return links.resolvedType = errorType;
40605 }
40606 var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */;
40607 // TODO: Future work: support unions/generics/whatever via a deferred import-type
40608 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
40609 if (!innerModuleSymbol) {
40610 links.resolvedSymbol = unknownSymbol;
40611 return links.resolvedType = errorType;
40612 }
40613 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
40614 if (!ts.nodeIsMissing(node.qualifier)) {
40615 var nameStack = getIdentifierChain(node.qualifier);
40616 var currentNamespace = moduleSymbol;
40617 var current = void 0;
40618 while (current = nameStack.shift()) {
40619 var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
40620 var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning);
40621 if (!next) {
40622 error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
40623 return links.resolvedType = errorType;
40624 }
40625 getNodeLinks(current).resolvedSymbol = next;
40626 getNodeLinks(current.parent).resolvedSymbol = next;
40627 currentNamespace = next;
40628 }
40629 resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
40630 }
40631 else {
40632 if (moduleSymbol.flags & targetMeaning) {
40633 resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
40634 }
40635 else {
40636 var errorMessage = targetMeaning === 67220415 /* Value */
40637 ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
40638 : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
40639 error(node, errorMessage, node.argument.literal.text);
40640 links.resolvedSymbol = unknownSymbol;
40641 links.resolvedType = errorType;
40642 }
40643 }
40644 }
40645 return links.resolvedType; // TODO: GH#18217
40646 }
40647 function resolveImportSymbolType(node, links, symbol, meaning) {
40648 var resolvedSymbol = resolveSymbol(symbol);
40649 links.resolvedSymbol = resolvedSymbol;
40650 if (meaning === 67220415 /* Value */) {
40651 return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
40652 }
40653 else {
40654 return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
40655 }
40656 }
40657 function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
40658 var links = getNodeLinks(node);
40659 if (!links.resolvedType) {
40660 // Deferred resolution of members is handled by resolveObjectTypeMembers
40661 var aliasSymbol = getAliasSymbolForTypeNode(node);
40662 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
40663 links.resolvedType = emptyTypeLiteralType;
40664 }
40665 else {
40666 var type = createObjectType(16 /* Anonymous */, node.symbol);
40667 type.aliasSymbol = aliasSymbol;
40668 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
40669 if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
40670 type = createArrayType(type);
40671 }
40672 links.resolvedType = type;
40673 }
40674 }
40675 return links.resolvedType;
40676 }
40677 function getAliasSymbolForTypeNode(node) {
40678 return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined;
40679 }
40680 function getTypeArgumentsForAliasSymbol(symbol) {
40681 return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
40682 }
40683 function isNonGenericObjectType(type) {
40684 return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
40685 }
40686 /**
40687 * Since the source of spread types are object literals, which are not binary,
40688 * this function should be called in a left folding style, with left = previous result of getSpreadType
40689 * and right = the new element to be spread.
40690 */
40691 function getSpreadType(left, right, symbol, objectFlags, readonly) {
40692 if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
40693 return anyType;
40694 }
40695 if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
40696 return unknownType;
40697 }
40698 if (left.flags & 131072 /* Never */) {
40699 return right;
40700 }
40701 if (right.flags & 131072 /* Never */) {
40702 return left;
40703 }
40704 if (left.flags & 1048576 /* Union */) {
40705 return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
40706 }
40707 if (right.flags & 1048576 /* Union */) {
40708 return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
40709 }
40710 if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
40711 return left;
40712 }
40713 if (isGenericObjectType(left) || isGenericObjectType(right)) {
40714 if (isEmptyObjectType(left)) {
40715 return right;
40716 }
40717 // When the left type is an intersection, we may need to merge the last constituent of the
40718 // intersection with the right type. For example when the left type is 'T & { a: string }'
40719 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
40720 if (left.flags & 2097152 /* Intersection */) {
40721 var types = left.types;
40722 var lastLeft = types[types.length - 1];
40723 if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
40724 return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
40725 }
40726 }
40727 return getIntersectionType([left, right]);
40728 }
40729 var members = ts.createSymbolTable();
40730 var skippedPrivateMembers = ts.createUnderscoreEscapedMap();
40731 var stringIndexInfo;
40732 var numberIndexInfo;
40733 if (left === emptyObjectType) {
40734 // for the first spread element, left === emptyObjectType, so take the right's string indexer
40735 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
40736 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
40737 }
40738 else {
40739 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
40740 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
40741 }
40742 for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
40743 var rightProp = _a[_i];
40744 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
40745 skippedPrivateMembers.set(rightProp.escapedName, true);
40746 }
40747 else if (isSpreadableProperty(rightProp)) {
40748 members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
40749 }
40750 }
40751 for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
40752 var leftProp = _c[_b];
40753 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
40754 continue;
40755 }
40756 if (members.has(leftProp.escapedName)) {
40757 var rightProp = members.get(leftProp.escapedName);
40758 var rightType = getTypeOfSymbol(rightProp);
40759 if (rightProp.flags & 16777216 /* Optional */) {
40760 var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
40761 var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
40762 var result = createSymbol(flags, leftProp.escapedName);
40763 result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
40764 result.leftSpread = leftProp;
40765 result.rightSpread = rightProp;
40766 result.declarations = declarations;
40767 result.nameType = leftProp.nameType;
40768 members.set(leftProp.escapedName, result);
40769 }
40770 }
40771 else {
40772 members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
40773 }
40774 }
40775 var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
40776 spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
40777 return spread;
40778 }
40779 /** We approximate own properties as non-methods plus methods that are inside the object literal */
40780 function isSpreadableProperty(prop) {
40781 return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
40782 !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); });
40783 }
40784 function getSpreadSymbol(prop, readonly) {
40785 var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
40786 if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
40787 return prop;
40788 }
40789 var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
40790 var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
40791 result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
40792 result.declarations = prop.declarations;
40793 result.nameType = prop.nameType;
40794 result.syntheticOrigin = prop;
40795 return result;
40796 }
40797 function getIndexInfoWithReadonly(info, readonly) {
40798 return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
40799 }
40800 function createLiteralType(flags, value, symbol) {
40801 var type = createType(flags);
40802 type.symbol = symbol;
40803 type.value = value;
40804 return type;
40805 }
40806 function getFreshTypeOfLiteralType(type) {
40807 if (type.flags & 2944 /* Literal */) {
40808 if (!type.freshType) {
40809 var freshType = createLiteralType(type.flags, type.value, type.symbol);
40810 freshType.regularType = type;
40811 freshType.freshType = freshType;
40812 type.freshType = freshType;
40813 }
40814 return type.freshType;
40815 }
40816 return type;
40817 }
40818 function getRegularTypeOfLiteralType(type) {
40819 return type.flags & 2944 /* Literal */ ? type.regularType :
40820 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) :
40821 type;
40822 }
40823 function isFreshLiteralType(type) {
40824 return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
40825 }
40826 function getLiteralType(value, enumId, symbol) {
40827 // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
40828 // where NNN is the text representation of a numeric literal and SSS are the characters
40829 // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
40830 // EEE is a unique id for the containing enum type.
40831 var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
40832 var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
40833 var type = literalTypes.get(key);
40834 if (!type) {
40835 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
40836 typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
40837 (enumId ? 1024 /* EnumLiteral */ : 0);
40838 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
40839 type.regularType = type;
40840 }
40841 return type;
40842 }
40843 function getTypeFromLiteralTypeNode(node) {
40844 var links = getNodeLinks(node);
40845 if (!links.resolvedType) {
40846 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
40847 }
40848 return links.resolvedType;
40849 }
40850 function createUniqueESSymbolType(symbol) {
40851 var type = createType(8192 /* UniqueESSymbol */);
40852 type.symbol = symbol;
40853 type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
40854 return type;
40855 }
40856 function getESSymbolLikeTypeForNode(node) {
40857 if (ts.isValidESSymbolDeclaration(node)) {
40858 var symbol = getSymbolOfNode(node);
40859 var links = getSymbolLinks(symbol);
40860 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
40861 }
40862 return esSymbolType;
40863 }
40864 function getThisType(node) {
40865 var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
40866 var parent = container && container.parent;
40867 if (parent && (ts.isClassLike(parent) || parent.kind === 241 /* InterfaceDeclaration */)) {
40868 if (!ts.hasModifier(container, 32 /* Static */) &&
40869 (container.kind !== 157 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) {
40870 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
40871 }
40872 }
40873 error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
40874 return errorType;
40875 }
40876 function getTypeFromThisTypeNode(node) {
40877 var links = getNodeLinks(node);
40878 if (!links.resolvedType) {
40879 links.resolvedType = getThisType(node);
40880 }
40881 return links.resolvedType;
40882 }
40883 function getTypeFromTypeNode(node) {
40884 switch (node.kind) {
40885 case 120 /* AnyKeyword */:
40886 case 289 /* JSDocAllType */:
40887 case 290 /* JSDocUnknownType */:
40888 return anyType;
40889 case 143 /* UnknownKeyword */:
40890 return unknownType;
40891 case 138 /* StringKeyword */:
40892 return stringType;
40893 case 135 /* NumberKeyword */:
40894 return numberType;
40895 case 146 /* BigIntKeyword */:
40896 return bigintType;
40897 case 123 /* BooleanKeyword */:
40898 return booleanType;
40899 case 139 /* SymbolKeyword */:
40900 return esSymbolType;
40901 case 106 /* VoidKeyword */:
40902 return voidType;
40903 case 141 /* UndefinedKeyword */:
40904 return undefinedType;
40905 case 96 /* NullKeyword */:
40906 return nullType;
40907 case 132 /* NeverKeyword */:
40908 return neverType;
40909 case 136 /* ObjectKeyword */:
40910 return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType;
40911 case 178 /* ThisType */:
40912 case 100 /* ThisKeyword */:
40913 return getTypeFromThisTypeNode(node);
40914 case 182 /* LiteralType */:
40915 return getTypeFromLiteralTypeNode(node);
40916 case 164 /* TypeReference */:
40917 return getTypeFromTypeReference(node);
40918 case 163 /* TypePredicate */:
40919 return booleanType;
40920 case 211 /* ExpressionWithTypeArguments */:
40921 return getTypeFromTypeReference(node);
40922 case 167 /* TypeQuery */:
40923 return getTypeFromTypeQueryNode(node);
40924 case 169 /* ArrayType */:
40925 return getTypeFromArrayTypeNode(node);
40926 case 170 /* TupleType */:
40927 return getTypeFromTupleTypeNode(node);
40928 case 171 /* OptionalType */:
40929 return getTypeFromOptionalTypeNode(node);
40930 case 173 /* UnionType */:
40931 return getTypeFromUnionTypeNode(node);
40932 case 174 /* IntersectionType */:
40933 return getTypeFromIntersectionTypeNode(node);
40934 case 291 /* JSDocNullableType */:
40935 return getTypeFromJSDocNullableTypeNode(node);
40936 case 293 /* JSDocOptionalType */:
40937 return addOptionality(getTypeFromTypeNode(node.type));
40938 case 177 /* ParenthesizedType */:
40939 case 172 /* RestType */:
40940 case 292 /* JSDocNonNullableType */:
40941 case 288 /* JSDocTypeExpression */:
40942 return getTypeFromTypeNode(node.type);
40943 case 295 /* JSDocVariadicType */:
40944 return getTypeFromJSDocVariadicType(node);
40945 case 165 /* FunctionType */:
40946 case 166 /* ConstructorType */:
40947 case 168 /* TypeLiteral */:
40948 case 297 /* JSDocTypeLiteral */:
40949 case 294 /* JSDocFunctionType */:
40950 case 298 /* JSDocSignature */:
40951 return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
40952 case 179 /* TypeOperator */:
40953 return getTypeFromTypeOperatorNode(node);
40954 case 180 /* IndexedAccessType */:
40955 return getTypeFromIndexedAccessTypeNode(node);
40956 case 181 /* MappedType */:
40957 return getTypeFromMappedTypeNode(node);
40958 case 175 /* ConditionalType */:
40959 return getTypeFromConditionalTypeNode(node);
40960 case 176 /* InferType */:
40961 return getTypeFromInferTypeNode(node);
40962 case 183 /* ImportType */:
40963 return getTypeFromImportTypeNode(node);
40964 // This function assumes that an identifier or qualified name is a type expression
40965 // Callers should first ensure this by calling isTypeNode
40966 case 72 /* Identifier */:
40967 case 148 /* QualifiedName */:
40968 var symbol = getSymbolAtLocation(node);
40969 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
40970 default:
40971 return errorType;
40972 }
40973 }
40974 function instantiateList(items, mapper, instantiator) {
40975 if (items && items.length) {
40976 for (var i = 0; i < items.length; i++) {
40977 var item = items[i];
40978 var mapped = instantiator(item, mapper);
40979 if (item !== mapped) {
40980 var result = i === 0 ? [] : items.slice(0, i);
40981 result.push(mapped);
40982 for (i++; i < items.length; i++) {
40983 result.push(instantiator(items[i], mapper));
40984 }
40985 return result;
40986 }
40987 }
40988 }
40989 return items;
40990 }
40991 function instantiateTypes(types, mapper) {
40992 return instantiateList(types, mapper, instantiateType);
40993 }
40994 function instantiateSignatures(signatures, mapper) {
40995 return instantiateList(signatures, mapper, instantiateSignature);
40996 }
40997 function makeUnaryTypeMapper(source, target) {
40998 return function (t) { return t === source ? target : t; };
40999 }
41000 function makeBinaryTypeMapper(source1, target1, source2, target2) {
41001 return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; };
41002 }
41003 function makeArrayTypeMapper(sources, targets) {
41004 return function (t) {
41005 for (var i = 0; i < sources.length; i++) {
41006 if (t === sources[i]) {
41007 return targets ? targets[i] : anyType;
41008 }
41009 }
41010 return t;
41011 };
41012 }
41013 function createTypeMapper(sources, targets) {
41014 ts.Debug.assert(targets === undefined || sources.length === targets.length);
41015 return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) :
41016 sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) :
41017 makeArrayTypeMapper(sources, targets);
41018 }
41019 function createTypeEraser(sources) {
41020 return createTypeMapper(sources, /*targets*/ undefined);
41021 }
41022 /**
41023 * Maps forward-references to later types parameters to the empty object type.
41024 * This is used during inference when instantiating type parameter defaults.
41025 */
41026 function createBackreferenceMapper(context, index) {
41027 return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? emptyObjectType : t; };
41028 }
41029 function combineTypeMappers(mapper1, mapper2) {
41030 if (!mapper1)
41031 return mapper2;
41032 if (!mapper2)
41033 return mapper1;
41034 return function (t) { return instantiateType(mapper1(t), mapper2); };
41035 }
41036 function createReplacementMapper(source, target, baseMapper) {
41037 return function (t) { return t === source ? target : baseMapper(t); };
41038 }
41039 function permissiveMapper(type) {
41040 return type.flags & 262144 /* TypeParameter */ ? wildcardType : type;
41041 }
41042 function getRestrictiveTypeParameter(tp) {
41043 return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
41044 tp.restrictiveInstantiation.constraint = unknownType,
41045 tp.restrictiveInstantiation);
41046 }
41047 function restrictiveMapper(type) {
41048 return type.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(type) : type;
41049 }
41050 function cloneTypeParameter(typeParameter) {
41051 var result = createTypeParameter(typeParameter.symbol);
41052 result.target = typeParameter;
41053 return result;
41054 }
41055 function instantiateTypePredicate(predicate, mapper) {
41056 if (ts.isIdentifierTypePredicate(predicate)) {
41057 return {
41058 kind: 1 /* Identifier */,
41059 parameterName: predicate.parameterName,
41060 parameterIndex: predicate.parameterIndex,
41061 type: instantiateType(predicate.type, mapper)
41062 };
41063 }
41064 else {
41065 return {
41066 kind: 0 /* This */,
41067 type: instantiateType(predicate.type, mapper)
41068 };
41069 }
41070 }
41071 function instantiateSignature(signature, mapper, eraseTypeParameters) {
41072 var freshTypeParameters;
41073 if (signature.typeParameters && !eraseTypeParameters) {
41074 // First create a fresh set of type parameters, then include a mapping from the old to the
41075 // new type parameters in the mapper function. Finally store this mapper in the new type
41076 // parameters such that we can use it when instantiating constraints.
41077 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
41078 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
41079 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
41080 var tp = freshTypeParameters_1[_i];
41081 tp.mapper = mapper;
41082 }
41083 }
41084 // Don't compute resolvedReturnType and resolvedTypePredicate now,
41085 // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
41086 // See GH#17600.
41087 var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol),
41088 /*resolvedReturnType*/ undefined,
41089 /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes);
41090 result.target = signature;
41091 result.mapper = mapper;
41092 return result;
41093 }
41094 function instantiateSymbol(symbol, mapper) {
41095 var links = getSymbolLinks(symbol);
41096 if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) {
41097 // If the type of the symbol is already resolved, and if that type could not possibly
41098 // be affected by instantiation, simply return the symbol itself.
41099 return symbol;
41100 }
41101 if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
41102 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
41103 // type mappers. This ensures that original type identities are properly preserved and that aliases
41104 // always reference a non-aliases.
41105 symbol = links.target;
41106 mapper = combineTypeMappers(links.mapper, mapper);
41107 }
41108 // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and
41109 // also transient so that we can just store data on it directly.
41110 var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
41111 result.declarations = symbol.declarations;
41112 result.parent = symbol.parent;
41113 result.target = symbol;
41114 result.mapper = mapper;
41115 if (symbol.valueDeclaration) {
41116 result.valueDeclaration = symbol.valueDeclaration;
41117 }
41118 if (symbol.nameType) {
41119 result.nameType = symbol.nameType;
41120 }
41121 return result;
41122 }
41123 function getAnonymousTypeInstantiation(type, mapper) {
41124 var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type;
41125 var symbol = target.symbol;
41126 var links = getSymbolLinks(symbol);
41127 var typeParameters = links.outerTypeParameters;
41128 if (!typeParameters) {
41129 // The first time an anonymous type is instantiated we compute and store a list of the type
41130 // parameters that are in scope (and therefore potentially referenced). For type literals that
41131 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
41132 // set of type parameters to those that are possibly referenced in the literal.
41133 var declaration_1 = symbol.declarations[0];
41134 if (ts.isInJSFile(declaration_1)) {
41135 var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
41136 if (paramTag) {
41137 var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
41138 if (paramSymbol) {
41139 declaration_1 = paramSymbol.valueDeclaration;
41140 }
41141 }
41142 }
41143 var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
41144 if (isJSConstructor(declaration_1)) {
41145 var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
41146 outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
41147 }
41148 typeParameters = outerTypeParameters || ts.emptyArray;
41149 typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ?
41150 ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) :
41151 typeParameters;
41152 links.outerTypeParameters = typeParameters;
41153 if (typeParameters.length) {
41154 links.instantiations = ts.createMap();
41155 links.instantiations.set(getTypeListId(typeParameters), target);
41156 }
41157 }
41158 if (typeParameters.length) {
41159 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
41160 // mapper to the type parameters to produce the effective list of type arguments, and compute the
41161 // instantiation cache key from the type IDs of the type arguments.
41162 var combinedMapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper;
41163 var typeArguments = ts.map(typeParameters, combinedMapper);
41164 var id = getTypeListId(typeArguments);
41165 var result = links.instantiations.get(id);
41166 if (!result) {
41167 var newMapper = createTypeMapper(typeParameters, typeArguments);
41168 result = target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper);
41169 links.instantiations.set(id, result);
41170 }
41171 return result;
41172 }
41173 return type;
41174 }
41175 function maybeTypeParameterReference(node) {
41176 return !(node.kind === 148 /* QualifiedName */ ||
41177 node.parent.kind === 164 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName);
41178 }
41179 function isTypeParameterPossiblyReferenced(tp, node) {
41180 // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
41181 // between the node and the type parameter declaration, if the node contains actual references to the
41182 // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
41183 if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
41184 var container_3 = tp.symbol.declarations[0].parent;
41185 if (ts.findAncestor(node, function (n) { return n.kind === 218 /* Block */ ? "quit" : n === container_3; })) {
41186 return !!ts.forEachChild(node, containsReference);
41187 }
41188 }
41189 return true;
41190 function containsReference(node) {
41191 switch (node.kind) {
41192 case 178 /* ThisType */:
41193 return !!tp.isThisType;
41194 case 72 /* Identifier */:
41195 return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
41196 getTypeFromTypeNode(node) === tp;
41197 case 167 /* TypeQuery */:
41198 return true;
41199 }
41200 return !!ts.forEachChild(node, containsReference);
41201 }
41202 }
41203 function getHomomorphicTypeVariable(type) {
41204 var constraintType = getConstraintTypeFromMappedType(type);
41205 if (constraintType.flags & 4194304 /* Index */) {
41206 var typeVariable = getActualTypeVariable(constraintType.type);
41207 if (typeVariable.flags & 262144 /* TypeParameter */) {
41208 return typeVariable;
41209 }
41210 }
41211 return undefined;
41212 }
41213 function instantiateMappedType(type, mapper) {
41214 // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
41215 // operation depends on T as follows:
41216 // * If T is a primitive type no mapping is performed and the result is simply T.
41217 // * If T is a union type we distribute the mapped type over the union.
41218 // * If T is an array we map to an array where the element type has been transformed.
41219 // * If T is a tuple we map to a tuple where the element types have been transformed.
41220 // * Otherwise we map to an object type where the type of each property has been transformed.
41221 // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
41222 // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
41223 // { [P in keyof A]: X } | undefined.
41224 var typeVariable = getHomomorphicTypeVariable(type);
41225 if (typeVariable) {
41226 var mappedTypeVariable = instantiateType(typeVariable, mapper);
41227 if (typeVariable !== mappedTypeVariable) {
41228 return mapType(mappedTypeVariable, function (t) {
41229 if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
41230 var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
41231 return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
41232 isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
41233 instantiateAnonymousType(type, replacementMapper);
41234 }
41235 return t;
41236 });
41237 }
41238 }
41239 return instantiateAnonymousType(type, mapper);
41240 }
41241 function getModifiedReadonlyState(state, modifiers) {
41242 return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
41243 }
41244 function instantiateMappedArrayType(arrayType, mappedType, mapper) {
41245 var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
41246 return elementType === errorType ? errorType :
41247 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
41248 }
41249 function instantiateMappedTupleType(tupleType, mappedType, mapper) {
41250 var minLength = tupleType.target.minLength;
41251 var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) {
41252 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper);
41253 });
41254 var modifiers = getMappedTypeModifiers(mappedType);
41255 var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 :
41256 modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) :
41257 minLength;
41258 var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
41259 return ts.contains(elementTypes, errorType) ? errorType :
41260 createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
41261 }
41262 function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
41263 var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key]));
41264 var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
41265 var modifiers = getMappedTypeModifiers(type);
41266 return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) :
41267 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
41268 propType;
41269 }
41270 function instantiateAnonymousType(type, mapper) {
41271 var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
41272 if (type.objectFlags & 32 /* Mapped */) {
41273 result.declaration = type.declaration;
41274 // C.f. instantiateSignature
41275 var origTypeParameter = getTypeParameterFromMappedType(type);
41276 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
41277 result.typeParameter = freshTypeParameter;
41278 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
41279 freshTypeParameter.mapper = mapper;
41280 }
41281 result.target = type;
41282 result.mapper = mapper;
41283 result.aliasSymbol = type.aliasSymbol;
41284 result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
41285 return result;
41286 }
41287 function getConditionalTypeInstantiation(type, mapper) {
41288 var root = type.root;
41289 if (root.outerTypeParameters) {
41290 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
41291 // mapper to the type parameters to produce the effective list of type arguments, and compute the
41292 // instantiation cache key from the type IDs of the type arguments.
41293 var typeArguments = ts.map(root.outerTypeParameters, mapper);
41294 var id = getTypeListId(typeArguments);
41295 var result = root.instantiations.get(id);
41296 if (!result) {
41297 var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
41298 result = instantiateConditionalType(root, newMapper);
41299 root.instantiations.set(id, result);
41300 }
41301 return result;
41302 }
41303 return type;
41304 }
41305 function instantiateConditionalType(root, mapper) {
41306 // Check if we have a conditional type where the check type is a naked type parameter. If so,
41307 // the conditional type is distributive over union types and when T is instantiated to a union
41308 // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
41309 if (root.isDistributive) {
41310 var checkType_1 = root.checkType;
41311 var instantiatedType = mapper(checkType_1);
41312 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
41313 return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); });
41314 }
41315 }
41316 return getConditionalType(root, mapper);
41317 }
41318 function instantiateType(type, mapper) {
41319 if (!type || !mapper || mapper === identityMapper) {
41320 return type;
41321 }
41322 if (instantiationDepth === 50) {
41323 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
41324 // with a combination of infinite generic types that perpetually generate new type identities. We stop
41325 // the recursion here by yielding the error type.
41326 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
41327 return errorType;
41328 }
41329 instantiationDepth++;
41330 var result = instantiateTypeWorker(type, mapper);
41331 instantiationDepth--;
41332 return result;
41333 }
41334 function instantiateTypeWorker(type, mapper) {
41335 var flags = type.flags;
41336 if (flags & 262144 /* TypeParameter */) {
41337 return mapper(type);
41338 }
41339 if (flags & 524288 /* Object */) {
41340 var objectFlags = type.objectFlags;
41341 if (objectFlags & 16 /* Anonymous */) {
41342 // If the anonymous type originates in a declaration of a function, method, class, or
41343 // interface, in an object type literal, or in an object literal expression, we may need
41344 // to instantiate the type because it might reference a type parameter.
41345 return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ?
41346 getAnonymousTypeInstantiation(type, mapper) : type;
41347 }
41348 if (objectFlags & 32 /* Mapped */) {
41349 return getAnonymousTypeInstantiation(type, mapper);
41350 }
41351 if (objectFlags & 4 /* Reference */) {
41352 var typeArguments = type.typeArguments;
41353 var newTypeArguments = instantiateTypes(typeArguments, mapper);
41354 return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type;
41355 }
41356 return type;
41357 }
41358 if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) {
41359 var types = type.types;
41360 var newTypes = instantiateTypes(types, mapper);
41361 return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type;
41362 }
41363 if (flags & 2097152 /* Intersection */) {
41364 var types = type.types;
41365 var newTypes = instantiateTypes(types, mapper);
41366 return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type;
41367 }
41368 if (flags & 4194304 /* Index */) {
41369 return getIndexType(instantiateType(type.type, mapper));
41370 }
41371 if (flags & 8388608 /* IndexedAccess */) {
41372 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
41373 }
41374 if (flags & 16777216 /* Conditional */) {
41375 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
41376 }
41377 if (flags & 33554432 /* Substitution */) {
41378 var maybeVariable = instantiateType(type.typeVariable, mapper);
41379 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
41380 return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
41381 }
41382 else {
41383 var sub = instantiateType(type.substitute, mapper);
41384 if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
41385 return maybeVariable;
41386 }
41387 return sub;
41388 }
41389 }
41390 return type;
41391 }
41392 function getPermissiveInstantiation(type) {
41393 return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
41394 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
41395 }
41396 function getRestrictiveInstantiation(type) {
41397 if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
41398 return type;
41399 }
41400 if (type.restrictiveInstantiation) {
41401 return type.restrictiveInstantiation;
41402 }
41403 type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
41404 // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
41405 // which is redundant - we'll produce new type identities, but all type params have already been mapped.
41406 // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
41407 // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
41408 // are constrained to `unknown` and produce tons of false positives/negatives!
41409 type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
41410 return type.restrictiveInstantiation;
41411 }
41412 function instantiateIndexInfo(info, mapper) {
41413 return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
41414 }
41415 // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
41416 // that is subject to contextual typing.
41417 function isContextSensitive(node) {
41418 ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
41419 switch (node.kind) {
41420 case 196 /* FunctionExpression */:
41421 case 197 /* ArrowFunction */:
41422 case 156 /* MethodDeclaration */:
41423 return isContextSensitiveFunctionLikeDeclaration(node);
41424 case 188 /* ObjectLiteralExpression */:
41425 return ts.some(node.properties, isContextSensitive);
41426 case 187 /* ArrayLiteralExpression */:
41427 return ts.some(node.elements, isContextSensitive);
41428 case 205 /* ConditionalExpression */:
41429 return isContextSensitive(node.whenTrue) ||
41430 isContextSensitive(node.whenFalse);
41431 case 204 /* BinaryExpression */:
41432 return node.operatorToken.kind === 55 /* BarBarToken */ &&
41433 (isContextSensitive(node.left) || isContextSensitive(node.right));
41434 case 275 /* PropertyAssignment */:
41435 return isContextSensitive(node.initializer);
41436 case 195 /* ParenthesizedExpression */:
41437 return isContextSensitive(node.expression);
41438 case 268 /* JsxAttributes */:
41439 return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
41440 case 267 /* JsxAttribute */: {
41441 // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
41442 var initializer = node.initializer;
41443 return !!initializer && isContextSensitive(initializer);
41444 }
41445 case 270 /* JsxExpression */: {
41446 // It is possible to that node.expression is undefined (e.g <div x={} />)
41447 var expression = node.expression;
41448 return !!expression && isContextSensitive(expression);
41449 }
41450 }
41451 return false;
41452 }
41453 function isContextSensitiveFunctionLikeDeclaration(node) {
41454 // Functions with type parameters are not context sensitive.
41455 if (node.typeParameters) {
41456 return false;
41457 }
41458 // Functions with any parameters that lack type annotations are context sensitive.
41459 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
41460 return true;
41461 }
41462 if (node.kind !== 197 /* ArrowFunction */) {
41463 // If the first parameter is not an explicit 'this' parameter, then the function has
41464 // an implicit 'this' parameter which is subject to contextual typing.
41465 var parameter = ts.firstOrUndefined(node.parameters);
41466 if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
41467 return true;
41468 }
41469 }
41470 return hasContextSensitiveReturnExpression(node);
41471 }
41472 function hasContextSensitiveReturnExpression(node) {
41473 // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
41474 return !!node.body && node.body.kind !== 218 /* Block */ && isContextSensitive(node.body);
41475 }
41476 function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
41477 return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
41478 isContextSensitiveFunctionLikeDeclaration(func);
41479 }
41480 function getTypeWithoutSignatures(type) {
41481 if (type.flags & 524288 /* Object */) {
41482 var resolved = resolveStructuredTypeMembers(type);
41483 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
41484 var result = createObjectType(16 /* Anonymous */, type.symbol);
41485 result.members = resolved.members;
41486 result.properties = resolved.properties;
41487 result.callSignatures = ts.emptyArray;
41488 result.constructSignatures = ts.emptyArray;
41489 return result;
41490 }
41491 }
41492 else if (type.flags & 2097152 /* Intersection */) {
41493 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
41494 }
41495 return type;
41496 }
41497 // TYPE CHECKING
41498 function isTypeIdenticalTo(source, target) {
41499 return isTypeRelatedTo(source, target, identityRelation);
41500 }
41501 function compareTypesIdentical(source, target) {
41502 return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
41503 }
41504 function compareTypesAssignable(source, target) {
41505 return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
41506 }
41507 function compareTypesSubtypeOf(source, target) {
41508 return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
41509 }
41510 function isTypeSubtypeOf(source, target) {
41511 return isTypeRelatedTo(source, target, subtypeRelation);
41512 }
41513 function isTypeAssignableTo(source, target) {
41514 return isTypeRelatedTo(source, target, assignableRelation);
41515 }
41516 // An object type S is considered to be derived from an object type T if
41517 // S is a union type and every constituent of S is derived from T,
41518 // T is a union type and S is derived from at least one constituent of T, or
41519 // S is a type variable with a base constraint that is derived from T,
41520 // T is one of the global types Object and Function and S is a subtype of T, or
41521 // T occurs directly or indirectly in an 'extends' clause of S.
41522 // Note that this check ignores type parameters and only considers the
41523 // inheritance hierarchy.
41524 function isTypeDerivedFrom(source, target) {
41525 return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
41526 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
41527 source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) :
41528 target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
41529 target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
41530 hasBaseType(source, getTargetType(target));
41531 }
41532 /**
41533 * This is *not* a bi-directional relationship.
41534 * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
41535 *
41536 * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T.
41537 * It is used to check following cases:
41538 * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
41539 * - the types of `case` clause expressions and their respective `switch` expressions.
41540 * - the type of an expression in a type assertion with the type being asserted.
41541 */
41542 function isTypeComparableTo(source, target) {
41543 return isTypeRelatedTo(source, target, comparableRelation);
41544 }
41545 function areTypesComparable(type1, type2) {
41546 return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
41547 }
41548 function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
41549 return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
41550 }
41551 /**
41552 * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
41553 * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
41554 */
41555 function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
41556 return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain);
41557 }
41558 function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) {
41559 if (isTypeRelatedTo(source, target, relation))
41560 return true;
41561 if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) {
41562 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain);
41563 }
41564 return false;
41565 }
41566 function isOrHasGenericConditional(type) {
41567 return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
41568 }
41569 function elaborateError(node, source, target, relation, headMessage) {
41570 if (!node || isOrHasGenericConditional(target))
41571 return false;
41572 if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) {
41573 return true;
41574 }
41575 switch (node.kind) {
41576 case 270 /* JsxExpression */:
41577 case 195 /* ParenthesizedExpression */:
41578 return elaborateError(node.expression, source, target, relation, headMessage);
41579 case 204 /* BinaryExpression */:
41580 switch (node.operatorToken.kind) {
41581 case 59 /* EqualsToken */:
41582 case 27 /* CommaToken */:
41583 return elaborateError(node.right, source, target, relation, headMessage);
41584 }
41585 break;
41586 case 188 /* ObjectLiteralExpression */:
41587 return elaborateObjectLiteral(node, source, target, relation);
41588 case 187 /* ArrayLiteralExpression */:
41589 return elaborateArrayLiteral(node, source, target, relation);
41590 case 268 /* JsxAttributes */:
41591 return elaborateJsxComponents(node, source, target, relation);
41592 case 197 /* ArrowFunction */:
41593 return elaborateArrowFunction(node, source, target, relation);
41594 }
41595 return false;
41596 }
41597 function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) {
41598 var callSignatures = getSignaturesOfType(source, 0 /* Call */);
41599 var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
41600 for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
41601 var signatures = _a[_i];
41602 if (ts.some(signatures, function (s) {
41603 var returnType = getReturnTypeOfSignature(s);
41604 return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
41605 })) {
41606 var resultObj = {};
41607 checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj);
41608 var diagnostic = resultObj.error;
41609 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
41610 return true;
41611 }
41612 }
41613 return false;
41614 }
41615 function elaborateArrowFunction(node, source, target, relation) {
41616 // Don't elaborate blocks
41617 if (ts.isBlock(node.body)) {
41618 return false;
41619 }
41620 // Or functions with annotated parameter types
41621 if (ts.some(node.parameters, ts.hasType)) {
41622 return false;
41623 }
41624 var sourceSig = getSingleCallSignature(source);
41625 if (!sourceSig) {
41626 return false;
41627 }
41628 var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
41629 if (!ts.length(targetSignatures)) {
41630 return false;
41631 }
41632 var returnExpression = node.body;
41633 var sourceReturn = getReturnTypeOfSignature(sourceSig);
41634 var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
41635 if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
41636 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined);
41637 if (elaborated) {
41638 return elaborated;
41639 }
41640 var resultObj = {};
41641 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj);
41642 if (resultObj.error) {
41643 if (target.symbol && ts.length(target.symbol.declarations)) {
41644 ts.addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
41645 }
41646 return true;
41647 }
41648 }
41649 return false;
41650 }
41651 /**
41652 * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
41653 * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError`
41654 * Otherwise, we issue an error on _every_ element which fail the assignability check
41655 */
41656 function elaborateElementwise(iterator, source, target, relation) {
41657 // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
41658 var reportedError = false;
41659 for (var status = iterator.next(); !status.done; status = iterator.next()) {
41660 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
41661 var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType);
41662 if (targetPropType === errorType || targetPropType.flags & 8388608 /* IndexedAccess */)
41663 continue; // Don't elaborate on indexes on generic variables
41664 var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType);
41665 if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
41666 var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined);
41667 if (elaborated) {
41668 reportedError = true;
41669 }
41670 else {
41671 // Issue error on the prop itself, since the prop couldn't elaborate the error
41672 var resultObj = {};
41673 // Use the expression type, if available
41674 var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType;
41675 var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj);
41676 if (result && specificSource !== sourcePropType) {
41677 // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
41678 checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj);
41679 }
41680 if (resultObj.error) {
41681 var reportedDiag = resultObj.error;
41682 var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
41683 var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
41684 var issuedElaboration = false;
41685 if (!targetProp) {
41686 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
41687 getIndexInfoOfType(target, 0 /* String */) ||
41688 undefined;
41689 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
41690 issuedElaboration = true;
41691 ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
41692 }
41693 }
41694 if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
41695 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
41696 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
41697 ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
41698 }
41699 }
41700 }
41701 reportedError = true;
41702 }
41703 }
41704 }
41705 return reportedError;
41706 }
41707 function generateJsxAttributes(node) {
41708 var _i, _a, prop;
41709 return __generator(this, function (_b) {
41710 switch (_b.label) {
41711 case 0:
41712 if (!ts.length(node.properties))
41713 return [2 /*return*/];
41714 _i = 0, _a = node.properties;
41715 _b.label = 1;
41716 case 1:
41717 if (!(_i < _a.length)) return [3 /*break*/, 4];
41718 prop = _a[_i];
41719 if (ts.isJsxSpreadAttribute(prop))
41720 return [3 /*break*/, 3];
41721 return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
41722 case 2:
41723 _b.sent();
41724 _b.label = 3;
41725 case 3:
41726 _i++;
41727 return [3 /*break*/, 1];
41728 case 4: return [2 /*return*/];
41729 }
41730 });
41731 }
41732 function generateJsxChildren(node, getInvalidTextDiagnostic) {
41733 var memberOffset, i, child, nameType, elem;
41734 return __generator(this, function (_a) {
41735 switch (_a.label) {
41736 case 0:
41737 if (!ts.length(node.children))
41738 return [2 /*return*/];
41739 memberOffset = 0;
41740 i = 0;
41741 _a.label = 1;
41742 case 1:
41743 if (!(i < node.children.length)) return [3 /*break*/, 5];
41744 child = node.children[i];
41745 nameType = getLiteralType(i - memberOffset);
41746 elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
41747 if (!elem) return [3 /*break*/, 3];
41748 return [4 /*yield*/, elem];
41749 case 2:
41750 _a.sent();
41751 return [3 /*break*/, 4];
41752 case 3:
41753 memberOffset++;
41754 _a.label = 4;
41755 case 4:
41756 i++;
41757 return [3 /*break*/, 1];
41758 case 5: return [2 /*return*/];
41759 }
41760 });
41761 }
41762 function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
41763 switch (child.kind) {
41764 case 270 /* JsxExpression */:
41765 // child is of the type of the expression
41766 return { errorNode: child, innerExpression: child.expression, nameType: nameType };
41767 case 11 /* JsxText */:
41768 if (child.containsOnlyTriviaWhiteSpaces) {
41769 break; // Whitespace only jsx text isn't real jsx text
41770 }
41771 // child is a string
41772 return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
41773 case 260 /* JsxElement */:
41774 case 261 /* JsxSelfClosingElement */:
41775 case 264 /* JsxFragment */:
41776 // child is of type JSX.Element
41777 return { errorNode: child, innerExpression: child, nameType: nameType };
41778 default:
41779 return ts.Debug.assertNever(child, "Found invalid jsx child");
41780 }
41781 }
41782 function elaborateJsxComponents(node, source, target, relation) {
41783 var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation);
41784 var invalidTextDiagnostic;
41785 if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
41786 var containingElement = node.parent.parent;
41787 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
41788 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
41789 var childrenNameType = getLiteralType(childrenPropName);
41790 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
41791 var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
41792 if (!ts.length(validChildren)) {
41793 return result;
41794 }
41795 var moreThanOneRealChildren = ts.length(validChildren) > 1;
41796 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
41797 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
41798 if (moreThanOneRealChildren) {
41799 if (arrayLikeTargetParts !== neverType) {
41800 var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
41801 result = elaborateElementwise(generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic), realSource, arrayLikeTargetParts, relation) || result;
41802 }
41803 else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
41804 // arity mismatch
41805 result = true;
41806 error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType));
41807 }
41808 }
41809 else {
41810 if (nonArrayLikeTargetParts !== neverType) {
41811 var child = validChildren[0];
41812 var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
41813 if (elem_1) {
41814 result = elaborateElementwise((function () { return __generator(this, function (_a) {
41815 switch (_a.label) {
41816 case 0: return [4 /*yield*/, elem_1];
41817 case 1:
41818 _a.sent();
41819 return [2 /*return*/];
41820 }
41821 }); })(), source, target, relation) || result;
41822 }
41823 }
41824 else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
41825 // arity mismatch
41826 result = true;
41827 error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType));
41828 }
41829 }
41830 }
41831 return result;
41832 function getInvalidTextualChildDiagnostic() {
41833 if (!invalidTextDiagnostic) {
41834 var tagNameText = ts.getTextOfNode(node.parent.tagName);
41835 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
41836 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
41837 var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
41838 var diagnostic = ts.Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2;
41839 invalidTextDiagnostic = __assign({}, diagnostic, { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
41840 }
41841 return invalidTextDiagnostic;
41842 }
41843 }
41844 function generateLimitedTupleElements(node, target) {
41845 var len, i, elem, nameType;
41846 return __generator(this, function (_a) {
41847 switch (_a.label) {
41848 case 0:
41849 len = ts.length(node.elements);
41850 if (!len)
41851 return [2 /*return*/];
41852 i = 0;
41853 _a.label = 1;
41854 case 1:
41855 if (!(i < len)) return [3 /*break*/, 4];
41856 // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature
41857 if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
41858 return [3 /*break*/, 3];
41859 elem = node.elements[i];
41860 if (ts.isOmittedExpression(elem))
41861 return [3 /*break*/, 3];
41862 nameType = getLiteralType(i);
41863 return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
41864 case 2:
41865 _a.sent();
41866 _a.label = 3;
41867 case 3:
41868 i++;
41869 return [3 /*break*/, 1];
41870 case 4: return [2 /*return*/];
41871 }
41872 });
41873 }
41874 function elaborateArrayLiteral(node, source, target, relation) {
41875 if (isTupleLikeType(source)) {
41876 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
41877 }
41878 // recreate a tuple from the elements, if possible
41879 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
41880 if (isTupleLikeType(tupleizedType)) {
41881 return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
41882 }
41883 return false;
41884 }
41885 function generateObjectLiteralElements(node) {
41886 var _i, _a, prop, type, _b;
41887 return __generator(this, function (_c) {
41888 switch (_c.label) {
41889 case 0:
41890 if (!ts.length(node.properties))
41891 return [2 /*return*/];
41892 _i = 0, _a = node.properties;
41893 _c.label = 1;
41894 case 1:
41895 if (!(_i < _a.length)) return [3 /*break*/, 8];
41896 prop = _a[_i];
41897 if (ts.isSpreadAssignment(prop))
41898 return [3 /*break*/, 7];
41899 type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
41900 if (!type || (type.flags & 131072 /* Never */)) {
41901 return [3 /*break*/, 7];
41902 }
41903 _b = prop.kind;
41904 switch (_b) {
41905 case 159 /* SetAccessor */: return [3 /*break*/, 2];
41906 case 158 /* GetAccessor */: return [3 /*break*/, 2];
41907 case 156 /* MethodDeclaration */: return [3 /*break*/, 2];
41908 case 276 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
41909 case 275 /* PropertyAssignment */: return [3 /*break*/, 4];
41910 }
41911 return [3 /*break*/, 6];
41912 case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
41913 case 3:
41914 _c.sent();
41915 return [3 /*break*/, 7];
41916 case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }];
41917 case 5:
41918 _c.sent();
41919 return [3 /*break*/, 7];
41920 case 6:
41921 ts.Debug.assertNever(prop);
41922 _c.label = 7;
41923 case 7:
41924 _i++;
41925 return [3 /*break*/, 1];
41926 case 8: return [2 /*return*/];
41927 }
41928 });
41929 }
41930 function elaborateObjectLiteral(node, source, target, relation) {
41931 return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation);
41932 }
41933 /**
41934 * This is *not* a bi-directional relationship.
41935 * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
41936 */
41937 function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
41938 return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
41939 }
41940 function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
41941 return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false,
41942 /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */;
41943 }
41944 /**
41945 * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
41946 */
41947 function isAnySignature(s) {
41948 return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
41949 s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
41950 isTypeAny(getReturnTypeOfSignature(s));
41951 }
41952 /**
41953 * See signatureRelatedTo, compareSignaturesIdentical
41954 */
41955 function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
41956 // TODO (drosen): De-duplicate code between related functions.
41957 if (source === target) {
41958 return -1 /* True */;
41959 }
41960 if (isAnySignature(target)) {
41961 return -1 /* True */;
41962 }
41963 var targetCount = getParameterCount(target);
41964 if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) {
41965 return 0 /* False */;
41966 }
41967 if (source.typeParameters && source.typeParameters !== target.typeParameters) {
41968 target = getCanonicalSignature(target);
41969 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
41970 }
41971 var sourceCount = getParameterCount(source);
41972 var sourceRestType = getNonArrayRestType(source);
41973 var targetRestType = getNonArrayRestType(target);
41974 if (sourceRestType && targetRestType && sourceCount !== targetCount) {
41975 // We're not able to relate misaligned complex rest parameters
41976 return 0 /* False */;
41977 }
41978 var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
41979 var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 156 /* MethodDeclaration */ &&
41980 kind !== 155 /* MethodSignature */ && kind !== 157 /* Constructor */;
41981 var result = -1 /* True */;
41982 var sourceThisType = getThisTypeOfSignature(source);
41983 if (sourceThisType && sourceThisType !== voidType) {
41984 var targetThisType = getThisTypeOfSignature(target);
41985 if (targetThisType) {
41986 // void sources are assignable to anything.
41987 var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
41988 || compareTypes(targetThisType, sourceThisType, reportErrors);
41989 if (!related) {
41990 if (reportErrors) {
41991 errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
41992 }
41993 return 0 /* False */;
41994 }
41995 result &= related;
41996 }
41997 }
41998 var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
41999 var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
42000 for (var i = 0; i < paramCount; i++) {
42001 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
42002 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
42003 // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
42004 // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
42005 // they naturally relate only contra-variantly). However, if the source and target parameters both have
42006 // function types with a single call signature, we know we are relating two callback parameters. In
42007 // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
42008 // similar to return values, callback parameters are output positions. This means that a Promise<T>,
42009 // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
42010 // with respect to T.
42011 var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
42012 var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType));
42013 var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) &&
42014 (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
42015 var related = callbacks ?
42016 // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is
42017 compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) :
42018 !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
42019 if (!related) {
42020 if (reportErrors) {
42021 errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
42022 }
42023 return 0 /* False */;
42024 }
42025 result &= related;
42026 }
42027 if (!ignoreReturnTypes) {
42028 var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ?
42029 getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target);
42030 if (targetReturnType === voidType) {
42031 return result;
42032 }
42033 var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ?
42034 getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source);
42035 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
42036 var targetTypePredicate = getTypePredicateOfSignature(target);
42037 if (targetTypePredicate) {
42038 var sourceTypePredicate = getTypePredicateOfSignature(source);
42039 if (sourceTypePredicate) {
42040 result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
42041 }
42042 else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
42043 if (reportErrors) {
42044 errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
42045 }
42046 return 0 /* False */;
42047 }
42048 }
42049 else {
42050 // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
42051 // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
42052 // wouldn't be co-variant for T without this rule.
42053 result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
42054 compareTypes(sourceReturnType, targetReturnType, reportErrors);
42055 }
42056 }
42057 return result;
42058 }
42059 function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
42060 if (source.kind !== target.kind) {
42061 if (reportErrors) {
42062 errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
42063 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
42064 }
42065 return 0 /* False */;
42066 }
42067 if (source.kind === 1 /* Identifier */) {
42068 if (source.parameterIndex !== target.parameterIndex) {
42069 if (reportErrors) {
42070 errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
42071 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
42072 }
42073 return 0 /* False */;
42074 }
42075 }
42076 var related = compareTypes(source.type, target.type, reportErrors);
42077 if (related === 0 /* False */ && reportErrors) {
42078 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
42079 }
42080 return related;
42081 }
42082 function isImplementationCompatibleWithOverload(implementation, overload) {
42083 var erasedSource = getErasedSignature(implementation);
42084 var erasedTarget = getErasedSignature(overload);
42085 // First see if the return types are compatible in either direction.
42086 var sourceReturnType = getReturnTypeOfSignature(erasedSource);
42087 var targetReturnType = getReturnTypeOfSignature(erasedTarget);
42088 if (targetReturnType === voidType
42089 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
42090 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
42091 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
42092 }
42093 return false;
42094 }
42095 function isEmptyResolvedType(t) {
42096 return t.properties.length === 0 &&
42097 t.callSignatures.length === 0 &&
42098 t.constructSignatures.length === 0 &&
42099 !t.stringIndexInfo &&
42100 !t.numberIndexInfo;
42101 }
42102 function isEmptyObjectType(type) {
42103 return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
42104 type.flags & 67108864 /* NonPrimitive */ ? true :
42105 type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
42106 type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
42107 false;
42108 }
42109 function isEmptyAnonymousObjectType(type) {
42110 return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type);
42111 }
42112 function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
42113 if (sourceSymbol === targetSymbol) {
42114 return true;
42115 }
42116 var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
42117 var relation = enumRelation.get(id);
42118 if (relation !== undefined && !(relation === 2 /* Failed */ && errorReporter)) {
42119 return relation === 1 /* Succeeded */;
42120 }
42121 if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
42122 enumRelation.set(id, 3 /* FailedAndReported */);
42123 return false;
42124 }
42125 var targetEnumType = getTypeOfSymbol(targetSymbol);
42126 for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
42127 var property = _a[_i];
42128 if (property.flags & 8 /* EnumMember */) {
42129 var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
42130 if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
42131 if (errorReporter) {
42132 errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
42133 enumRelation.set(id, 3 /* FailedAndReported */);
42134 }
42135 else {
42136 enumRelation.set(id, 2 /* Failed */);
42137 }
42138 return false;
42139 }
42140 }
42141 }
42142 enumRelation.set(id, 1 /* Succeeded */);
42143 return true;
42144 }
42145 function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
42146 var s = source.flags;
42147 var t = target.flags;
42148 if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
42149 return true;
42150 if (t & 131072 /* Never */)
42151 return false;
42152 if (s & 132 /* StringLike */ && t & 4 /* String */)
42153 return true;
42154 if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
42155 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
42156 source.value === target.value)
42157 return true;
42158 if (s & 296 /* NumberLike */ && t & 8 /* Number */)
42159 return true;
42160 if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
42161 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
42162 source.value === target.value)
42163 return true;
42164 if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
42165 return true;
42166 if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
42167 return true;
42168 if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
42169 return true;
42170 if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
42171 return true;
42172 if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
42173 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
42174 return true;
42175 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
42176 source.value === target.value &&
42177 isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
42178 return true;
42179 }
42180 if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
42181 return true;
42182 if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
42183 return true;
42184 if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
42185 return true;
42186 if (relation === assignableRelation || relation === comparableRelation) {
42187 if (s & 1 /* Any */)
42188 return true;
42189 // Type number or any numeric literal type is assignable to any numeric enum type or any
42190 // numeric enum literal type. This rule exists for backwards compatibility reasons because
42191 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
42192 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
42193 return true;
42194 }
42195 return false;
42196 }
42197 function isTypeRelatedTo(source, target, relation) {
42198 if (isFreshLiteralType(source)) {
42199 source = source.regularType;
42200 }
42201 if (isFreshLiteralType(target)) {
42202 target = target.regularType;
42203 }
42204 if (source === target ||
42205 relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
42206 relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) {
42207 return true;
42208 }
42209 if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
42210 var related = relation.get(getRelationKey(source, target, relation));
42211 if (related !== undefined) {
42212 return related === 1 /* Succeeded */;
42213 }
42214 }
42215 if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) {
42216 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
42217 }
42218 return false;
42219 }
42220 function isIgnoredJsxProperty(source, sourceProp, targetMemberType) {
42221 return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType);
42222 }
42223 /**
42224 * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
42225 * @param source The left-hand-side of the relation.
42226 * @param target The right-hand-side of the relation.
42227 * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
42228 * Used as both to determine which checks are performed and as a cache of previously computed results.
42229 * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
42230 * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
42231 * @param containingMessageChain A chain of errors to prepend any new errors found.
42232 */
42233 function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
42234 var errorInfo;
42235 var relatedInfo;
42236 var maybeKeys;
42237 var sourceStack;
42238 var targetStack;
42239 var maybeCount = 0;
42240 var depth = 0;
42241 var expandingFlags = 0 /* None */;
42242 var overflow = false;
42243 var suppressNextError = false;
42244 ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
42245 var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
42246 if (overflow) {
42247 error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
42248 }
42249 else if (errorInfo) {
42250 if (containingMessageChain) {
42251 var chain_1 = containingMessageChain();
42252 if (chain_1) {
42253 errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo);
42254 }
42255 }
42256 var relatedInformation = void 0;
42257 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
42258 if (headMessage && errorNode && !result && source.symbol) {
42259 var links = getSymbolLinks(source.symbol);
42260 if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
42261 var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
42262 if (helpfulRetry) {
42263 // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
42264 var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.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);
42265 relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
42266 }
42267 }
42268 }
42269 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
42270 if (relatedInfo) {
42271 ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
42272 }
42273 if (errorOutputContainer) {
42274 errorOutputContainer.error = diag;
42275 }
42276 diagnostics.add(diag); // TODO: GH#18217
42277 }
42278 return result !== 0 /* False */;
42279 function reportError(message, arg0, arg1, arg2, arg3) {
42280 ts.Debug.assert(!!errorNode);
42281 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
42282 }
42283 function associateRelatedInfo(info) {
42284 ts.Debug.assert(!!errorInfo);
42285 if (!relatedInfo) {
42286 relatedInfo = [info];
42287 }
42288 else {
42289 relatedInfo.push(info);
42290 }
42291 }
42292 function reportRelationError(message, source, target) {
42293 var sourceType = typeToString(source);
42294 var targetType = typeToString(target);
42295 if (sourceType === targetType) {
42296 sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
42297 targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
42298 }
42299 if (!message) {
42300 if (relation === comparableRelation) {
42301 message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
42302 }
42303 else if (sourceType === targetType) {
42304 message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
42305 }
42306 else {
42307 message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
42308 }
42309 }
42310 reportError(message, sourceType, targetType);
42311 }
42312 function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
42313 var sourceType = typeToString(source);
42314 var targetType = typeToString(target);
42315 if ((globalStringType === source && stringType === target) ||
42316 (globalNumberType === source && numberType === target) ||
42317 (globalBooleanType === source && booleanType === target) ||
42318 (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
42319 reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
42320 }
42321 }
42322 function isUnionOrIntersectionTypeWithoutNullableConstituents(type) {
42323 if (!(type.flags & 3145728 /* UnionOrIntersection */)) {
42324 return false;
42325 }
42326 // at this point we know that this is union or intersection type possibly with nullable constituents.
42327 // check if we still will have compound type if we ignore nullable components.
42328 var seenNonNullable = false;
42329 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
42330 var t = _a[_i];
42331 if (t.flags & 98304 /* Nullable */) {
42332 continue;
42333 }
42334 if (seenNonNullable) {
42335 return true;
42336 }
42337 seenNonNullable = true;
42338 }
42339 return false;
42340 }
42341 /**
42342 * Compare two types and return
42343 * * Ternary.True if they are related with no assumptions,
42344 * * Ternary.Maybe if they are related with assumptions of other relationships, or
42345 * * Ternary.False if they are not related.
42346 */
42347 function isRelatedTo(source, target, reportErrors, headMessage, isApparentIntersectionConstituent) {
42348 if (reportErrors === void 0) { reportErrors = false; }
42349 if (isFreshLiteralType(source)) {
42350 source = source.regularType;
42351 }
42352 if (isFreshLiteralType(target)) {
42353 target = target.regularType;
42354 }
42355 if (source.flags & 33554432 /* Substitution */) {
42356 source = source.substitute;
42357 }
42358 if (target.flags & 33554432 /* Substitution */) {
42359 target = target.typeVariable;
42360 }
42361 if (source.flags & 8388608 /* IndexedAccess */) {
42362 source = getSimplifiedType(source);
42363 }
42364 if (target.flags & 8388608 /* IndexedAccess */) {
42365 target = getSimplifiedType(target);
42366 }
42367 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
42368 // If so, reporting the `null` and `undefined` in the type is hardly useful.
42369 // First, see if we're even relating an object type to a union.
42370 // Then see if the target is stripped down to a single non-union type.
42371 // Note
42372 // * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
42373 // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
42374 // when dealing with generics.
42375 // * We also don't deal with primitive source types, since we already halt elaboration below.
42376 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
42377 target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
42378 var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
42379 if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
42380 target = nullStrippedTarget;
42381 }
42382 }
42383 // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases
42384 if (source === target)
42385 return -1 /* True */;
42386 if (relation === identityRelation) {
42387 return isIdenticalTo(source, target);
42388 }
42389 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
42390 isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
42391 return -1 /* True */;
42392 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
42393 if (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */) {
42394 var discriminantType = target.flags & 1048576 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined;
42395 if (hasExcessProperties(source, target, discriminantType, reportErrors)) {
42396 if (reportErrors) {
42397 reportRelationError(headMessage, source, target);
42398 }
42399 return 0 /* False */;
42400 }
42401 // Above we check for excess properties with respect to the entire target type. When union
42402 // and intersection types are further deconstructed on the target side, we don't want to
42403 // make the check again (as it might fail for a partial target type). Therefore we obtain
42404 // the regular source type and proceed with that.
42405 if (isUnionOrIntersectionTypeWithoutNullableConstituents(target) && !discriminantType) {
42406 source = getRegularTypeOfObjectLiteral(source);
42407 }
42408 }
42409 if (relation !== comparableRelation && !isApparentIntersectionConstituent &&
42410 source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
42411 target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
42412 (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) &&
42413 !hasCommonProperties(source, target, isComparingJsxAttributes)) {
42414 if (reportErrors) {
42415 var calls = getSignaturesOfType(source, 0 /* Call */);
42416 var constructs = getSignaturesOfType(source, 1 /* Construct */);
42417 if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
42418 constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
42419 reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target));
42420 }
42421 else {
42422 reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
42423 }
42424 }
42425 return 0 /* False */;
42426 }
42427 var result = 0 /* False */;
42428 var saveErrorInfo = errorInfo;
42429 var isIntersectionConstituent = !!isApparentIntersectionConstituent;
42430 // Note that these checks are specifically ordered to produce correct results. In particular,
42431 // we need to deconstruct unions before intersections (because unions are always at the top),
42432 // and we need to handle "each" relations before "some" relations for the same kind of type.
42433 if (source.flags & 1048576 /* Union */) {
42434 result = relation === comparableRelation ?
42435 someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)) :
42436 eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */));
42437 }
42438 else {
42439 if (target.flags & 1048576 /* Union */) {
42440 result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
42441 }
42442 else if (target.flags & 2097152 /* Intersection */) {
42443 isIntersectionConstituent = true; // set here to affect the following trio of checks
42444 result = typeRelatedToEachType(source, target, reportErrors);
42445 }
42446 else if (source.flags & 2097152 /* Intersection */) {
42447 // Check to see if any constituents of the intersection are immediately related to the target.
42448 //
42449 // Don't report errors though. Checking whether a constituent is related to the source is not actually
42450 // useful and leads to some confusing error messages. Instead it is better to let the below checks
42451 // take care of this, or to not elaborate at all. For instance,
42452 //
42453 // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
42454 //
42455 // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
42456 // than to report that 'D' is not assignable to 'A' or 'B'.
42457 //
42458 // - For a primitive type or type parameter (such as 'number = A & B') there is no point in
42459 // breaking the intersection apart.
42460 result = someTypeRelatedToType(source, target, /*reportErrors*/ false);
42461 }
42462 if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) {
42463 if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) {
42464 errorInfo = saveErrorInfo;
42465 }
42466 }
42467 }
42468 if (!result && source.flags & 2097152 /* Intersection */) {
42469 // The combined constraint of an intersection type is the intersection of the constraints of
42470 // the constituents. When an intersection type contains instantiable types with union type
42471 // constraints, there are situations where we need to examine the combined constraint. One is
42472 // when the target is a union type. Another is when the intersection contains types belonging
42473 // to one of the disjoint domains. For example, given type variables T and U, each with the
42474 // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
42475 // we need to check this constraint against a union on the target side. Also, given a type
42476 // variable V constrained to 'string | number', 'V & number' has a combined constraint of
42477 // 'string & number | number & number' which reduces to just 'number'.
42478 var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 1048576 /* Union */));
42479 if (constraint) {
42480 if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) {
42481 errorInfo = saveErrorInfo;
42482 }
42483 }
42484 }
42485 if (!result && reportErrors) {
42486 var maybeSuppress = suppressNextError;
42487 suppressNextError = false;
42488 if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
42489 tryElaborateErrorsForPrimitivesAndObjects(source, target);
42490 }
42491 else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
42492 reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
42493 }
42494 else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
42495 var targetTypes = target.types;
42496 var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
42497 var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
42498 if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
42499 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
42500 // do not report top error
42501 return result;
42502 }
42503 }
42504 if (!headMessage && maybeSuppress) {
42505 // Used by, eg, missing property checking to replace the top-level message with a more informative one
42506 return result;
42507 }
42508 reportRelationError(headMessage, source, target);
42509 }
42510 return result;
42511 }
42512 function isIdenticalTo(source, target) {
42513 var result;
42514 var flags = source.flags & target.flags;
42515 if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) {
42516 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false);
42517 }
42518 if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
42519 if (result = eachTypeRelatedToSomeType(source, target)) {
42520 if (result &= eachTypeRelatedToSomeType(target, source)) {
42521 return result;
42522 }
42523 }
42524 }
42525 return 0 /* False */;
42526 }
42527 function hasExcessProperties(source, target, discriminant, reportErrors) {
42528 if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
42529 return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
42530 }
42531 if (isExcessPropertyCheckTarget(target)) {
42532 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
42533 if ((relation === assignableRelation || relation === comparableRelation) &&
42534 (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
42535 return false;
42536 }
42537 if (discriminant) {
42538 // check excess properties against discriminant type only, not the entire union
42539 return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors);
42540 }
42541 var _loop_7 = function (prop) {
42542 if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
42543 if (reportErrors) {
42544 // Report error in terms of object types in the target as those are the only ones
42545 // we check in isKnownProperty.
42546 var errorTarget = filterType(target, isExcessPropertyCheckTarget);
42547 // We know *exactly* where things went wrong when comparing the types.
42548 // Use this property as the error node as this will be more helpful in
42549 // reasoning about what went wrong.
42550 if (!errorNode)
42551 return { value: ts.Debug.fail() };
42552 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
42553 // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
42554 // However, using an object-literal error message will be very confusing to the users so we give different a message.
42555 // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages)
42556 reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget));
42557 }
42558 else {
42559 // use the property's value declaration if the property is assigned inside the literal itself
42560 var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
42561 var suggestion = void 0;
42562 if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) {
42563 var propDeclaration = prop.valueDeclaration;
42564 ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
42565 errorNode = propDeclaration;
42566 var name = propDeclaration.name;
42567 if (ts.isIdentifier(name)) {
42568 suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
42569 }
42570 }
42571 if (suggestion !== undefined) {
42572 reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion);
42573 }
42574 else {
42575 reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
42576 }
42577 }
42578 }
42579 return { value: true };
42580 }
42581 };
42582 for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
42583 var prop = _a[_i];
42584 var state_3 = _loop_7(prop);
42585 if (typeof state_3 === "object")
42586 return state_3.value;
42587 }
42588 }
42589 return false;
42590 }
42591 function shouldCheckAsExcessProperty(prop, container) {
42592 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
42593 }
42594 function eachTypeRelatedToSomeType(source, target) {
42595 var result = -1 /* True */;
42596 var sourceTypes = source.types;
42597 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
42598 var sourceType = sourceTypes_1[_i];
42599 var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
42600 if (!related) {
42601 return 0 /* False */;
42602 }
42603 result &= related;
42604 }
42605 return result;
42606 }
42607 function typeRelatedToSomeType(source, target, reportErrors) {
42608 var targetTypes = target.types;
42609 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
42610 return -1 /* True */;
42611 }
42612 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
42613 var type = targetTypes_1[_i];
42614 var related = isRelatedTo(source, type, /*reportErrors*/ false);
42615 if (related) {
42616 return related;
42617 }
42618 }
42619 if (reportErrors) {
42620 var bestMatchingType = findMatchingDiscriminantType(source, target) ||
42621 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
42622 findBestTypeForObjectLiteral(source, target) ||
42623 findBestTypeForInvokable(source, target) ||
42624 findMostOverlappyType(source, target);
42625 isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
42626 }
42627 return 0 /* False */;
42628 }
42629 function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
42630 var sourceObjectFlags = ts.getObjectFlags(source);
42631 if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
42632 return ts.find(unionTarget.types, function (target) {
42633 if (target.flags & 524288 /* Object */) {
42634 var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
42635 if (overlapObjFlags & 4 /* Reference */) {
42636 return source.target === target.target;
42637 }
42638 if (overlapObjFlags & 16 /* Anonymous */) {
42639 return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
42640 }
42641 }
42642 return false;
42643 });
42644 }
42645 }
42646 function findBestTypeForObjectLiteral(source, unionTarget) {
42647 if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
42648 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
42649 }
42650 }
42651 function findBestTypeForInvokable(source, unionTarget) {
42652 var signatureKind = 0 /* Call */;
42653 var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
42654 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
42655 if (hasSignatures) {
42656 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
42657 }
42658 }
42659 function findMostOverlappyType(source, unionTarget) {
42660 var bestMatch;
42661 var matchingCount = 0;
42662 for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
42663 var target_1 = _a[_i];
42664 var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]);
42665 if (overlap.flags & 4194304 /* Index */) {
42666 // perfect overlap of keys
42667 bestMatch = target_1;
42668 matchingCount = Infinity;
42669 }
42670 else if (overlap.flags & 1048576 /* Union */) {
42671 // We only want to account for literal types otherwise.
42672 // If we have a union of index types, it seems likely that we
42673 // needed to elaborate between two generic mapped types anyway.
42674 var len = ts.length(ts.filter(overlap.types, isUnitType));
42675 if (len >= matchingCount) {
42676 bestMatch = target_1;
42677 matchingCount = len;
42678 }
42679 }
42680 else if (isUnitType(overlap) && 1 >= matchingCount) {
42681 bestMatch = target_1;
42682 matchingCount = 1;
42683 }
42684 }
42685 return bestMatch;
42686 }
42687 // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
42688 function findMatchingDiscriminantType(source, target) {
42689 if (target.flags & 1048576 /* Union */) {
42690 var sourceProperties = getPropertiesOfObjectType(source);
42691 if (sourceProperties) {
42692 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
42693 if (sourcePropertiesFiltered) {
42694 return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo);
42695 }
42696 }
42697 }
42698 return undefined;
42699 }
42700 function typeRelatedToEachType(source, target, reportErrors) {
42701 var result = -1 /* True */;
42702 var targetTypes = target.types;
42703 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
42704 var targetType = targetTypes_2[_i];
42705 var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true);
42706 if (!related) {
42707 return 0 /* False */;
42708 }
42709 result &= related;
42710 }
42711 return result;
42712 }
42713 function someTypeRelatedToType(source, target, reportErrors) {
42714 var sourceTypes = source.types;
42715 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
42716 return -1 /* True */;
42717 }
42718 var len = sourceTypes.length;
42719 for (var i = 0; i < len; i++) {
42720 var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1);
42721 if (related) {
42722 return related;
42723 }
42724 }
42725 return 0 /* False */;
42726 }
42727 function eachTypeRelatedToType(source, target, reportErrors) {
42728 var result = -1 /* True */;
42729 var sourceTypes = source.types;
42730 for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) {
42731 var sourceType = sourceTypes_2[_i];
42732 var related = isRelatedTo(sourceType, target, reportErrors);
42733 if (!related) {
42734 return 0 /* False */;
42735 }
42736 result &= related;
42737 }
42738 return result;
42739 }
42740 function typeArgumentsRelatedTo(sources, targets, variances, reportErrors) {
42741 if (sources === void 0) { sources = ts.emptyArray; }
42742 if (targets === void 0) { targets = ts.emptyArray; }
42743 if (variances === void 0) { variances = ts.emptyArray; }
42744 if (sources.length !== targets.length && relation === identityRelation) {
42745 return 0 /* False */;
42746 }
42747 var length = sources.length <= targets.length ? sources.length : targets.length;
42748 var result = -1 /* True */;
42749 for (var i = 0; i < length; i++) {
42750 // When variance information isn't available we default to covariance. This happens
42751 // in the process of computing variance information for recursive types and when
42752 // comparing 'this' type arguments.
42753 var variance = i < variances.length ? variances[i] : 1 /* Covariant */;
42754 // We ignore arguments for independent type parameters (because they're never witnessed).
42755 if (variance !== 4 /* Independent */) {
42756 var s = sources[i];
42757 var t = targets[i];
42758 var related = -1 /* True */;
42759 if (variance === 1 /* Covariant */) {
42760 related = isRelatedTo(s, t, reportErrors);
42761 }
42762 else if (variance === 2 /* Contravariant */) {
42763 related = isRelatedTo(t, s, reportErrors);
42764 }
42765 else if (variance === 3 /* Bivariant */) {
42766 // In the bivariant case we first compare contravariantly without reporting
42767 // errors. Then, if that doesn't succeed, we compare covariantly with error
42768 // reporting. Thus, error elaboration will be based on the the covariant check,
42769 // which is generally easier to reason about.
42770 related = isRelatedTo(t, s, /*reportErrors*/ false);
42771 if (!related) {
42772 related = isRelatedTo(s, t, reportErrors);
42773 }
42774 }
42775 else {
42776 // In the invariant case we first compare covariantly, and only when that
42777 // succeeds do we proceed to compare contravariantly. Thus, error elaboration
42778 // will typically be based on the covariant check.
42779 related = isRelatedTo(s, t, reportErrors);
42780 if (related) {
42781 related &= isRelatedTo(t, s, reportErrors);
42782 }
42783 }
42784 if (!related) {
42785 return 0 /* False */;
42786 }
42787 result &= related;
42788 }
42789 }
42790 return result;
42791 }
42792 // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
42793 // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
42794 // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
42795 // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
42796 // and issue an error. Otherwise, actually compare the structure of the two types.
42797 function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) {
42798 if (overflow) {
42799 return 0 /* False */;
42800 }
42801 var id = getRelationKey(source, target, relation);
42802 var related = relation.get(id);
42803 if (related !== undefined) {
42804 if (reportErrors && related === 2 /* Failed */) {
42805 // We are elaborating errors and the cached result is an unreported failure. The result will be reported
42806 // as a failure, and should be updated as a reported failure by the bottom of this function.
42807 }
42808 else {
42809 return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
42810 }
42811 }
42812 if (!maybeKeys) {
42813 maybeKeys = [];
42814 sourceStack = [];
42815 targetStack = [];
42816 }
42817 else {
42818 for (var i = 0; i < maybeCount; i++) {
42819 // If source and target are already being compared, consider them related with assumptions
42820 if (id === maybeKeys[i]) {
42821 return 1 /* Maybe */;
42822 }
42823 }
42824 if (depth === 100) {
42825 overflow = true;
42826 return 0 /* False */;
42827 }
42828 }
42829 var maybeStart = maybeCount;
42830 maybeKeys[maybeCount] = id;
42831 maybeCount++;
42832 sourceStack[depth] = source;
42833 targetStack[depth] = target;
42834 depth++;
42835 var saveExpandingFlags = expandingFlags;
42836 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
42837 expandingFlags |= 1 /* Source */;
42838 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
42839 expandingFlags |= 2 /* Target */;
42840 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : 1 /* Maybe */;
42841 expandingFlags = saveExpandingFlags;
42842 depth--;
42843 if (result) {
42844 if (result === -1 /* True */ || depth === 0) {
42845 // If result is definitely true, record all maybe keys as having succeeded
42846 for (var i = maybeStart; i < maybeCount; i++) {
42847 relation.set(maybeKeys[i], 1 /* Succeeded */);
42848 }
42849 maybeCount = maybeStart;
42850 }
42851 }
42852 else {
42853 // A false result goes straight into global cache (when something is false under
42854 // assumptions it will also be false without assumptions)
42855 relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */);
42856 maybeCount = maybeStart;
42857 }
42858 return result;
42859 }
42860 function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) {
42861 var flags = source.flags & target.flags;
42862 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
42863 if (flags & 4194304 /* Index */) {
42864 return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
42865 }
42866 var result_3 = 0 /* False */;
42867 if (flags & 8388608 /* IndexedAccess */) {
42868 if (result_3 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
42869 if (result_3 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
42870 return result_3;
42871 }
42872 }
42873 }
42874 if (flags & 16777216 /* Conditional */) {
42875 if (source.root.isDistributive === target.root.isDistributive) {
42876 if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
42877 if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
42878 if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) {
42879 if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) {
42880 return result_3;
42881 }
42882 }
42883 }
42884 }
42885 }
42886 }
42887 if (flags & 33554432 /* Substitution */) {
42888 return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
42889 }
42890 return 0 /* False */;
42891 }
42892 var result;
42893 var originalErrorInfo;
42894 var varianceCheckFailed = false;
42895 var saveErrorInfo = errorInfo;
42896 // We limit alias variance probing to only object and conditional types since their alias behavior
42897 // is more predictable than other, interned types, which may or may not have an alias depending on
42898 // the order in which things were checked.
42899 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
42900 source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
42901 !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
42902 var variances = getAliasVariances(source.aliasSymbol);
42903 var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances);
42904 if (varianceResult !== undefined) {
42905 return varianceResult;
42906 }
42907 }
42908 if (target.flags & 262144 /* TypeParameter */) {
42909 // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q].
42910 if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
42911 if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
42912 var templateType = getTemplateTypeFromMappedType(source);
42913 var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
42914 if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
42915 return result;
42916 }
42917 }
42918 }
42919 }
42920 else if (target.flags & 4194304 /* Index */) {
42921 // A keyof S is related to a keyof T if T is related to S.
42922 if (source.flags & 4194304 /* Index */) {
42923 if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
42924 return result;
42925 }
42926 }
42927 // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
42928 // simplified form of T or, if T doesn't simplify, the constraint of T.
42929 var simplified = getSimplifiedType(target.type);
42930 var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type);
42931 if (constraint) {
42932 // We require Ternary.True here such that circular constraints don't cause
42933 // false positives. For example, given 'T extends { [K in keyof T]: string }',
42934 // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
42935 // related to other types.
42936 if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
42937 return -1 /* True */;
42938 }
42939 }
42940 }
42941 else if (target.flags & 8388608 /* IndexedAccess */) {
42942 // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C,
42943 // where C is the base constraint of T[K]
42944 if (relation !== identityRelation &&
42945 !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) {
42946 var constraint = getBaseConstraintOfType(target);
42947 if (constraint && constraint !== target) {
42948 if (result = isRelatedTo(source, constraint, reportErrors)) {
42949 return result;
42950 }
42951 }
42952 }
42953 }
42954 else if (isGenericMappedType(target)) {
42955 // A source type T is related to a target type { [P in X]: T[P] }
42956 var template = getTemplateTypeFromMappedType(target);
42957 var modifiers = getMappedTypeModifiers(target);
42958 if (!(modifiers & 8 /* ExcludeOptional */)) {
42959 if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
42960 template.indexType === getTypeParameterFromMappedType(target)) {
42961 return -1 /* True */;
42962 }
42963 if (!isGenericMappedType(source)) {
42964 var targetConstraint = getConstraintTypeFromMappedType(target);
42965 var sourceKeys_1 = getIndexType(source);
42966 var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */;
42967 var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined;
42968 // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X.
42969 // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
42970 if (hasOptionalUnionKeys
42971 ? !(filteredByApplicability.flags & 131072 /* Never */)
42972 : isRelatedTo(targetConstraint, sourceKeys_1)) {
42973 var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target);
42974 var indexedAccessType = getIndexedAccessType(source, indexingType);
42975 var templateType = getTemplateTypeFromMappedType(target);
42976 if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
42977 return result;
42978 }
42979 }
42980 originalErrorInfo = errorInfo;
42981 errorInfo = saveErrorInfo;
42982 }
42983 }
42984 }
42985 if (source.flags & 8650752 /* TypeVariable */) {
42986 if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
42987 // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
42988 if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
42989 result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
42990 }
42991 if (result) {
42992 errorInfo = saveErrorInfo;
42993 return result;
42994 }
42995 }
42996 var constraint = getConstraintOfType(source);
42997 if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
42998 // A type variable with no constraint is not related to the non-primitive object type.
42999 if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
43000 errorInfo = saveErrorInfo;
43001 return result;
43002 }
43003 }
43004 // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed
43005 else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) {
43006 errorInfo = saveErrorInfo;
43007 return result;
43008 }
43009 // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
43010 else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) {
43011 errorInfo = saveErrorInfo;
43012 return result;
43013 }
43014 }
43015 else if (source.flags & 4194304 /* Index */) {
43016 if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
43017 errorInfo = saveErrorInfo;
43018 return result;
43019 }
43020 }
43021 else if (source.flags & 16777216 /* Conditional */) {
43022 if (target.flags & 16777216 /* Conditional */) {
43023 // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
43024 // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
43025 // and Y1 is related to Y2.
43026 if (isTypeIdenticalTo(source.extendsType, target.extendsType) &&
43027 (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
43028 if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
43029 result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
43030 }
43031 if (result) {
43032 errorInfo = saveErrorInfo;
43033 return result;
43034 }
43035 }
43036 }
43037 else {
43038 var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
43039 if (distributiveConstraint) {
43040 if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
43041 errorInfo = saveErrorInfo;
43042 return result;
43043 }
43044 }
43045 var defaultConstraint = getDefaultConstraintOfConditionalType(source);
43046 if (defaultConstraint) {
43047 if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
43048 errorInfo = saveErrorInfo;
43049 return result;
43050 }
43051 }
43052 }
43053 }
43054 else {
43055 // An empty object type is related to any mapped type that includes a '?' modifier.
43056 if (relation !== subtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
43057 return -1 /* True */;
43058 }
43059 if (isGenericMappedType(target)) {
43060 if (isGenericMappedType(source)) {
43061 if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
43062 errorInfo = saveErrorInfo;
43063 return result;
43064 }
43065 }
43066 return 0 /* False */;
43067 }
43068 var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
43069 if (relation !== identityRelation) {
43070 source = getApparentType(source);
43071 }
43072 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
43073 !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
43074 // We have type references to the same generic type, and the type references are not marker
43075 // type references (which are intended by be compared structurally). Obtain the variance
43076 // information for the type parameters and relate the type arguments accordingly.
43077 var variances = getVariances(source.target);
43078 var varianceResult = relateVariances(source.typeArguments, target.typeArguments, variances);
43079 if (varianceResult !== undefined) {
43080 return varianceResult;
43081 }
43082 }
43083 else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
43084 return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
43085 }
43086 // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
43087 // and not `{} <- fresh({}) <- {[idx: string]: any}`
43088 else if (relation === subtypeRelation && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
43089 return 0 /* False */;
43090 }
43091 // Even if relationship doesn't hold for unions, intersections, or generic type references,
43092 // it may hold in a structural comparison.
43093 // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
43094 // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
43095 // relates to X. Thus, we include intersection types on the source side here.
43096 if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
43097 // Report structural errors only if we haven't reported any errors yet
43098 var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive;
43099 result = propertiesRelatedTo(source, target, reportStructuralErrors);
43100 if (result) {
43101 result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
43102 if (result) {
43103 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
43104 if (result) {
43105 result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors);
43106 if (result) {
43107 result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors);
43108 }
43109 }
43110 }
43111 }
43112 if (varianceCheckFailed && result) {
43113 errorInfo = originalErrorInfo || errorInfo || saveErrorInfo; // Use variance error (there is no structural one) and return false
43114 }
43115 else if (result) {
43116 return result;
43117 }
43118 }
43119 }
43120 return 0 /* False */;
43121 function isNonGeneric(type) {
43122 // If we're already in identity relationship checking, we should use `isRelatedTo`
43123 // to catch the `Maybe` from an excessively deep type (which we then assume means
43124 // that the type could possibly contain a generic)
43125 if (relation === identityRelation) {
43126 return isRelatedTo(type, getPermissiveInstantiation(type)) === -1 /* True */;
43127 }
43128 return isTypeIdenticalTo(type, getPermissiveInstantiation(type));
43129 }
43130 function relateVariances(sourceTypeArguments, targetTypeArguments, variances) {
43131 if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) {
43132 return result;
43133 }
43134 var allowStructuralFallback = (targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances)) || isNonGeneric(source) || isNonGeneric(target);
43135 varianceCheckFailed = !allowStructuralFallback;
43136 // The type arguments did not relate appropriately, but it may be because we have no variance
43137 // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
43138 // arguments). It might also be the case that the target type has a 'void' type argument for
43139 // a covariant type parameter that is only used in return positions within the generic type
43140 // (in which case any type argument is permitted on the source side). In those cases we proceed
43141 // with a structural comparison. Otherwise, we know for certain the instantiations aren't
43142 // related and we can return here.
43143 if (variances !== ts.emptyArray && !allowStructuralFallback) {
43144 // In some cases generic types that are covariant in regular type checking mode become
43145 // invariant in --strictFunctionTypes mode because one or more type parameters are used in
43146 // both co- and contravariant positions. In order to make it easier to diagnose *why* such
43147 // types are invariant, if any of the type parameters are invariant we reset the reported
43148 // errors and instead force a structural comparison (which will include elaborations that
43149 // reveal the reason).
43150 // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
43151 // we can return `False` early here to skip calculating the structural error message we don't need.
43152 if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
43153 return 0 /* False */;
43154 }
43155 // We remember the original error information so we can restore it in case the structural
43156 // comparison unexpectedly succeeds. This can happen when the structural comparison result
43157 // is a Ternary.Maybe for example caused by the recursion depth limiter.
43158 originalErrorInfo = errorInfo;
43159 errorInfo = saveErrorInfo;
43160 }
43161 }
43162 }
43163 // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
43164 // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
43165 // that S and T are contra-variant whereas X and Y are co-variant.
43166 function mappedTypeRelatedTo(source, target, reportErrors) {
43167 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
43168 getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
43169 if (modifiersRelated) {
43170 var result_4;
43171 if (result_4 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
43172 var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
43173 return result_4 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
43174 }
43175 }
43176 return 0 /* False */;
43177 }
43178 function propertiesRelatedTo(source, target, reportErrors) {
43179 if (relation === identityRelation) {
43180 return propertiesIdenticalTo(source, target);
43181 }
43182 var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
43183 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
43184 if (unmatchedProperty) {
43185 if (reportErrors) {
43186 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
43187 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
43188 headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
43189 suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it
43190 }
43191 if (props.length === 1) {
43192 var propName = symbolToString(unmatchedProperty);
43193 reportError(ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target));
43194 if (ts.length(unmatchedProperty.declarations)) {
43195 associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
43196 }
43197 }
43198 else if (props.length > 5) { // arbitrary cutoff for too-long list form
43199 reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4);
43200 }
43201 else {
43202 reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", "));
43203 }
43204 }
43205 return 0 /* False */;
43206 }
43207 if (isObjectLiteralType(target)) {
43208 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
43209 var sourceProp = _a[_i];
43210 if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
43211 var sourceType = getTypeOfSymbol(sourceProp);
43212 if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) {
43213 if (reportErrors) {
43214 reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
43215 }
43216 return 0 /* False */;
43217 }
43218 }
43219 }
43220 }
43221 var result = -1 /* True */;
43222 if (isTupleType(target)) {
43223 var targetRestType = getRestTypeOfTupleType(target);
43224 if (targetRestType) {
43225 if (!isTupleType(source)) {
43226 return 0 /* False */;
43227 }
43228 var sourceRestType = getRestTypeOfTupleType(source);
43229 if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) {
43230 if (reportErrors) {
43231 reportError(ts.Diagnostics.Rest_signatures_are_incompatible);
43232 }
43233 return 0 /* False */;
43234 }
43235 var targetCount = getTypeReferenceArity(target) - 1;
43236 var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0);
43237 for (var i = targetCount; i < sourceCount; i++) {
43238 var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors);
43239 if (!related) {
43240 if (reportErrors) {
43241 reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i);
43242 }
43243 return 0 /* False */;
43244 }
43245 result &= related;
43246 }
43247 }
43248 }
43249 var properties = getPropertiesOfObjectType(target);
43250 for (var _b = 0, properties_2 = properties; _b < properties_2.length; _b++) {
43251 var targetProp = properties_2[_b];
43252 if (!(targetProp.flags & 4194304 /* Prototype */)) {
43253 var sourceProp = getPropertyOfType(source, targetProp.escapedName);
43254 if (sourceProp && sourceProp !== targetProp) {
43255 if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) {
43256 continue;
43257 }
43258 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
43259 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
43260 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
43261 var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration;
43262 if (ts.getCheckFlags(sourceProp) & 512 /* ContainsPrivate */ && hasDifferingDeclarations) {
43263 if (reportErrors) {
43264 reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source));
43265 }
43266 return 0 /* False */;
43267 }
43268 if (hasDifferingDeclarations) {
43269 if (reportErrors) {
43270 if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
43271 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
43272 }
43273 else {
43274 reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source));
43275 }
43276 }
43277 return 0 /* False */;
43278 }
43279 }
43280 else if (targetPropFlags & 16 /* Protected */) {
43281 if (!isValidOverrideOf(sourceProp, targetProp)) {
43282 if (reportErrors) {
43283 reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target));
43284 }
43285 return 0 /* False */;
43286 }
43287 }
43288 else if (sourcePropFlags & 16 /* Protected */) {
43289 if (reportErrors) {
43290 reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
43291 }
43292 return 0 /* False */;
43293 }
43294 var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors);
43295 if (!related) {
43296 if (reportErrors) {
43297 reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
43298 }
43299 return 0 /* False */;
43300 }
43301 result &= related;
43302 // When checking for comparability, be more lenient with optional properties.
43303 if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
43304 // TypeScript 1.0 spec (April 2014): 3.8.3
43305 // S is a subtype of a type T, and T is a supertype of S if ...
43306 // S' and T are object types and, for each member M in T..
43307 // M is a property and S' contains a property N where
43308 // if M is a required property, N is also a required property
43309 // (M - property in T)
43310 // (N - property in S)
43311 if (reportErrors) {
43312 reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
43313 }
43314 return 0 /* False */;
43315 }
43316 }
43317 }
43318 }
43319 return result;
43320 }
43321 function propertiesIdenticalTo(source, target) {
43322 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
43323 return 0 /* False */;
43324 }
43325 var sourceProperties = getPropertiesOfObjectType(source);
43326 var targetProperties = getPropertiesOfObjectType(target);
43327 if (sourceProperties.length !== targetProperties.length) {
43328 return 0 /* False */;
43329 }
43330 var result = -1 /* True */;
43331 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
43332 var sourceProp = sourceProperties_1[_i];
43333 var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
43334 if (!targetProp) {
43335 return 0 /* False */;
43336 }
43337 var related = compareProperties(sourceProp, targetProp, isRelatedTo);
43338 if (!related) {
43339 return 0 /* False */;
43340 }
43341 result &= related;
43342 }
43343 return result;
43344 }
43345 function signaturesRelatedTo(source, target, kind, reportErrors) {
43346 if (relation === identityRelation) {
43347 return signaturesIdenticalTo(source, target, kind);
43348 }
43349 if (target === anyFunctionType || source === anyFunctionType) {
43350 return -1 /* True */;
43351 }
43352 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
43353 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
43354 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
43355 0 /* Call */ : kind);
43356 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
43357 0 /* Call */ : kind);
43358 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
43359 if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
43360 // An abstract constructor type is not assignable to a non-abstract constructor type
43361 // as it would otherwise be possible to new an abstract class. Note that the assignability
43362 // check we perform for an extends clause excludes construct signatures from the target,
43363 // so this check never proceeds.
43364 if (reportErrors) {
43365 reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
43366 }
43367 return 0 /* False */;
43368 }
43369 if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
43370 return 0 /* False */;
43371 }
43372 }
43373 var result = -1 /* True */;
43374 var saveErrorInfo = errorInfo;
43375 if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) {
43376 // We have instantiations of the same anonymous type (which typically will be the type of a
43377 // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
43378 // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
43379 // as they are known to always be the same.
43380 for (var i = 0; i < targetSignatures.length; i++) {
43381 var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors);
43382 if (!related) {
43383 return 0 /* False */;
43384 }
43385 result &= related;
43386 }
43387 }
43388 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
43389 // For simple functions (functions with a single signature) we only erase type parameters for
43390 // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
43391 // in the context of the target signature before checking the relationship. Ideally we'd do
43392 // this regardless of the number of signatures, but the potential costs are prohibitive due
43393 // to the quadratic nature of the logic below.
43394 var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
43395 result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors);
43396 }
43397 else {
43398 outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
43399 var t = targetSignatures_1[_i];
43400 // Only elaborate errors from the first failure
43401 var shouldElaborateErrors = reportErrors;
43402 for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) {
43403 var s = sourceSignatures_1[_a];
43404 var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors);
43405 if (related) {
43406 result &= related;
43407 errorInfo = saveErrorInfo;
43408 continue outer;
43409 }
43410 shouldElaborateErrors = false;
43411 }
43412 if (shouldElaborateErrors) {
43413 reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
43414 }
43415 return 0 /* False */;
43416 }
43417 }
43418 return result;
43419 }
43420 /**
43421 * See signatureAssignableTo, compareSignaturesIdentical
43422 */
43423 function signatureRelatedTo(source, target, erase, reportErrors) {
43424 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo);
43425 }
43426 function signaturesIdenticalTo(source, target, kind) {
43427 var sourceSignatures = getSignaturesOfType(source, kind);
43428 var targetSignatures = getSignaturesOfType(target, kind);
43429 if (sourceSignatures.length !== targetSignatures.length) {
43430 return 0 /* False */;
43431 }
43432 var result = -1 /* True */;
43433 for (var i = 0; i < sourceSignatures.length; i++) {
43434 var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
43435 if (!related) {
43436 return 0 /* False */;
43437 }
43438 result &= related;
43439 }
43440 return result;
43441 }
43442 function eachPropertyRelatedTo(source, target, kind, reportErrors) {
43443 var result = -1 /* True */;
43444 for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
43445 var prop = _a[_i];
43446 if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) {
43447 continue;
43448 }
43449 // Skip over symbol-named members
43450 if (prop.nameType && prop.nameType.flags & 8192 /* UniqueESSymbol */) {
43451 continue;
43452 }
43453 if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
43454 var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
43455 if (!related) {
43456 if (reportErrors) {
43457 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
43458 }
43459 return 0 /* False */;
43460 }
43461 result &= related;
43462 }
43463 }
43464 return result;
43465 }
43466 function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) {
43467 var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors);
43468 if (!related && reportErrors) {
43469 reportError(ts.Diagnostics.Index_signatures_are_incompatible);
43470 }
43471 return related;
43472 }
43473 function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) {
43474 if (relation === identityRelation) {
43475 return indexTypesIdenticalTo(source, target, kind);
43476 }
43477 var targetInfo = getIndexInfoOfType(target, kind);
43478 if (!targetInfo || targetInfo.type.flags & 3 /* AnyOrUnknown */ && !sourceIsPrimitive) {
43479 // Index signature of type any permits assignment from everything but primitives
43480 return -1 /* True */;
43481 }
43482 var sourceInfo = getIndexInfoOfType(source, kind) ||
43483 kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */);
43484 if (sourceInfo) {
43485 return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors);
43486 }
43487 if (isGenericMappedType(source)) {
43488 // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U }
43489 // if T is related to U.
43490 return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217
43491 }
43492 if (isObjectTypeWithInferableIndex(source)) {
43493 var related = -1 /* True */;
43494 if (kind === 0 /* String */) {
43495 var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */);
43496 if (sourceNumberInfo) {
43497 related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors);
43498 }
43499 }
43500 if (related) {
43501 related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors);
43502 }
43503 return related;
43504 }
43505 if (reportErrors) {
43506 reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
43507 }
43508 return 0 /* False */;
43509 }
43510 function indexTypesIdenticalTo(source, target, indexKind) {
43511 var targetInfo = getIndexInfoOfType(target, indexKind);
43512 var sourceInfo = getIndexInfoOfType(source, indexKind);
43513 if (!sourceInfo && !targetInfo) {
43514 return -1 /* True */;
43515 }
43516 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
43517 return isRelatedTo(sourceInfo.type, targetInfo.type);
43518 }
43519 return 0 /* False */;
43520 }
43521 function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
43522 if (!sourceSignature.declaration || !targetSignature.declaration) {
43523 return true;
43524 }
43525 var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
43526 var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
43527 // A public, protected and private signature is assignable to a private signature.
43528 if (targetAccessibility === 8 /* Private */) {
43529 return true;
43530 }
43531 // A public and protected signature is assignable to a protected signature.
43532 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
43533 return true;
43534 }
43535 // Only a public signature is assignable to public signature.
43536 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
43537 return true;
43538 }
43539 if (reportErrors) {
43540 reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
43541 }
43542 return false;
43543 }
43544 }
43545 function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) {
43546 var match;
43547 for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
43548 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
43549 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
43550 var type = _c[_b];
43551 var targetType = getTypeOfPropertyOfType(type, propertyName);
43552 if (targetType && related(getDiscriminatingType(), targetType)) {
43553 if (match) {
43554 if (type === match)
43555 continue; // Finding multiple fields which discriminate to the same type is fine
43556 return defaultValue;
43557 }
43558 match = type;
43559 }
43560 }
43561 }
43562 return match || defaultValue;
43563 }
43564 /**
43565 * A type is 'weak' if it is an object type with at least one optional property
43566 * and no required properties, call/construct signatures or index signatures
43567 */
43568 function isWeakType(type) {
43569 if (type.flags & 524288 /* Object */) {
43570 var resolved = resolveStructuredTypeMembers(type);
43571 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
43572 !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
43573 resolved.properties.length > 0 &&
43574 ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
43575 }
43576 if (type.flags & 2097152 /* Intersection */) {
43577 return ts.every(type.types, isWeakType);
43578 }
43579 return false;
43580 }
43581 function hasCommonProperties(source, target, isComparingJsxAttributes) {
43582 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
43583 var prop = _a[_i];
43584 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
43585 return true;
43586 }
43587 }
43588 return false;
43589 }
43590 // Return a type reference where the source type parameter is replaced with the target marker
43591 // type, and flag the result as a marker type reference.
43592 function getMarkerTypeReference(type, source, target) {
43593 var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
43594 result.objectFlags |= 8192 /* MarkerType */;
43595 return result;
43596 }
43597 function getAliasVariances(symbol) {
43598 var links = getSymbolLinks(symbol);
43599 return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
43600 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
43601 type.aliasTypeArgumentsContainsMarker = true;
43602 return type;
43603 });
43604 }
43605 // Return an array containing the variance of each type parameter. The variance is effectively
43606 // a digest of the type comparisons that occur for each type argument when instantiations of the
43607 // generic type are structurally compared. We infer the variance information by comparing
43608 // instantiations of the generic type for type arguments with known relations. The function
43609 // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function
43610 // has been invoked recursively for the given generic type.
43611 function getVariancesWorker(typeParameters, cache, createMarkerType) {
43612 if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
43613 var variances = cache.variances;
43614 if (!variances) {
43615 // The emptyArray singleton is used to signal a recursive invocation.
43616 cache.variances = ts.emptyArray;
43617 variances = [];
43618 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
43619 var tp = typeParameters_1[_i];
43620 // We first compare instantiations where the type parameter is replaced with
43621 // marker types that have a known subtype relationship. From this we can infer
43622 // invariance, covariance, contravariance or bivariance.
43623 var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
43624 var typeWithSub = createMarkerType(cache, tp, markerSubType);
43625 var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
43626 (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
43627 // If the instantiations appear to be related bivariantly it may be because the
43628 // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
43629 // type). To determine this we compare instantiations where the type parameter is
43630 // replaced with marker types that are known to be unrelated.
43631 if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
43632 variance = 4 /* Independent */;
43633 }
43634 variances.push(variance);
43635 }
43636 cache.variances = variances;
43637 }
43638 return variances;
43639 }
43640 function getVariances(type) {
43641 // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
43642 if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
43643 return ts.emptyArray;
43644 }
43645 return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
43646 }
43647 // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
43648 // See comment at call in recursiveTypeRelatedTo for when this case matters.
43649 function hasCovariantVoidArgument(typeArguments, variances) {
43650 for (var i = 0; i < variances.length; i++) {
43651 if (variances[i] === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
43652 return true;
43653 }
43654 }
43655 return false;
43656 }
43657 function isUnconstrainedTypeParameter(type) {
43658 return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
43659 }
43660 function isTypeReferenceWithGenericArguments(type) {
43661 return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
43662 }
43663 /**
43664 * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
43665 * where A.id=111 and number.id=12
43666 */
43667 function getTypeReferenceId(type, typeParameters, depth) {
43668 if (depth === void 0) { depth = 0; }
43669 var result = "" + type.target.id;
43670 for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) {
43671 var t = _a[_i];
43672 if (isUnconstrainedTypeParameter(t)) {
43673 var index = typeParameters.indexOf(t);
43674 if (index < 0) {
43675 index = typeParameters.length;
43676 typeParameters.push(t);
43677 }
43678 result += "=" + index;
43679 }
43680 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
43681 result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
43682 }
43683 else {
43684 result += "-" + t.id;
43685 }
43686 }
43687 return result;
43688 }
43689 /**
43690 * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
43691 * For other cases, the types ids are used.
43692 */
43693 function getRelationKey(source, target, relation) {
43694 if (relation === identityRelation && source.id > target.id) {
43695 var temp = source;
43696 source = target;
43697 target = temp;
43698 }
43699 if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
43700 var typeParameters = [];
43701 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters);
43702 }
43703 return source.id + "," + target.id;
43704 }
43705 // Invoke the callback for each underlying property symbol of the given symbol and return the first
43706 // value that isn't undefined.
43707 function forEachProperty(prop, callback) {
43708 if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
43709 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
43710 var t = _a[_i];
43711 var p = getPropertyOfType(t, prop.escapedName);
43712 var result = p && forEachProperty(p, callback);
43713 if (result) {
43714 return result;
43715 }
43716 }
43717 return undefined;
43718 }
43719 return callback(prop);
43720 }
43721 // Return the declaring class type of a property or undefined if property not declared in class
43722 function getDeclaringClass(prop) {
43723 return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
43724 }
43725 // Return true if some underlying source property is declared in a class that derives
43726 // from the given base class.
43727 function isPropertyInClassDerivedFrom(prop, baseClass) {
43728 return forEachProperty(prop, function (sp) {
43729 var sourceClass = getDeclaringClass(sp);
43730 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
43731 });
43732 }
43733 // Return true if source property is a valid override of protected parts of target property.
43734 function isValidOverrideOf(sourceProp, targetProp) {
43735 return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
43736 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
43737 }
43738 // Return true if the given class derives from each of the declaring classes of the protected
43739 // constituents of the given property.
43740 function isClassDerivedFromDeclaringClasses(checkClass, prop) {
43741 return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
43742 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
43743 }
43744 // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
43745 // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
43746 // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
43747 // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
43748 // levels, but unequal at some level beyond that.
43749 function isDeeplyNestedType(type, stack, depth) {
43750 // We track all object types that have an associated symbol (representing the origin of the type)
43751 if (depth >= 5 && type.flags & 524288 /* Object */) {
43752 var symbol = type.symbol;
43753 if (symbol) {
43754 var count = 0;
43755 for (var i = 0; i < depth; i++) {
43756 var t = stack[i];
43757 if (t.flags & 524288 /* Object */ && t.symbol === symbol) {
43758 count++;
43759 if (count >= 5)
43760 return true;
43761 }
43762 }
43763 }
43764 }
43765 return false;
43766 }
43767 function isPropertyIdenticalTo(sourceProp, targetProp) {
43768 return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
43769 }
43770 function compareProperties(sourceProp, targetProp, compareTypes) {
43771 // Two members are considered identical when
43772 // - they are public properties with identical names, optionality, and types,
43773 // - they are private or protected properties originating in the same declaration and having identical types
43774 if (sourceProp === targetProp) {
43775 return -1 /* True */;
43776 }
43777 var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
43778 var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
43779 if (sourcePropAccessibility !== targetPropAccessibility) {
43780 return 0 /* False */;
43781 }
43782 if (sourcePropAccessibility) {
43783 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
43784 return 0 /* False */;
43785 }
43786 }
43787 else {
43788 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
43789 return 0 /* False */;
43790 }
43791 }
43792 if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
43793 return 0 /* False */;
43794 }
43795 return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
43796 }
43797 function isMatchingSignature(source, target, partialMatch) {
43798 var sourceParameterCount = getParameterCount(source);
43799 var targetParameterCount = getParameterCount(target);
43800 var sourceMinArgumentCount = getMinArgumentCount(source);
43801 var targetMinArgumentCount = getMinArgumentCount(target);
43802 var sourceHasRestParameter = hasEffectiveRestParameter(source);
43803 var targetHasRestParameter = hasEffectiveRestParameter(target);
43804 // A source signature matches a target signature if the two signatures have the same number of required,
43805 // optional, and rest parameters.
43806 if (sourceParameterCount === targetParameterCount &&
43807 sourceMinArgumentCount === targetMinArgumentCount &&
43808 sourceHasRestParameter === targetHasRestParameter) {
43809 return true;
43810 }
43811 // A source signature partially matches a target signature if the target signature has no fewer required
43812 // parameters
43813 if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
43814 return true;
43815 }
43816 return false;
43817 }
43818 /**
43819 * See signatureRelatedTo, compareSignaturesIdentical
43820 */
43821 function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
43822 // TODO (drosen): De-duplicate code between related functions.
43823 if (source === target) {
43824 return -1 /* True */;
43825 }
43826 if (!(isMatchingSignature(source, target, partialMatch))) {
43827 return 0 /* False */;
43828 }
43829 // Check that the two signatures have the same number of type parameters. We might consider
43830 // also checking that any type parameter constraints match, but that would require instantiating
43831 // the constraints with a common set of type arguments to get relatable entities in places where
43832 // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile,
43833 // particularly as we're comparing erased versions of the signatures below.
43834 if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
43835 return 0 /* False */;
43836 }
43837 // Spec 1.0 Section 3.8.3 & 3.8.4:
43838 // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N
43839 source = getErasedSignature(source);
43840 target = getErasedSignature(target);
43841 var result = -1 /* True */;
43842 if (!ignoreThisTypes) {
43843 var sourceThisType = getThisTypeOfSignature(source);
43844 if (sourceThisType) {
43845 var targetThisType = getThisTypeOfSignature(target);
43846 if (targetThisType) {
43847 var related = compareTypes(sourceThisType, targetThisType);
43848 if (!related) {
43849 return 0 /* False */;
43850 }
43851 result &= related;
43852 }
43853 }
43854 }
43855 var targetLen = getParameterCount(target);
43856 for (var i = 0; i < targetLen; i++) {
43857 var s = getTypeAtPosition(source, i);
43858 var t = getTypeAtPosition(target, i);
43859 var related = compareTypes(t, s);
43860 if (!related) {
43861 return 0 /* False */;
43862 }
43863 result &= related;
43864 }
43865 if (!ignoreReturnTypes) {
43866 var sourceTypePredicate = getTypePredicateOfSignature(source);
43867 var targetTypePredicate = getTypePredicateOfSignature(target);
43868 result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined
43869 ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes)
43870 // If they're both type predicates their return types will both be `boolean`, so no need to compare those.
43871 : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
43872 }
43873 return result;
43874 }
43875 function compareTypePredicatesIdentical(source, target, compareTypes) {
43876 return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type);
43877 }
43878 function literalTypesWithSameBaseType(types) {
43879 var commonBaseType;
43880 for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
43881 var t = types_9[_i];
43882 var baseType = getBaseTypeOfLiteralType(t);
43883 if (!commonBaseType) {
43884 commonBaseType = baseType;
43885 }
43886 if (baseType === t || baseType !== commonBaseType) {
43887 return false;
43888 }
43889 }
43890 return true;
43891 }
43892 // When the candidate types are all literal types with the same base type, return a union
43893 // of those literal types. Otherwise, return the leftmost type for which no type to the
43894 // right is a supertype.
43895 function getSupertypeOrUnion(types) {
43896 return literalTypesWithSameBaseType(types) ?
43897 getUnionType(types) :
43898 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
43899 }
43900 function getCommonSupertype(types) {
43901 if (!strictNullChecks) {
43902 return getSupertypeOrUnion(types);
43903 }
43904 var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
43905 return primaryTypes.length ?
43906 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
43907 getUnionType(types, 2 /* Subtype */);
43908 }
43909 // Return the leftmost type for which no type to the right is a subtype.
43910 function getCommonSubtype(types) {
43911 return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
43912 }
43913 function isArrayType(type) {
43914 return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
43915 }
43916 function isReadonlyArrayType(type) {
43917 return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
43918 }
43919 function getElementTypeOfArrayType(type) {
43920 return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined;
43921 }
43922 function isArrayLikeType(type) {
43923 // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
43924 // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
43925 return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
43926 }
43927 function isEmptyArrayLiteralType(type) {
43928 var elementType = isArrayType(type) ? type.typeArguments[0] : undefined;
43929 return elementType === undefinedWideningType || elementType === implicitNeverType;
43930 }
43931 function isTupleLikeType(type) {
43932 return isTupleType(type) || !!getPropertyOfType(type, "0");
43933 }
43934 function isArrayOrTupleLikeType(type) {
43935 return isArrayLikeType(type) || isTupleLikeType(type);
43936 }
43937 function getTupleElementType(type, index) {
43938 var propType = getTypeOfPropertyOfType(type, "" + index);
43939 if (propType) {
43940 return propType;
43941 }
43942 if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) {
43943 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
43944 }
43945 return undefined;
43946 }
43947 function isNeitherUnitTypeNorNever(type) {
43948 return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
43949 }
43950 function isUnitType(type) {
43951 return !!(type.flags & 109440 /* Unit */);
43952 }
43953 function isLiteralType(type) {
43954 return type.flags & 16 /* Boolean */ ? true :
43955 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
43956 isUnitType(type);
43957 }
43958 function getBaseTypeOfLiteralType(type) {
43959 return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
43960 type.flags & 128 /* StringLiteral */ ? stringType :
43961 type.flags & 256 /* NumberLiteral */ ? numberType :
43962 type.flags & 2048 /* BigIntLiteral */ ? bigintType :
43963 type.flags & 512 /* BooleanLiteral */ ? booleanType :
43964 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
43965 type;
43966 }
43967 function getWidenedLiteralType(type) {
43968 return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
43969 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
43970 type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
43971 type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
43972 type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
43973 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
43974 type;
43975 }
43976 function getWidenedUniqueESSymbolType(type) {
43977 return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
43978 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
43979 type;
43980 }
43981 function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
43982 if (!isLiteralOfContextualType(type, contextualType)) {
43983 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
43984 }
43985 return type;
43986 }
43987 /**
43988 * Check if a Type was written as a tuple type literal.
43989 * Prefer using isTupleLikeType() unless the use of `elementTypes` is required.
43990 */
43991 function isTupleType(type) {
43992 return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
43993 }
43994 function getRestTypeOfTupleType(type) {
43995 return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined;
43996 }
43997 function getRestArrayTypeOfTupleType(type) {
43998 var restType = getRestTypeOfTupleType(type);
43999 return restType && createArrayType(restType);
44000 }
44001 function getLengthOfTupleType(type) {
44002 return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0);
44003 }
44004 function isZeroBigInt(_a) {
44005 var value = _a.value;
44006 return value.base10Value === "0";
44007 }
44008 function getFalsyFlagsOfTypes(types) {
44009 var result = 0;
44010 for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
44011 var t = types_10[_i];
44012 result |= getFalsyFlags(t);
44013 }
44014 return result;
44015 }
44016 // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
44017 // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
44018 // no flags for all other types (including non-falsy literal types).
44019 function getFalsyFlags(type) {
44020 return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
44021 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
44022 type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
44023 type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
44024 type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
44025 type.flags & 117724 /* PossiblyFalsy */;
44026 }
44027 function removeDefinitelyFalsyTypes(type) {
44028 return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
44029 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
44030 type;
44031 }
44032 function extractDefinitelyFalsyTypes(type) {
44033 return mapType(type, getDefinitelyFalsyPartOfType);
44034 }
44035 function getDefinitelyFalsyPartOfType(type) {
44036 return type.flags & 4 /* String */ ? emptyStringType :
44037 type.flags & 8 /* Number */ ? zeroType :
44038 type.flags & 64 /* BigInt */ ? zeroBigIntType :
44039 type === regularFalseType ||
44040 type === falseType ||
44041 type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) ||
44042 type.flags & 128 /* StringLiteral */ && type.value === "" ||
44043 type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
44044 type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
44045 neverType;
44046 }
44047 /**
44048 * Add undefined or null or both to a type if they are missing.
44049 * @param type - type to add undefined and/or null to if not present
44050 * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
44051 */
44052 function getNullableType(type, flags) {
44053 var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
44054 return missing === 0 ? type :
44055 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
44056 missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
44057 getUnionType([type, undefinedType, nullType]);
44058 }
44059 function getOptionalType(type) {
44060 ts.Debug.assert(strictNullChecks);
44061 return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
44062 }
44063 function getGlobalNonNullableTypeInstantiation(type) {
44064 if (!deferredGlobalNonNullableTypeAlias) {
44065 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
44066 }
44067 // Use NonNullable global type alias if available to improve quick info/declaration emit
44068 if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
44069 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
44070 }
44071 return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
44072 }
44073 function getNonNullableType(type) {
44074 return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
44075 }
44076 /**
44077 * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
44078 * with no call or construct signatures.
44079 */
44080 function isObjectTypeWithInferableIndex(type) {
44081 return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 &&
44082 !typeHasCallOrConstructSignatures(type);
44083 }
44084 function createSymbolWithType(source, type) {
44085 var symbol = createSymbol(source.flags, source.escapedName);
44086 symbol.declarations = source.declarations;
44087 symbol.parent = source.parent;
44088 symbol.type = type;
44089 symbol.target = source;
44090 if (source.valueDeclaration) {
44091 symbol.valueDeclaration = source.valueDeclaration;
44092 }
44093 if (source.nameType) {
44094 symbol.nameType = source.nameType;
44095 }
44096 return symbol;
44097 }
44098 function transformTypeOfMembers(type, f) {
44099 var members = ts.createSymbolTable();
44100 for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
44101 var property = _a[_i];
44102 var original = getTypeOfSymbol(property);
44103 var updated = f(original);
44104 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
44105 }
44106 return members;
44107 }
44108 /**
44109 * If the the provided object literal is subject to the excess properties check,
44110 * create a new that is exempt. Recursively mark object literal members as exempt.
44111 * Leave signatures alone since they are not subject to the check.
44112 */
44113 function getRegularTypeOfObjectLiteral(type) {
44114 if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
44115 return type;
44116 }
44117 var regularType = type.regularType;
44118 if (regularType) {
44119 return regularType;
44120 }
44121 var resolved = type;
44122 var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
44123 var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
44124 regularNew.flags = resolved.flags;
44125 regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
44126 type.regularType = regularNew;
44127 return regularNew;
44128 }
44129 function createWideningContext(parent, propertyName, siblings) {
44130 return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
44131 }
44132 function getSiblingsOfContext(context) {
44133 if (!context.siblings) {
44134 var siblings_1 = [];
44135 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
44136 var type = _a[_i];
44137 if (isObjectLiteralType(type)) {
44138 var prop = getPropertyOfObjectType(type, context.propertyName);
44139 if (prop) {
44140 forEachType(getTypeOfSymbol(prop), function (t) {
44141 siblings_1.push(t);
44142 });
44143 }
44144 }
44145 }
44146 context.siblings = siblings_1;
44147 }
44148 return context.siblings;
44149 }
44150 function getPropertiesOfContext(context) {
44151 if (!context.resolvedProperties) {
44152 var names = ts.createMap();
44153 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
44154 var t = _a[_i];
44155 if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
44156 for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
44157 var prop = _c[_b];
44158 names.set(prop.escapedName, prop);
44159 }
44160 }
44161 }
44162 context.resolvedProperties = ts.arrayFrom(names.values());
44163 }
44164 return context.resolvedProperties;
44165 }
44166 function getWidenedProperty(prop, context) {
44167 if (!(prop.flags & 4 /* Property */)) {
44168 // Since get accessors already widen their return value there is no need to
44169 // widen accessor based properties here.
44170 return prop;
44171 }
44172 var original = getTypeOfSymbol(prop);
44173 var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
44174 var widened = getWidenedTypeWithContext(original, propContext);
44175 return widened === original ? prop : createSymbolWithType(prop, widened);
44176 }
44177 function getUndefinedProperty(prop) {
44178 var cached = undefinedProperties.get(prop.escapedName);
44179 if (cached) {
44180 return cached;
44181 }
44182 var result = createSymbolWithType(prop, undefinedType);
44183 result.flags |= 16777216 /* Optional */;
44184 undefinedProperties.set(prop.escapedName, result);
44185 return result;
44186 }
44187 function getWidenedTypeOfObjectLiteral(type, context) {
44188 var members = ts.createSymbolTable();
44189 for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
44190 var prop = _a[_i];
44191 members.set(prop.escapedName, getWidenedProperty(prop, context));
44192 }
44193 if (context) {
44194 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
44195 var prop = _c[_b];
44196 if (!members.has(prop.escapedName)) {
44197 members.set(prop.escapedName, getUndefinedProperty(prop));
44198 }
44199 }
44200 }
44201 var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
44202 var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
44203 var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
44204 result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening
44205 return result;
44206 }
44207 function getWidenedType(type) {
44208 return getWidenedTypeWithContext(type, /*context*/ undefined);
44209 }
44210 function getWidenedTypeWithContext(type, context) {
44211 if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) {
44212 if (type.flags & 98304 /* Nullable */) {
44213 return anyType;
44214 }
44215 if (isObjectLiteralType(type)) {
44216 return getWidenedTypeOfObjectLiteral(type, context);
44217 }
44218 if (type.flags & 1048576 /* Union */) {
44219 var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
44220 var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
44221 // Widening an empty object literal transitions from a highly restrictive type to
44222 // a highly inclusive one. For that reason we perform subtype reduction here if the
44223 // union includes empty object types (e.g. reducing {} | string to just {}).
44224 return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
44225 }
44226 if (type.flags & 2097152 /* Intersection */) {
44227 return getIntersectionType(ts.sameMap(type.types, getWidenedType));
44228 }
44229 if (isArrayType(type) || isTupleType(type)) {
44230 return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType));
44231 }
44232 }
44233 return type;
44234 }
44235 /**
44236 * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
44237 * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
44238 * getWidenedType. But in some cases getWidenedType is called without reporting errors
44239 * (type argument inference is an example).
44240 *
44241 * The return value indicates whether an error was in fact reported. The particular circumstances
44242 * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
44243 * an object literal property (arbitrarily deeply), this function reports an error. If no error is
44244 * reported, reportImplicitAnyError is a suitable fallback to report a general error.
44245 */
44246 function reportWideningErrorsInType(type) {
44247 var errorReported = false;
44248 if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
44249 if (type.flags & 1048576 /* Union */) {
44250 if (ts.some(type.types, isEmptyObjectType)) {
44251 errorReported = true;
44252 }
44253 else {
44254 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
44255 var t = _a[_i];
44256 if (reportWideningErrorsInType(t)) {
44257 errorReported = true;
44258 }
44259 }
44260 }
44261 }
44262 if (isArrayType(type) || isTupleType(type)) {
44263 for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) {
44264 var t = _c[_b];
44265 if (reportWideningErrorsInType(t)) {
44266 errorReported = true;
44267 }
44268 }
44269 }
44270 if (isObjectLiteralType(type)) {
44271 for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
44272 var p = _e[_d];
44273 var t = getTypeOfSymbol(p);
44274 if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) {
44275 if (!reportWideningErrorsInType(t)) {
44276 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
44277 }
44278 errorReported = true;
44279 }
44280 }
44281 }
44282 }
44283 return errorReported;
44284 }
44285 function reportImplicitAny(declaration, type) {
44286 var typeAsString = typeToString(getWidenedType(type));
44287 if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
44288 // Only report implicit any errors/suggestions in TS and ts-check JS files
44289 return;
44290 }
44291 var diagnostic;
44292 switch (declaration.kind) {
44293 case 204 /* BinaryExpression */:
44294 case 154 /* PropertyDeclaration */:
44295 case 153 /* PropertySignature */:
44296 diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
44297 break;
44298 case 151 /* Parameter */:
44299 var param = declaration;
44300 if (ts.isIdentifier(param.name) &&
44301 (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
44302 param.parent.parameters.indexOf(param) > -1 &&
44303 (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
44304 param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
44305 var newName = "arg" + param.parent.parameters.indexOf(param);
44306 errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
44307 return;
44308 }
44309 diagnostic = declaration.dotDotDotToken ?
44310 noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage :
44311 noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
44312 break;
44313 case 186 /* BindingElement */:
44314 diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
44315 if (!noImplicitAny) {
44316 // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
44317 return;
44318 }
44319 break;
44320 case 294 /* JSDocFunctionType */:
44321 error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
44322 return;
44323 case 239 /* FunctionDeclaration */:
44324 case 156 /* MethodDeclaration */:
44325 case 155 /* MethodSignature */:
44326 case 158 /* GetAccessor */:
44327 case 159 /* SetAccessor */:
44328 case 196 /* FunctionExpression */:
44329 case 197 /* ArrowFunction */:
44330 if (noImplicitAny && !declaration.name) {
44331 error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
44332 return;
44333 }
44334 diagnostic = noImplicitAny ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage;
44335 break;
44336 case 181 /* MappedType */:
44337 if (noImplicitAny) {
44338 error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
44339 }
44340 return;
44341 default:
44342 diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
44343 }
44344 errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
44345 }
44346 function reportErrorsFromWidening(declaration, type) {
44347 if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
44348 // Report implicit any error within type if possible, otherwise report error on declaration
44349 if (!reportWideningErrorsInType(type)) {
44350 reportImplicitAny(declaration, type);
44351 }
44352 }
44353 }
44354 function applyToParameterTypes(source, target, callback) {
44355 var sourceCount = getParameterCount(source);
44356 var targetCount = getParameterCount(target);
44357 var sourceRestType = getEffectiveRestType(source);
44358 var targetRestType = getEffectiveRestType(target);
44359 var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
44360 var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
44361 var sourceThisType = getThisTypeOfSignature(source);
44362 if (sourceThisType) {
44363 var targetThisType = getThisTypeOfSignature(target);
44364 if (targetThisType) {
44365 callback(sourceThisType, targetThisType);
44366 }
44367 }
44368 for (var i = 0; i < paramCount; i++) {
44369 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
44370 }
44371 if (targetRestType) {
44372 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
44373 }
44374 }
44375 function applyToReturnTypes(source, target, callback) {
44376 var sourceTypePredicate = getTypePredicateOfSignature(source);
44377 var targetTypePredicate = getTypePredicateOfSignature(target);
44378 if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind &&
44379 (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) {
44380 callback(sourceTypePredicate.type, targetTypePredicate.type);
44381 }
44382 else {
44383 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
44384 }
44385 }
44386 function createInferenceContext(typeParameters, signature, flags, compareTypes) {
44387 return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
44388 }
44389 function cloneInferenceContext(context, extraFlags) {
44390 if (extraFlags === void 0) { extraFlags = 0; }
44391 return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
44392 }
44393 function cloneInferredPartOfContext(context) {
44394 var inferences = ts.filter(context.inferences, hasInferenceCandidates);
44395 return inferences.length ?
44396 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
44397 undefined;
44398 }
44399 function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
44400 var context = {
44401 inferences: inferences,
44402 signature: signature,
44403 flags: flags,
44404 compareTypes: compareTypes,
44405 mapper: function (t) { return mapToInferredType(context, t, /*fix*/ true); },
44406 nonFixingMapper: function (t) { return mapToInferredType(context, t, /*fix*/ false); },
44407 };
44408 return context;
44409 }
44410 function mapToInferredType(context, t, fix) {
44411 var inferences = context.inferences;
44412 for (var i = 0; i < inferences.length; i++) {
44413 var inference = inferences[i];
44414 if (t === inference.typeParameter) {
44415 if (fix && !inference.isFixed) {
44416 inference.isFixed = true;
44417 inference.inferredType = undefined;
44418 }
44419 return getInferredType(context, i);
44420 }
44421 }
44422 return t;
44423 }
44424 function createInferenceInfo(typeParameter) {
44425 return {
44426 typeParameter: typeParameter,
44427 candidates: undefined,
44428 contraCandidates: undefined,
44429 inferredType: undefined,
44430 priority: undefined,
44431 topLevel: true,
44432 isFixed: false
44433 };
44434 }
44435 function cloneInferenceInfo(inference) {
44436 return {
44437 typeParameter: inference.typeParameter,
44438 candidates: inference.candidates && inference.candidates.slice(),
44439 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
44440 inferredType: inference.inferredType,
44441 priority: inference.priority,
44442 topLevel: inference.topLevel,
44443 isFixed: inference.isFixed
44444 };
44445 }
44446 function getMapperFromContext(context) {
44447 return context && context.mapper;
44448 }
44449 // Return true if the given type could possibly reference a type parameter for which
44450 // we perform type inference (i.e. a type parameter of a generic function). We cache
44451 // results for union and intersection types for performance reasons.
44452 function couldContainTypeVariables(type) {
44453 var objectFlags = ts.getObjectFlags(type);
44454 return !!(type.flags & 63176704 /* Instantiable */ ||
44455 objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) ||
44456 objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) ||
44457 objectFlags & 32 /* Mapped */ ||
44458 type.flags & 3145728 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type));
44459 }
44460 function couldUnionOrIntersectionContainTypeVariables(type) {
44461 if (type.couldContainTypeVariables === undefined) {
44462 type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables);
44463 }
44464 return type.couldContainTypeVariables;
44465 }
44466 function isTypeParameterAtTopLevel(type, typeParameter) {
44467 return type === typeParameter || !!(type.flags & 3145728 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); });
44468 }
44469 /** Create an object with properties named in the string literal type. Every property has type `any` */
44470 function createEmptyObjectTypeFromStringLiteral(type) {
44471 var members = ts.createSymbolTable();
44472 forEachType(type, function (t) {
44473 if (!(t.flags & 128 /* StringLiteral */)) {
44474 return;
44475 }
44476 var name = ts.escapeLeadingUnderscores(t.value);
44477 var literalProp = createSymbol(4 /* Property */, name);
44478 literalProp.type = anyType;
44479 if (t.symbol) {
44480 literalProp.declarations = t.symbol.declarations;
44481 literalProp.valueDeclaration = t.symbol.valueDeclaration;
44482 }
44483 members.set(name, literalProp);
44484 });
44485 var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
44486 return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
44487 }
44488 /**
44489 * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
44490 * an object type with the same set of properties as the source type, where the type of each
44491 * property is computed by inferring from the source property type to X for the type
44492 * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
44493 */
44494 function inferTypeForHomomorphicMappedType(source, target, constraint) {
44495 var key = source.id + "," + target.id + "," + constraint.id;
44496 if (reverseMappedCache.has(key)) {
44497 return reverseMappedCache.get(key);
44498 }
44499 reverseMappedCache.set(key, undefined);
44500 var type = createReverseMappedType(source, target, constraint);
44501 reverseMappedCache.set(key, type);
44502 return type;
44503 }
44504 function createReverseMappedType(source, target, constraint) {
44505 // If any property contains context sensitive functions that have been skipped, the source type
44506 // is incomplete and we can't infer a meaningful input type.
44507 if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || getPropertiesOfType(source).length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
44508 return undefined;
44509 }
44510 // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
44511 // applied to the element type(s).
44512 if (isArrayType(source)) {
44513 return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint), isReadonlyArrayType(source));
44514 }
44515 if (isTupleType(source)) {
44516 var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); });
44517 var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
44518 getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength;
44519 return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames);
44520 }
44521 // For all other object types we infer a new object type where the reverse mapping has been
44522 // applied to the type of each property.
44523 var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
44524 reversed.source = source;
44525 reversed.mappedType = target;
44526 reversed.constraintType = constraint;
44527 return reversed;
44528 }
44529 function getTypeOfReverseMappedSymbol(symbol) {
44530 return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
44531 }
44532 function inferReverseMappedType(sourceType, target, constraint) {
44533 var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
44534 var templateType = getTemplateTypeFromMappedType(target);
44535 var inference = createInferenceInfo(typeParameter);
44536 inferTypes([inference], sourceType, templateType);
44537 return getTypeFromInference(inference);
44538 }
44539 function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
44540 var properties, _i, properties_3, targetProp, sourceProp, targetType, sourceType;
44541 return __generator(this, function (_a) {
44542 switch (_a.label) {
44543 case 0:
44544 properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
44545 _i = 0, properties_3 = properties;
44546 _a.label = 1;
44547 case 1:
44548 if (!(_i < properties_3.length)) return [3 /*break*/, 6];
44549 targetProp = properties_3[_i];
44550 if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5];
44551 sourceProp = getPropertyOfType(source, targetProp.escapedName);
44552 if (!!sourceProp) return [3 /*break*/, 3];
44553 return [4 /*yield*/, targetProp];
44554 case 2:
44555 _a.sent();
44556 return [3 /*break*/, 5];
44557 case 3:
44558 if (!matchDiscriminantProperties) return [3 /*break*/, 5];
44559 targetType = getTypeOfSymbol(targetProp);
44560 if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
44561 sourceType = getTypeOfSymbol(sourceProp);
44562 if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
44563 return [4 /*yield*/, targetProp];
44564 case 4:
44565 _a.sent();
44566 _a.label = 5;
44567 case 5:
44568 _i++;
44569 return [3 /*break*/, 1];
44570 case 6: return [2 /*return*/];
44571 }
44572 });
44573 }
44574 function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
44575 return getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next().value;
44576 }
44577 function tupleTypesDefinitelyUnrelated(source, target) {
44578 return target.target.minLength > source.target.minLength ||
44579 !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source));
44580 }
44581 function typesDefinitelyUnrelated(source, target) {
44582 // Two tuple types with incompatible arities are definitely unrelated.
44583 // Two object types that each have a property that is unmatched in the other are definitely unrelated.
44584 return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) ||
44585 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
44586 !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
44587 }
44588 function getTypeFromInference(inference) {
44589 return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
44590 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
44591 emptyObjectType;
44592 }
44593 function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
44594 if (priority === void 0) { priority = 0; }
44595 if (contravariant === void 0) { contravariant = false; }
44596 var symbolStack;
44597 var visited;
44598 var bivariant = false;
44599 var propagationType;
44600 var allowComplexConstraintInference = true;
44601 inferFromTypes(originalSource, originalTarget);
44602 function inferFromTypes(source, target) {
44603 if (!couldContainTypeVariables(target)) {
44604 return;
44605 }
44606 if (source === wildcardType) {
44607 // We are inferring from an 'any' type. We want to infer this type for every type parameter
44608 // referenced in the target type, so we record it as the propagation type and infer from the
44609 // target to itself. Then, as we find candidates we substitute the propagation type.
44610 var savePropagationType = propagationType;
44611 propagationType = source;
44612 inferFromTypes(target, target);
44613 propagationType = savePropagationType;
44614 return;
44615 }
44616 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
44617 // Source and target are types originating in the same generic type alias declaration.
44618 // Simply infer from source type arguments to target type arguments.
44619 var sourceTypes = source.aliasTypeArguments;
44620 var targetTypes = target.aliasTypeArguments;
44621 for (var i = 0; i < sourceTypes.length; i++) {
44622 inferFromTypes(sourceTypes[i], targetTypes[i]);
44623 }
44624 return;
44625 }
44626 if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ && !(source.flags & 1024 /* EnumLiteral */ && target.flags & 1024 /* EnumLiteral */) ||
44627 source.flags & 2097152 /* Intersection */ && target.flags & 2097152 /* Intersection */) {
44628 // Source and target are both unions or both intersections. If source and target
44629 // are the same type, just relate each constituent type to itself.
44630 if (source === target) {
44631 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
44632 var t = _a[_i];
44633 inferFromTypes(t, t);
44634 }
44635 return;
44636 }
44637 // Find each source constituent type that has an identically matching target constituent
44638 // type, and for each such type infer from the type to itself. When inferring from a
44639 // type to itself we effectively find all type parameter occurrences within that type
44640 // and infer themselves as their type arguments. We have special handling for numeric
44641 // and string literals because the number and string types are not represented as unions
44642 // of all their possible values.
44643 var matchingTypes = void 0;
44644 for (var _b = 0, _c = source.types; _b < _c.length; _b++) {
44645 var t = _c[_b];
44646 if (typeIdenticalToSomeType(t, target.types)) {
44647 (matchingTypes || (matchingTypes = [])).push(t);
44648 inferFromTypes(t, t);
44649 }
44650 else if (t.flags & (256 /* NumberLiteral */ | 128 /* StringLiteral */)) {
44651 var b = getBaseTypeOfLiteralType(t);
44652 if (typeIdenticalToSomeType(b, target.types)) {
44653 (matchingTypes || (matchingTypes = [])).push(t, b);
44654 }
44655 }
44656 }
44657 // Next, to improve the quality of inferences, reduce the source and target types by
44658 // removing the identically matched constituents. For example, when inferring from
44659 // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'.
44660 if (matchingTypes) {
44661 source = removeTypesFromUnionOrIntersection(source, matchingTypes);
44662 target = removeTypesFromUnionOrIntersection(target, matchingTypes);
44663 }
44664 }
44665 if (target.flags & 8650752 /* TypeVariable */) {
44666 // If target is a type parameter, make an inference, unless the source type contains
44667 // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
44668 // Because the anyFunctionType is internal, it should not be exposed to the user by adding
44669 // it as an inference candidate. Hopefully, a better candidate will come along that does
44670 // not contain anyFunctionType when we come back to this argument for its second round
44671 // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
44672 // when constructing types from type parameters that had no inference candidates).
44673 if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
44674 return;
44675 }
44676 var inference = getInferenceInfoForType(target);
44677 if (inference) {
44678 if (!inference.isFixed) {
44679 if (inference.priority === undefined || priority < inference.priority) {
44680 inference.candidates = undefined;
44681 inference.contraCandidates = undefined;
44682 inference.topLevel = true;
44683 inference.priority = priority;
44684 }
44685 if (priority === inference.priority) {
44686 var candidate = propagationType || source;
44687 // We make contravariant inferences only if we are in a pure contravariant position,
44688 // i.e. only if we have not descended into a bivariant position.
44689 if (contravariant && !bivariant) {
44690 if (!ts.contains(inference.contraCandidates, candidate)) {
44691 inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
44692 inference.inferredType = undefined;
44693 }
44694 }
44695 else if (!ts.contains(inference.candidates, candidate)) {
44696 inference.candidates = ts.append(inference.candidates, candidate);
44697 inference.inferredType = undefined;
44698 }
44699 }
44700 if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
44701 inference.topLevel = false;
44702 inference.inferredType = undefined;
44703 }
44704 }
44705 return;
44706 }
44707 else {
44708 // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
44709 var simplified = getSimplifiedType(target);
44710 if (simplified !== target) {
44711 inferFromTypesOnce(source, simplified);
44712 }
44713 else if (target.flags & 8388608 /* IndexedAccess */) {
44714 var indexType = getSimplifiedType(target.indexType);
44715 // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
44716 // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
44717 if (indexType.flags & 63176704 /* Instantiable */) {
44718 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType), indexType);
44719 if (simplified_1 && simplified_1 !== target) {
44720 inferFromTypesOnce(source, simplified_1);
44721 }
44722 }
44723 }
44724 }
44725 }
44726 else if (target.flags & 33554432 /* Substitution */) {
44727 inferFromTypes(source, target.typeVariable);
44728 }
44729 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
44730 // If source and target are references to the same generic type, infer from type arguments
44731 var sourceTypes = source.typeArguments || ts.emptyArray;
44732 var targetTypes = target.typeArguments || ts.emptyArray;
44733 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
44734 var variances = getVariances(source.target);
44735 for (var i = 0; i < count; i++) {
44736 if (i < variances.length && variances[i] === 2 /* Contravariant */) {
44737 inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
44738 }
44739 else {
44740 inferFromTypes(sourceTypes[i], targetTypes[i]);
44741 }
44742 }
44743 }
44744 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
44745 contravariant = !contravariant;
44746 inferFromTypes(source.type, target.type);
44747 contravariant = !contravariant;
44748 }
44749 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
44750 var empty = createEmptyObjectTypeFromStringLiteral(source);
44751 contravariant = !contravariant;
44752 var savePriority = priority;
44753 priority |= 16 /* LiteralKeyof */;
44754 inferFromTypes(empty, target.type);
44755 priority = savePriority;
44756 contravariant = !contravariant;
44757 }
44758 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
44759 inferFromTypes(source.objectType, target.objectType);
44760 inferFromTypes(source.indexType, target.indexType);
44761 }
44762 else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
44763 inferFromTypes(source.checkType, target.checkType);
44764 inferFromTypes(source.extendsType, target.extendsType);
44765 inferFromTypes(source.trueType, target.trueType);
44766 inferFromTypes(source.falseType, target.falseType);
44767 }
44768 else if (target.flags & 16777216 /* Conditional */ && !contravariant) {
44769 inferFromTypes(source, target.trueType);
44770 inferFromTypes(source, target.falseType);
44771 }
44772 else if (target.flags & 3145728 /* UnionOrIntersection */) {
44773 // We infer from types that are not naked type variables first so that inferences we
44774 // make from nested naked type variables and given slightly higher priority by virtue
44775 // of being first in the candidates array.
44776 var typeVariableCount = 0;
44777 for (var _d = 0, _e = target.types; _d < _e.length; _d++) {
44778 var t = _e[_d];
44779 if (getInferenceInfoForType(t)) {
44780 typeVariableCount++;
44781 }
44782 else {
44783 inferFromTypes(source, t);
44784 }
44785 }
44786 // Inferences directly to naked type variables are given lower priority as they are
44787 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
44788 // we want to infer string for T, not Promise<string> | string. For intersection types
44789 // we only infer to single naked type variables.
44790 if (target.flags & 1048576 /* Union */ ? typeVariableCount !== 0 : typeVariableCount === 1) {
44791 var savePriority = priority;
44792 priority |= 1 /* NakedTypeVariable */;
44793 for (var _f = 0, _g = target.types; _f < _g.length; _f++) {
44794 var t = _g[_f];
44795 if (getInferenceInfoForType(t)) {
44796 inferFromTypes(source, t);
44797 }
44798 }
44799 priority = savePriority;
44800 }
44801 }
44802 else if (source.flags & 1048576 /* Union */) {
44803 // Source is a union or intersection type, infer from each constituent type
44804 var sourceTypes = source.types;
44805 for (var _h = 0, sourceTypes_3 = sourceTypes; _h < sourceTypes_3.length; _h++) {
44806 var sourceType = sourceTypes_3[_h];
44807 inferFromTypes(sourceType, target);
44808 }
44809 }
44810 else {
44811 if (!(priority & 32 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) {
44812 var apparentSource = getApparentType(source);
44813 // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
44814 // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
44815 // with the simplified source.
44816 if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
44817 // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
44818 // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
44819 // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
44820 // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
44821 // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
44822 // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
44823 // remove this `allowComplexConstraintInference` flag.
44824 allowComplexConstraintInference = false;
44825 return inferFromTypes(apparentSource, target);
44826 }
44827 source = apparentSource;
44828 }
44829 if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
44830 var key = source.id + "," + target.id;
44831 if (visited && visited.get(key)) {
44832 return;
44833 }
44834 (visited || (visited = ts.createMap())).set(key, true);
44835 // If we are already processing another target type with the same associated symbol (such as
44836 // an instantiation of the same generic type), we do not explore this target as it would yield
44837 // no further inferences. We exclude the static side of classes from this check since it shares
44838 // its symbol with the instance side which would lead to false positives.
44839 var isNonConstructorObject = target.flags & 524288 /* Object */ &&
44840 !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */);
44841 var symbol = isNonConstructorObject ? target.symbol : undefined;
44842 if (symbol) {
44843 if (ts.contains(symbolStack, symbol)) {
44844 return;
44845 }
44846 (symbolStack || (symbolStack = [])).push(symbol);
44847 inferFromObjectTypes(source, target);
44848 symbolStack.pop();
44849 }
44850 else {
44851 inferFromObjectTypes(source, target);
44852 }
44853 }
44854 }
44855 function inferFromTypesOnce(source, target) {
44856 var key = source.id + "," + target.id;
44857 if (!visited || !visited.get(key)) {
44858 (visited || (visited = ts.createMap())).set(key, true);
44859 inferFromTypes(source, target);
44860 }
44861 }
44862 }
44863 function inferFromContravariantTypes(source, target) {
44864 if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) {
44865 contravariant = !contravariant;
44866 inferFromTypes(source, target);
44867 contravariant = !contravariant;
44868 }
44869 else {
44870 inferFromTypes(source, target);
44871 }
44872 }
44873 function getInferenceInfoForType(type) {
44874 if (type.flags & 8650752 /* TypeVariable */) {
44875 for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
44876 var inference = inferences_1[_i];
44877 if (type === inference.typeParameter) {
44878 return inference;
44879 }
44880 }
44881 }
44882 return undefined;
44883 }
44884 function inferToMappedType(source, target, constraintType) {
44885 if (constraintType.flags & 1048576 /* Union */) {
44886 var result = false;
44887 for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
44888 var type = _a[_i];
44889 result = inferToMappedType(source, target, type) || result;
44890 }
44891 return result;
44892 }
44893 if (constraintType.flags & 4194304 /* Index */) {
44894 // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
44895 // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
44896 // type and then make a secondary inference from that type to T. We make a secondary inference
44897 // such that direct inferences to T get priority over inferences to Partial<T>, for example.
44898 var inference = getInferenceInfoForType(constraintType.type);
44899 if (inference && !inference.isFixed) {
44900 var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
44901 if (inferredType) {
44902 var savePriority = priority;
44903 priority |= 2 /* HomomorphicMappedType */;
44904 inferFromTypes(inferredType, inference.typeParameter);
44905 priority = savePriority;
44906 }
44907 }
44908 return true;
44909 }
44910 if (constraintType.flags & 262144 /* TypeParameter */) {
44911 // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
44912 // parameter. First infer from 'keyof S' to K.
44913 var savePriority = priority;
44914 priority |= 4 /* MappedTypeConstraint */;
44915 inferFromTypes(getIndexType(source), constraintType);
44916 priority = savePriority;
44917 // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
44918 // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
44919 // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
44920 // Pick<T, K>.
44921 var extendedConstraint = getConstraintOfType(constraintType);
44922 if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
44923 return true;
44924 }
44925 // If no inferences can be made to K's constraint, infer from a union of the property types
44926 // in the source to the template type X.
44927 var valueTypes = ts.compact([
44928 getIndexTypeOfType(source, 0 /* String */),
44929 getIndexTypeOfType(source, 1 /* Number */)
44930 ].concat(ts.map(getPropertiesOfType(source), getTypeOfSymbol)));
44931 inferFromTypes(getUnionType(valueTypes), getTemplateTypeFromMappedType(target));
44932 return true;
44933 }
44934 return false;
44935 }
44936 function inferFromObjectTypes(source, target) {
44937 if (isGenericMappedType(source) && isGenericMappedType(target)) {
44938 // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
44939 // from S to T and from X to Y.
44940 inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
44941 inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
44942 }
44943 if (ts.getObjectFlags(target) & 32 /* Mapped */) {
44944 var constraintType = getConstraintTypeFromMappedType(target);
44945 if (inferToMappedType(source, target, constraintType)) {
44946 return;
44947 }
44948 }
44949 // Infer from the members of source and target only if the two types are possibly related
44950 if (!typesDefinitelyUnrelated(source, target)) {
44951 inferFromProperties(source, target);
44952 inferFromSignatures(source, target, 0 /* Call */);
44953 inferFromSignatures(source, target, 1 /* Construct */);
44954 inferFromIndexTypes(source, target);
44955 }
44956 }
44957 function inferFromProperties(source, target) {
44958 if (isArrayType(source) || isTupleType(source)) {
44959 if (isTupleType(target)) {
44960 var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
44961 var targetLength = getLengthOfTupleType(target);
44962 var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
44963 var targetRestType = getRestTypeOfTupleType(target);
44964 var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
44965 for (var i = 0; i < fixedLength; i++) {
44966 inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]);
44967 }
44968 if (targetRestType) {
44969 var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : [];
44970 if (sourceRestType) {
44971 types.push(sourceRestType);
44972 }
44973 if (types.length) {
44974 inferFromTypes(getUnionType(types), targetRestType);
44975 }
44976 }
44977 return;
44978 }
44979 if (isArrayType(target)) {
44980 inferFromIndexTypes(source, target);
44981 return;
44982 }
44983 }
44984 var properties = getPropertiesOfObjectType(target);
44985 for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) {
44986 var targetProp = properties_4[_i];
44987 var sourceProp = getPropertyOfType(source, targetProp.escapedName);
44988 if (sourceProp) {
44989 inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
44990 }
44991 }
44992 }
44993 function inferFromSignatures(source, target, kind) {
44994 var sourceSignatures = getSignaturesOfType(source, kind);
44995 var targetSignatures = getSignaturesOfType(target, kind);
44996 var sourceLen = sourceSignatures.length;
44997 var targetLen = targetSignatures.length;
44998 var len = sourceLen < targetLen ? sourceLen : targetLen;
44999 var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */);
45000 for (var i = 0; i < len; i++) {
45001 inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
45002 }
45003 }
45004 function inferFromSignature(source, target, skipParameters) {
45005 if (!skipParameters) {
45006 var saveBivariant = bivariant;
45007 var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
45008 // Once we descend into a bivariant signature we remain bivariant for all nested inferences
45009 bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */;
45010 applyToParameterTypes(source, target, inferFromContravariantTypes);
45011 bivariant = saveBivariant;
45012 }
45013 applyToReturnTypes(source, target, inferFromTypes);
45014 }
45015 function inferFromIndexTypes(source, target) {
45016 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
45017 if (targetStringIndexType) {
45018 var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
45019 getImplicitIndexTypeOfType(source, 0 /* String */);
45020 if (sourceIndexType) {
45021 inferFromTypes(sourceIndexType, targetStringIndexType);
45022 }
45023 }
45024 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
45025 if (targetNumberIndexType) {
45026 var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
45027 getIndexTypeOfType(source, 0 /* String */) ||
45028 getImplicitIndexTypeOfType(source, 1 /* Number */);
45029 if (sourceIndexType) {
45030 inferFromTypes(sourceIndexType, targetNumberIndexType);
45031 }
45032 }
45033 }
45034 }
45035 function typeIdenticalToSomeType(type, types) {
45036 for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
45037 var t = types_11[_i];
45038 if (isTypeIdenticalTo(t, type)) {
45039 return true;
45040 }
45041 }
45042 return false;
45043 }
45044 /**
45045 * Return a new union or intersection type computed by removing a given set of types
45046 * from a given union or intersection type.
45047 */
45048 function removeTypesFromUnionOrIntersection(type, typesToRemove) {
45049 var reducedTypes = [];
45050 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
45051 var t = _a[_i];
45052 if (!typeIdenticalToSomeType(t, typesToRemove)) {
45053 reducedTypes.push(t);
45054 }
45055 }
45056 return type.flags & 1048576 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes);
45057 }
45058 function hasPrimitiveConstraint(type) {
45059 var constraint = getConstraintOfTypeParameter(type);
45060 return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */);
45061 }
45062 function isObjectLiteralType(type) {
45063 return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
45064 }
45065 function widenObjectLiteralCandidates(candidates) {
45066 if (candidates.length > 1) {
45067 var objectLiterals = ts.filter(candidates, isObjectLiteralType);
45068 if (objectLiterals.length) {
45069 var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2 /* Subtype */));
45070 return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]);
45071 }
45072 }
45073 return candidates;
45074 }
45075 function getContravariantInference(inference) {
45076 return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
45077 }
45078 function getCovariantInference(inference, signature) {
45079 // Extract all object literal types and replace them with a single widened and normalized type.
45080 var candidates = widenObjectLiteralCandidates(inference.candidates);
45081 // We widen inferred literal types if
45082 // all inferences were made to top-level occurrences of the type parameter, and
45083 // the type parameter has no constraint or its constraint includes no primitive or literal types, and
45084 // the type parameter was fixed during inference or does not occur at top-level in the return type.
45085 var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
45086 var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
45087 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
45088 var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
45089 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
45090 candidates;
45091 // If all inferences were made from a position that implies a combined result, infer a union type.
45092 // Otherwise, infer a common supertype.
45093 var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ?
45094 getUnionType(baseCandidates, 2 /* Subtype */) :
45095 getCommonSupertype(baseCandidates);
45096 return getWidenedType(unwidenedType);
45097 }
45098 function getInferredType(context, index) {
45099 var inference = context.inferences[index];
45100 var inferredType = inference.inferredType;
45101 if (!inferredType) {
45102 var signature = context.signature;
45103 if (signature) {
45104 var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
45105 if (inference.contraCandidates) {
45106 var inferredContravariantType = getContravariantInference(inference);
45107 // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
45108 // unless the co-variant inference is a subtype and not 'never'.
45109 inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
45110 isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
45111 inferredCovariantType : inferredContravariantType;
45112 }
45113 else if (inferredCovariantType) {
45114 inferredType = inferredCovariantType;
45115 }
45116 else if (context.flags & 1 /* NoDefault */) {
45117 // We use silentNeverType as the wildcard that signals no inferences.
45118 inferredType = silentNeverType;
45119 }
45120 else {
45121 // Infer either the default or the empty object type when no inferences were
45122 // made. It is important to remember that in this case, inference still
45123 // succeeds, meaning there is no error for not having inference candidates. An
45124 // inference error only occurs when there are *conflicting* candidates, i.e.
45125 // candidates with no common supertype.
45126 var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
45127 if (defaultType) {
45128 // Instantiate the default type. Any forward reference to a type
45129 // parameter should be instantiated to the empty object type.
45130 inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
45131 }
45132 else {
45133 inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
45134 }
45135 }
45136 }
45137 else {
45138 inferredType = getTypeFromInference(inference);
45139 }
45140 inference.inferredType = inferredType;
45141 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
45142 if (constraint) {
45143 var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
45144 if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
45145 inference.inferredType = inferredType = instantiatedConstraint;
45146 }
45147 }
45148 }
45149 return inferredType;
45150 }
45151 function getDefaultTypeArgumentType(isInJavaScriptFile) {
45152 return isInJavaScriptFile ? anyType : emptyObjectType;
45153 }
45154 function getInferredTypes(context) {
45155 var result = [];
45156 for (var i = 0; i < context.inferences.length; i++) {
45157 result.push(getInferredType(context, i));
45158 }
45159 return result;
45160 }
45161 // EXPRESSION TYPE CHECKING
45162 function getCannotFindNameDiagnosticForName(name) {
45163 switch (name) {
45164 case "document":
45165 case "console":
45166 return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
45167 case "$":
45168 return compilerOptions.types
45169 ? ts.Diagnostics.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
45170 : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
45171 case "describe":
45172 case "suite":
45173 case "it":
45174 case "test":
45175 return compilerOptions.types
45176 ? ts.Diagnostics.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
45177 : ts.Diagnostics.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;
45178 case "process":
45179 case "require":
45180 case "Buffer":
45181 case "module":
45182 return compilerOptions.types
45183 ? ts.Diagnostics.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
45184 : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
45185 case "Map":
45186 case "Set":
45187 case "Promise":
45188 case "Symbol":
45189 case "WeakMap":
45190 case "WeakSet":
45191 case "Iterator":
45192 case "AsyncIterator":
45193 return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later;
45194 default: return ts.Diagnostics.Cannot_find_name_0;
45195 }
45196 }
45197 function getResolvedSymbol(node) {
45198 var links = getNodeLinks(node);
45199 if (!links.resolvedSymbol) {
45200 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
45201 resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node),
45202 /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
45203 }
45204 return links.resolvedSymbol;
45205 }
45206 function isInTypeQuery(node) {
45207 // TypeScript 1.0 spec (April 2014): 3.6.3
45208 // A type query consists of the keyword typeof followed by an expression.
45209 // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
45210 return !!ts.findAncestor(node, function (n) { return n.kind === 167 /* TypeQuery */ ? true : n.kind === 72 /* Identifier */ || n.kind === 148 /* QualifiedName */ ? false : "quit"; });
45211 }
45212 // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
45213 // separated by dots). The key consists of the id of the symbol referenced by the
45214 // leftmost identifier followed by zero or more property names separated by dots.
45215 // The result is undefined if the reference isn't a dotted name. We prefix nodes
45216 // occurring in an apparent type position with '@' because the control flow type
45217 // of such nodes may be based on the apparent type instead of the declared type.
45218 function getFlowCacheKey(node) {
45219 switch (node.kind) {
45220 case 72 /* Identifier */:
45221 var symbol = getResolvedSymbol(node);
45222 return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
45223 case 100 /* ThisKeyword */:
45224 return "0";
45225 case 213 /* NonNullExpression */:
45226 case 195 /* ParenthesizedExpression */:
45227 return getFlowCacheKey(node.expression);
45228 case 189 /* PropertyAccessExpression */:
45229 case 190 /* ElementAccessExpression */:
45230 var propName = getAccessedPropertyName(node);
45231 if (propName !== undefined) {
45232 var key = getFlowCacheKey(node.expression);
45233 return key && key + "." + propName;
45234 }
45235 }
45236 return undefined;
45237 }
45238 function isMatchingReference(source, target) {
45239 switch (target.kind) {
45240 case 195 /* ParenthesizedExpression */:
45241 case 213 /* NonNullExpression */:
45242 return isMatchingReference(source, target.expression);
45243 }
45244 switch (source.kind) {
45245 case 72 /* Identifier */:
45246 return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
45247 (target.kind === 237 /* VariableDeclaration */ || target.kind === 186 /* BindingElement */) &&
45248 getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
45249 case 100 /* ThisKeyword */:
45250 return target.kind === 100 /* ThisKeyword */;
45251 case 98 /* SuperKeyword */:
45252 return target.kind === 98 /* SuperKeyword */;
45253 case 213 /* NonNullExpression */:
45254 case 195 /* ParenthesizedExpression */:
45255 return isMatchingReference(source.expression, target);
45256 case 189 /* PropertyAccessExpression */:
45257 case 190 /* ElementAccessExpression */:
45258 return ts.isAccessExpression(target) &&
45259 getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
45260 isMatchingReference(source.expression, target.expression);
45261 }
45262 return false;
45263 }
45264 function getAccessedPropertyName(access) {
45265 return access.kind === 189 /* PropertyAccessExpression */ ? access.name.escapedText :
45266 ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
45267 undefined;
45268 }
45269 function containsMatchingReference(source, target) {
45270 while (ts.isAccessExpression(source)) {
45271 source = source.expression;
45272 if (isMatchingReference(source, target)) {
45273 return true;
45274 }
45275 }
45276 return false;
45277 }
45278 // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared
45279 // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property
45280 // a possible discriminant if its type differs in the constituents of containing union type, and if every
45281 // choice is a unit type or a union of unit types.
45282 function containsMatchingReferenceDiscriminant(source, target) {
45283 var name;
45284 return ts.isAccessExpression(target) &&
45285 containsMatchingReference(source, target.expression) &&
45286 (name = getAccessedPropertyName(target)) !== undefined &&
45287 isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), name);
45288 }
45289 function getDeclaredTypeOfReference(expr) {
45290 if (expr.kind === 72 /* Identifier */) {
45291 return getTypeOfSymbol(getResolvedSymbol(expr));
45292 }
45293 if (ts.isAccessExpression(expr)) {
45294 var type = getDeclaredTypeOfReference(expr.expression);
45295 if (type) {
45296 var propName = getAccessedPropertyName(expr);
45297 return propName !== undefined ? getTypeOfPropertyOfType(type, propName) : undefined;
45298 }
45299 }
45300 return undefined;
45301 }
45302 function isDiscriminantType(type) {
45303 return !!(type.flags & 1048576 /* Union */ &&
45304 (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */) || !isGenericIndexType(type)));
45305 }
45306 function isDiscriminantProperty(type, name) {
45307 if (type && type.flags & 1048576 /* Union */) {
45308 var prop = getUnionOrIntersectionProperty(type, name);
45309 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
45310 if (prop.isDiscriminantProperty === undefined) {
45311 prop.isDiscriminantProperty =
45312 (prop.checkFlags & 96 /* Discriminant */) === 96 /* Discriminant */ &&
45313 isDiscriminantType(getTypeOfSymbol(prop));
45314 }
45315 return !!prop.isDiscriminantProperty;
45316 }
45317 }
45318 return false;
45319 }
45320 function isSyntheticThisPropertyAccess(expr) {
45321 return ts.isAccessExpression(expr) && expr.expression.kind === 100 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */);
45322 }
45323 function findDiscriminantProperties(sourceProperties, target) {
45324 var result;
45325 for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
45326 var sourceProperty = sourceProperties_2[_i];
45327 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
45328 if (result) {
45329 result.push(sourceProperty);
45330 continue;
45331 }
45332 result = [sourceProperty];
45333 }
45334 }
45335 return result;
45336 }
45337 function isOrContainsMatchingReference(source, target) {
45338 return isMatchingReference(source, target) || containsMatchingReference(source, target);
45339 }
45340 function hasMatchingArgument(callExpression, reference) {
45341 if (callExpression.arguments) {
45342 for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
45343 var argument = _a[_i];
45344 if (isOrContainsMatchingReference(reference, argument)) {
45345 return true;
45346 }
45347 }
45348 }
45349 if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ &&
45350 isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
45351 return true;
45352 }
45353 return false;
45354 }
45355 function getFlowNodeId(flow) {
45356 if (!flow.id) {
45357 flow.id = nextFlowId;
45358 nextFlowId++;
45359 }
45360 return flow.id;
45361 }
45362 function typeMaybeAssignableTo(source, target) {
45363 if (!(source.flags & 1048576 /* Union */)) {
45364 return isTypeAssignableTo(source, target);
45365 }
45366 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
45367 var t = _a[_i];
45368 if (isTypeAssignableTo(t, target)) {
45369 return true;
45370 }
45371 }
45372 return false;
45373 }
45374 // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
45375 // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
45376 // we remove type string.
45377 function getAssignmentReducedType(declaredType, assignedType) {
45378 if (declaredType !== assignedType) {
45379 if (assignedType.flags & 131072 /* Never */) {
45380 return assignedType;
45381 }
45382 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
45383 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
45384 reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
45385 }
45386 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
45387 // For now, when that happens, we give up and don't narrow at all. (This also
45388 // means we'll never narrow for erroneous assignments where the assigned type
45389 // is not assignable to the declared type.)
45390 if (isTypeAssignableTo(assignedType, reducedType)) {
45391 return reducedType;
45392 }
45393 }
45394 return declaredType;
45395 }
45396 function getTypeFactsOfTypes(types) {
45397 var result = 0 /* None */;
45398 for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
45399 var t = types_12[_i];
45400 result |= getTypeFacts(t);
45401 }
45402 return result;
45403 }
45404 function isFunctionObjectType(type) {
45405 // We do a quick check for a "bind" property before performing the more expensive subtype
45406 // check. This gives us a quicker out in the common case where an object type is not a function.
45407 var resolved = resolveStructuredTypeMembers(type);
45408 return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
45409 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
45410 }
45411 function getTypeFacts(type) {
45412 var flags = type.flags;
45413 if (flags & 4 /* String */) {
45414 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
45415 }
45416 if (flags & 128 /* StringLiteral */) {
45417 var isEmpty = type.value === "";
45418 return strictNullChecks ?
45419 isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
45420 isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
45421 }
45422 if (flags & (8 /* Number */ | 32 /* Enum */)) {
45423 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
45424 }
45425 if (flags & 256 /* NumberLiteral */) {
45426 var isZero = type.value === 0;
45427 return strictNullChecks ?
45428 isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
45429 isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
45430 }
45431 if (flags & 64 /* BigInt */) {
45432 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
45433 }
45434 if (flags & 2048 /* BigIntLiteral */) {
45435 var isZero = isZeroBigInt(type);
45436 return strictNullChecks ?
45437 isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
45438 isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
45439 }
45440 if (flags & 16 /* Boolean */) {
45441 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
45442 }
45443 if (flags & 528 /* BooleanLike */) {
45444 return strictNullChecks ?
45445 (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
45446 (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
45447 }
45448 if (flags & 524288 /* Object */) {
45449 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
45450 strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
45451 isFunctionObjectType(type) ?
45452 strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
45453 strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
45454 }
45455 if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
45456 return 9830144 /* UndefinedFacts */;
45457 }
45458 if (flags & 65536 /* Null */) {
45459 return 9363232 /* NullFacts */;
45460 }
45461 if (flags & 12288 /* ESSymbolLike */) {
45462 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
45463 }
45464 if (flags & 67108864 /* NonPrimitive */) {
45465 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
45466 }
45467 if (flags & 63176704 /* Instantiable */) {
45468 return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType);
45469 }
45470 if (flags & 3145728 /* UnionOrIntersection */) {
45471 return getTypeFactsOfTypes(type.types);
45472 }
45473 return 16777215 /* All */;
45474 }
45475 function getTypeWithFacts(type, include) {
45476 return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
45477 }
45478 function getTypeWithDefault(type, defaultExpression) {
45479 if (defaultExpression) {
45480 var defaultType = getTypeOfExpression(defaultExpression);
45481 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
45482 }
45483 return type;
45484 }
45485 function getTypeOfDestructuredProperty(type, name) {
45486 var nameType = getLiteralTypeFromPropertyName(name);
45487 if (!isTypeUsableAsPropertyName(nameType))
45488 return errorType;
45489 var text = getPropertyNameFromType(nameType);
45490 return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
45491 isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) ||
45492 getIndexTypeOfType(type, 0 /* String */) ||
45493 errorType;
45494 }
45495 function getTypeOfDestructuredArrayElement(type, index) {
45496 return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
45497 checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) ||
45498 errorType;
45499 }
45500 function getTypeOfDestructuredSpreadExpression(type) {
45501 return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType);
45502 }
45503 function getAssignedTypeOfBinaryExpression(node) {
45504 var isDestructuringDefaultAssignment = node.parent.kind === 187 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
45505 node.parent.kind === 275 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
45506 return isDestructuringDefaultAssignment ?
45507 getTypeWithDefault(getAssignedType(node), node.right) :
45508 getTypeOfExpression(node.right);
45509 }
45510 function isDestructuringAssignmentTarget(parent) {
45511 return parent.parent.kind === 204 /* BinaryExpression */ && parent.parent.left === parent ||
45512 parent.parent.kind === 227 /* ForOfStatement */ && parent.parent.initializer === parent;
45513 }
45514 function getAssignedTypeOfArrayLiteralElement(node, element) {
45515 return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
45516 }
45517 function getAssignedTypeOfSpreadExpression(node) {
45518 return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
45519 }
45520 function getAssignedTypeOfPropertyAssignment(node) {
45521 return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
45522 }
45523 function getAssignedTypeOfShorthandPropertyAssignment(node) {
45524 return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
45525 }
45526 function getAssignedType(node) {
45527 var parent = node.parent;
45528 switch (parent.kind) {
45529 case 226 /* ForInStatement */:
45530 return stringType;
45531 case 227 /* ForOfStatement */:
45532 return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType;
45533 case 204 /* BinaryExpression */:
45534 return getAssignedTypeOfBinaryExpression(parent);
45535 case 198 /* DeleteExpression */:
45536 return undefinedType;
45537 case 187 /* ArrayLiteralExpression */:
45538 return getAssignedTypeOfArrayLiteralElement(parent, node);
45539 case 208 /* SpreadElement */:
45540 return getAssignedTypeOfSpreadExpression(parent);
45541 case 275 /* PropertyAssignment */:
45542 return getAssignedTypeOfPropertyAssignment(parent);
45543 case 276 /* ShorthandPropertyAssignment */:
45544 return getAssignedTypeOfShorthandPropertyAssignment(parent);
45545 }
45546 return errorType;
45547 }
45548 function getInitialTypeOfBindingElement(node) {
45549 var pattern = node.parent;
45550 var parentType = getInitialType(pattern.parent);
45551 var type = pattern.kind === 184 /* ObjectBindingPattern */ ?
45552 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
45553 !node.dotDotDotToken ?
45554 getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
45555 getTypeOfDestructuredSpreadExpression(parentType);
45556 return getTypeWithDefault(type, node.initializer);
45557 }
45558 function getTypeOfInitializer(node) {
45559 // Return the cached type if one is available. If the type of the variable was inferred
45560 // from its initializer, we'll already have cached the type. Otherwise we compute it now
45561 // without caching such that transient types are reflected.
45562 var links = getNodeLinks(node);
45563 return links.resolvedType || getTypeOfExpression(node);
45564 }
45565 function getInitialTypeOfVariableDeclaration(node) {
45566 if (node.initializer) {
45567 return getTypeOfInitializer(node.initializer);
45568 }
45569 if (node.parent.parent.kind === 226 /* ForInStatement */) {
45570 return stringType;
45571 }
45572 if (node.parent.parent.kind === 227 /* ForOfStatement */) {
45573 return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType;
45574 }
45575 return errorType;
45576 }
45577 function getInitialType(node) {
45578 return node.kind === 237 /* VariableDeclaration */ ?
45579 getInitialTypeOfVariableDeclaration(node) :
45580 getInitialTypeOfBindingElement(node);
45581 }
45582 function getInitialOrAssignedType(node, reference) {
45583 return getConstraintForLocation(node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */ ?
45584 getInitialType(node) :
45585 getAssignedType(node), reference);
45586 }
45587 function isEmptyArrayAssignment(node) {
45588 return node.kind === 237 /* VariableDeclaration */ && node.initializer &&
45589 isEmptyArrayLiteral(node.initializer) ||
45590 node.kind !== 186 /* BindingElement */ && node.parent.kind === 204 /* BinaryExpression */ &&
45591 isEmptyArrayLiteral(node.parent.right);
45592 }
45593 function getReferenceCandidate(node) {
45594 switch (node.kind) {
45595 case 195 /* ParenthesizedExpression */:
45596 return getReferenceCandidate(node.expression);
45597 case 204 /* BinaryExpression */:
45598 switch (node.operatorToken.kind) {
45599 case 59 /* EqualsToken */:
45600 return getReferenceCandidate(node.left);
45601 case 27 /* CommaToken */:
45602 return getReferenceCandidate(node.right);
45603 }
45604 }
45605 return node;
45606 }
45607 function getReferenceRoot(node) {
45608 var parent = node.parent;
45609 return parent.kind === 195 /* ParenthesizedExpression */ ||
45610 parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */ && parent.left === node ||
45611 parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
45612 getReferenceRoot(parent) : node;
45613 }
45614 function getTypeOfSwitchClause(clause) {
45615 if (clause.kind === 271 /* CaseClause */) {
45616 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
45617 }
45618 return neverType;
45619 }
45620 function getSwitchClauseTypes(switchStatement) {
45621 var links = getNodeLinks(switchStatement);
45622 if (!links.switchTypes) {
45623 links.switchTypes = [];
45624 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
45625 var clause = _a[_i];
45626 links.switchTypes.push(getTypeOfSwitchClause(clause));
45627 }
45628 }
45629 return links.switchTypes;
45630 }
45631 // Get the types from all cases in a switch on `typeof`. An
45632 // `undefined` element denotes an explicit `default` clause.
45633 function getSwitchClauseTypeOfWitnesses(switchStatement) {
45634 var witnesses = [];
45635 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
45636 var clause = _a[_i];
45637 if (clause.kind === 271 /* CaseClause */) {
45638 if (clause.expression.kind === 10 /* StringLiteral */) {
45639 witnesses.push(clause.expression.text);
45640 continue;
45641 }
45642 return ts.emptyArray;
45643 }
45644 witnesses.push(/*explicitDefaultStatement*/ undefined);
45645 }
45646 return witnesses;
45647 }
45648 function eachTypeContainedIn(source, types) {
45649 return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
45650 }
45651 function isTypeSubsetOf(source, target) {
45652 return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
45653 }
45654 function isTypeSubsetOfUnion(source, target) {
45655 if (source.flags & 1048576 /* Union */) {
45656 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
45657 var t = _a[_i];
45658 if (!containsType(target.types, t)) {
45659 return false;
45660 }
45661 }
45662 return true;
45663 }
45664 if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
45665 return true;
45666 }
45667 return containsType(target.types, source);
45668 }
45669 function forEachType(type, f) {
45670 return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
45671 }
45672 function everyType(type, f) {
45673 return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
45674 }
45675 function filterType(type, f) {
45676 if (type.flags & 1048576 /* Union */) {
45677 var types = type.types;
45678 var filtered = ts.filter(types, f);
45679 return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
45680 }
45681 return f(type) ? type : neverType;
45682 }
45683 function mapType(type, mapper, noReductions) {
45684 if (type.flags & 131072 /* Never */) {
45685 return type;
45686 }
45687 if (!(type.flags & 1048576 /* Union */)) {
45688 return mapper(type);
45689 }
45690 var types = type.types;
45691 var mappedType;
45692 var mappedTypes;
45693 for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
45694 var current = types_13[_i];
45695 var t = mapper(current);
45696 if (t) {
45697 if (!mappedType) {
45698 mappedType = t;
45699 }
45700 else if (!mappedTypes) {
45701 mappedTypes = [mappedType, t];
45702 }
45703 else {
45704 mappedTypes.push(t);
45705 }
45706 }
45707 }
45708 return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : mappedType;
45709 }
45710 function extractTypesOfKind(type, kind) {
45711 return filterType(type, function (t) { return (t.flags & kind) !== 0; });
45712 }
45713 // Return a new type in which occurrences of the string and number primitive types in
45714 // typeWithPrimitives have been replaced with occurrences of string literals and numeric
45715 // literals in typeWithLiterals, respectively.
45716 function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
45717 if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
45718 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
45719 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
45720 return mapType(typeWithPrimitives, function (t) {
45721 return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
45722 t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
45723 t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) :
45724 t;
45725 });
45726 }
45727 return typeWithPrimitives;
45728 }
45729 function isIncomplete(flowType) {
45730 return flowType.flags === 0;
45731 }
45732 function getTypeFromFlowType(flowType) {
45733 return flowType.flags === 0 ? flowType.type : flowType;
45734 }
45735 function createFlowType(type, incomplete) {
45736 return incomplete ? { flags: 0, type: type } : type;
45737 }
45738 // An evolving array type tracks the element types that have so far been seen in an
45739 // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
45740 // array types are ultimately converted into manifest array types (using getFinalArrayType)
45741 // and never escape the getFlowTypeOfReference function.
45742 function createEvolvingArrayType(elementType) {
45743 var result = createObjectType(256 /* EvolvingArray */);
45744 result.elementType = elementType;
45745 return result;
45746 }
45747 function getEvolvingArrayType(elementType) {
45748 return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
45749 }
45750 // When adding evolving array element types we do not perform subtype reduction. Instead,
45751 // we defer subtype reduction until the evolving array type is finalized into a manifest
45752 // array type.
45753 function addEvolvingArrayElementType(evolvingArrayType, node) {
45754 var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node));
45755 return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
45756 }
45757 function createFinalArrayType(elementType) {
45758 return elementType.flags & 131072 /* Never */ ?
45759 autoArrayType :
45760 createArrayType(elementType.flags & 1048576 /* Union */ ?
45761 getUnionType(elementType.types, 2 /* Subtype */) :
45762 elementType);
45763 }
45764 // We perform subtype reduction upon obtaining the final array type from an evolving array type.
45765 function getFinalArrayType(evolvingArrayType) {
45766 return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
45767 }
45768 function finalizeEvolvingArrayType(type) {
45769 return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
45770 }
45771 function getElementTypeOfEvolvingArrayType(type) {
45772 return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
45773 }
45774 function isEvolvingArrayTypeList(types) {
45775 var hasEvolvingArrayType = false;
45776 for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
45777 var t = types_14[_i];
45778 if (!(t.flags & 131072 /* Never */)) {
45779 if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
45780 return false;
45781 }
45782 hasEvolvingArrayType = true;
45783 }
45784 }
45785 return hasEvolvingArrayType;
45786 }
45787 // At flow control branch or loop junctions, if the type along every antecedent code path
45788 // is an evolving array type, we construct a combined evolving array type. Otherwise we
45789 // finalize all evolving array types.
45790 function getUnionOrEvolvingArrayType(types, subtypeReduction) {
45791 return isEvolvingArrayTypeList(types) ?
45792 getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
45793 getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
45794 }
45795 // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
45796 // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
45797 function isEvolvingArrayOperationTarget(node) {
45798 var root = getReferenceRoot(node);
45799 var parent = root.parent;
45800 var isLengthPushOrUnshift = parent.kind === 189 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" ||
45801 parent.parent.kind === 191 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name));
45802 var isElementAssignment = parent.kind === 190 /* ElementAccessExpression */ &&
45803 parent.expression === root &&
45804 parent.parent.kind === 204 /* BinaryExpression */ &&
45805 parent.parent.operatorToken.kind === 59 /* EqualsToken */ &&
45806 parent.parent.left === parent &&
45807 !ts.isAssignmentTarget(parent.parent) &&
45808 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
45809 return isLengthPushOrUnshift || isElementAssignment;
45810 }
45811 function maybeTypePredicateCall(node) {
45812 var links = getNodeLinks(node);
45813 if (links.maybeTypePredicate === undefined) {
45814 links.maybeTypePredicate = getMaybeTypePredicate(node);
45815 }
45816 return links.maybeTypePredicate;
45817 }
45818 function getMaybeTypePredicate(node) {
45819 if (node.expression.kind !== 98 /* SuperKeyword */) {
45820 var funcType = checkNonNullExpression(node.expression);
45821 if (funcType !== silentNeverType) {
45822 var apparentType = getApparentType(funcType);
45823 return apparentType !== errorType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate);
45824 }
45825 }
45826 return false;
45827 }
45828 function reportFlowControlError(node) {
45829 var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
45830 var sourceFile = ts.getSourceFileOfNode(node);
45831 var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
45832 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
45833 }
45834 function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
45835 if (initialType === void 0) { initialType = declaredType; }
45836 var key;
45837 var flowDepth = 0;
45838 if (flowAnalysisDisabled) {
45839 return errorType;
45840 }
45841 if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) {
45842 return declaredType;
45843 }
45844 var sharedFlowStart = sharedFlowCount;
45845 var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
45846 sharedFlowCount = sharedFlowStart;
45847 // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
45848 // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
45849 // on empty arrays are possible without implicit any errors and new element types can be inferred without
45850 // type mismatch errors.
45851 var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
45852 if (reference.parent && reference.parent.kind === 213 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
45853 return declaredType;
45854 }
45855 return resultType;
45856 function getTypeAtFlowNode(flow) {
45857 if (flowDepth === 2000) {
45858 // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
45859 // and disable further control flow analysis in the containing function or module body.
45860 flowAnalysisDisabled = true;
45861 reportFlowControlError(reference);
45862 return errorType;
45863 }
45864 flowDepth++;
45865 while (true) {
45866 var flags = flow.flags;
45867 if (flags & 1024 /* Shared */) {
45868 // We cache results of flow type resolution for shared nodes that were previously visited in
45869 // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
45870 // antecedent of more than one node.
45871 for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
45872 if (sharedFlowNodes[i] === flow) {
45873 flowDepth--;
45874 return sharedFlowTypes[i];
45875 }
45876 }
45877 }
45878 var type = void 0;
45879 if (flags & 4096 /* AfterFinally */) {
45880 // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement
45881 flow.locked = true;
45882 type = getTypeAtFlowNode(flow.antecedent);
45883 flow.locked = false;
45884 }
45885 else if (flags & 2048 /* PreFinally */) {
45886 // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel
45887 // so here just redirect to antecedent
45888 flow = flow.antecedent;
45889 continue;
45890 }
45891 else if (flags & 16 /* Assignment */) {
45892 type = getTypeAtFlowAssignment(flow);
45893 if (!type) {
45894 flow = flow.antecedent;
45895 continue;
45896 }
45897 }
45898 else if (flags & 96 /* Condition */) {
45899 type = getTypeAtFlowCondition(flow);
45900 }
45901 else if (flags & 128 /* SwitchClause */) {
45902 type = getTypeAtSwitchClause(flow);
45903 }
45904 else if (flags & 12 /* Label */) {
45905 if (flow.antecedents.length === 1) {
45906 flow = flow.antecedents[0];
45907 continue;
45908 }
45909 type = flags & 4 /* BranchLabel */ ?
45910 getTypeAtFlowBranchLabel(flow) :
45911 getTypeAtFlowLoopLabel(flow);
45912 }
45913 else if (flags & 256 /* ArrayMutation */) {
45914 type = getTypeAtFlowArrayMutation(flow);
45915 if (!type) {
45916 flow = flow.antecedent;
45917 continue;
45918 }
45919 }
45920 else if (flags & 2 /* Start */) {
45921 // Check if we should continue with the control flow of the containing function.
45922 var container = flow.container;
45923 if (container && container !== flowContainer &&
45924 reference.kind !== 189 /* PropertyAccessExpression */ &&
45925 reference.kind !== 190 /* ElementAccessExpression */ &&
45926 reference.kind !== 100 /* ThisKeyword */) {
45927 flow = container.flowNode;
45928 continue;
45929 }
45930 // At the top of the flow we have the initial type.
45931 type = initialType;
45932 }
45933 else {
45934 // Unreachable code errors are reported in the binding phase. Here we
45935 // simply return the non-auto declared type to reduce follow-on errors.
45936 type = convertAutoToAny(declaredType);
45937 }
45938 if (flags & 1024 /* Shared */) {
45939 // Record visited node and the associated type in the cache.
45940 sharedFlowNodes[sharedFlowCount] = flow;
45941 sharedFlowTypes[sharedFlowCount] = type;
45942 sharedFlowCount++;
45943 }
45944 flowDepth--;
45945 return type;
45946 }
45947 }
45948 function getTypeAtFlowAssignment(flow) {
45949 var node = flow.node;
45950 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
45951 // only need to evaluate the assigned type if the declared type is a union type.
45952 if (isMatchingReference(reference, node)) {
45953 if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
45954 var flowType = getTypeAtFlowNode(flow.antecedent);
45955 return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
45956 }
45957 if (declaredType === autoType || declaredType === autoArrayType) {
45958 if (isEmptyArrayAssignment(node)) {
45959 return getEvolvingArrayType(neverType);
45960 }
45961 var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference));
45962 return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
45963 }
45964 if (declaredType.flags & 1048576 /* Union */) {
45965 return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference));
45966 }
45967 return declaredType;
45968 }
45969 // We didn't have a direct match. However, if the reference is a dotted name, this
45970 // may be an assignment to a left hand part of the reference. For example, for a
45971 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
45972 // return the declared type.
45973 if (containsMatchingReference(reference, node)) {
45974 // A matching dotted name might also be an expando property on a function *expression*,
45975 // in which case we continue control flow analysis back to the function's declaration
45976 if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
45977 var init = ts.getDeclaredExpandoInitializer(node);
45978 if (init && (init.kind === 196 /* FunctionExpression */ || init.kind === 197 /* ArrowFunction */)) {
45979 return getTypeAtFlowNode(flow.antecedent);
45980 }
45981 }
45982 return declaredType;
45983 }
45984 // for (const _ in ref) acts as a nonnull on ref
45985 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 226 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
45986 return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
45987 }
45988 // Assignment doesn't affect reference
45989 return undefined;
45990 }
45991 function getTypeAtFlowArrayMutation(flow) {
45992 if (declaredType === autoType || declaredType === autoArrayType) {
45993 var node = flow.node;
45994 var expr = node.kind === 191 /* CallExpression */ ?
45995 node.expression.expression :
45996 node.left.expression;
45997 if (isMatchingReference(reference, getReferenceCandidate(expr))) {
45998 var flowType = getTypeAtFlowNode(flow.antecedent);
45999 var type = getTypeFromFlowType(flowType);
46000 if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
46001 var evolvedType_1 = type;
46002 if (node.kind === 191 /* CallExpression */) {
46003 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
46004 var arg = _a[_i];
46005 evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
46006 }
46007 }
46008 else {
46009 // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time)
46010 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
46011 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
46012 evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
46013 }
46014 }
46015 return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
46016 }
46017 return flowType;
46018 }
46019 }
46020 return undefined;
46021 }
46022 function getTypeAtFlowCondition(flow) {
46023 var flowType = getTypeAtFlowNode(flow.antecedent);
46024 var type = getTypeFromFlowType(flowType);
46025 if (type.flags & 131072 /* Never */) {
46026 return flowType;
46027 }
46028 // If we have an antecedent type (meaning we're reachable in some way), we first
46029 // attempt to narrow the antecedent type. If that produces the never type, and if
46030 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
46031 // take the type guard as an indication that control *could* reach here once we
46032 // have the complete type. We proceed by switching to the silent never type which
46033 // doesn't report errors when operators are applied to it. Note that this is the
46034 // *only* place a silent never type is ever generated.
46035 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
46036 var nonEvolvingType = finalizeEvolvingArrayType(type);
46037 var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue);
46038 if (narrowedType === nonEvolvingType) {
46039 return flowType;
46040 }
46041 var incomplete = isIncomplete(flowType);
46042 var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType;
46043 return createFlowType(resultType, incomplete);
46044 }
46045 function getTypeAtSwitchClause(flow) {
46046 var expr = flow.switchStatement.expression;
46047 var flowType = getTypeAtFlowNode(flow.antecedent);
46048 var type = getTypeFromFlowType(flowType);
46049 if (isMatchingReference(reference, expr)) {
46050 type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
46051 }
46052 else if (isMatchingReferenceDiscriminant(expr, type)) {
46053 type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
46054 }
46055 else if (expr.kind === 199 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
46056 type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
46057 }
46058 else if (containsMatchingReferenceDiscriminant(reference, expr)) {
46059 type = declaredType;
46060 }
46061 return createFlowType(type, isIncomplete(flowType));
46062 }
46063 function getTypeAtFlowBranchLabel(flow) {
46064 var antecedentTypes = [];
46065 var subtypeReduction = false;
46066 var seenIncomplete = false;
46067 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
46068 var antecedent = _a[_i];
46069 if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) {
46070 // if flow correspond to branch from pre-try to finally and this branch is locked - this means that
46071 // we initially have started following the flow outside the finally block.
46072 // in this case we should ignore this branch.
46073 continue;
46074 }
46075 var flowType = getTypeAtFlowNode(antecedent);
46076 var type = getTypeFromFlowType(flowType);
46077 // If the type at a particular antecedent path is the declared type and the
46078 // reference is known to always be assigned (i.e. when declared and initial types
46079 // are the same), there is no reason to process more antecedents since the only
46080 // possible outcome is subtypes that will be removed in the final union type anyway.
46081 if (type === declaredType && declaredType === initialType) {
46082 return type;
46083 }
46084 ts.pushIfUnique(antecedentTypes, type);
46085 // If an antecedent type is not a subset of the declared type, we need to perform
46086 // subtype reduction. This happens when a "foreign" type is injected into the control
46087 // flow using the instanceof operator or a user defined type predicate.
46088 if (!isTypeSubsetOf(type, declaredType)) {
46089 subtypeReduction = true;
46090 }
46091 if (isIncomplete(flowType)) {
46092 seenIncomplete = true;
46093 }
46094 }
46095 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
46096 }
46097 function getTypeAtFlowLoopLabel(flow) {
46098 // If we have previously computed the control flow type for the reference at
46099 // this flow loop junction, return the cached type.
46100 var id = getFlowNodeId(flow);
46101 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap());
46102 if (!key) {
46103 key = getFlowCacheKey(reference);
46104 // No cache key is generated when binding patterns are in unnarrowable situations
46105 if (!key) {
46106 return declaredType;
46107 }
46108 }
46109 var cached = cache.get(key);
46110 if (cached) {
46111 return cached;
46112 }
46113 // If this flow loop junction and reference are already being processed, return
46114 // the union of the types computed for each branch so far, marked as incomplete.
46115 // It is possible to see an empty array in cases where loops are nested and the
46116 // back edge of the outer loop reaches an inner loop that is already being analyzed.
46117 // In such cases we restart the analysis of the inner loop, which will then see
46118 // a non-empty in-process array for the outer loop and eventually terminate because
46119 // the first antecedent of a loop junction is always the non-looping control flow
46120 // path that leads to the top.
46121 for (var i = flowLoopStart; i < flowLoopCount; i++) {
46122 if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
46123 return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
46124 }
46125 }
46126 // Add the flow loop junction and reference to the in-process stack and analyze
46127 // each antecedent code path.
46128 var antecedentTypes = [];
46129 var subtypeReduction = false;
46130 var firstAntecedentType;
46131 flowLoopNodes[flowLoopCount] = flow;
46132 flowLoopKeys[flowLoopCount] = key;
46133 flowLoopTypes[flowLoopCount] = antecedentTypes;
46134 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
46135 var antecedent = _a[_i];
46136 flowLoopCount++;
46137 var flowType = getTypeAtFlowNode(antecedent);
46138 flowLoopCount--;
46139 if (!firstAntecedentType) {
46140 firstAntecedentType = flowType;
46141 }
46142 var type = getTypeFromFlowType(flowType);
46143 // If we see a value appear in the cache it is a sign that control flow analysis
46144 // was restarted and completed by checkExpressionCached. We can simply pick up
46145 // the resulting type and bail out.
46146 var cached_1 = cache.get(key);
46147 if (cached_1) {
46148 return cached_1;
46149 }
46150 ts.pushIfUnique(antecedentTypes, type);
46151 // If an antecedent type is not a subset of the declared type, we need to perform
46152 // subtype reduction. This happens when a "foreign" type is injected into the control
46153 // flow using the instanceof operator or a user defined type predicate.
46154 if (!isTypeSubsetOf(type, declaredType)) {
46155 subtypeReduction = true;
46156 }
46157 // If the type at a particular antecedent path is the declared type there is no
46158 // reason to process more antecedents since the only possible outcome is subtypes
46159 // that will be removed in the final union type anyway.
46160 if (type === declaredType) {
46161 break;
46162 }
46163 }
46164 // The result is incomplete if the first antecedent (the non-looping control flow path)
46165 // is incomplete.
46166 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
46167 if (isIncomplete(firstAntecedentType)) {
46168 return createFlowType(result, /*incomplete*/ true);
46169 }
46170 cache.set(key, result);
46171 return result;
46172 }
46173 function isMatchingReferenceDiscriminant(expr, computedType) {
46174 if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
46175 return false;
46176 }
46177 var name = getAccessedPropertyName(expr);
46178 if (name === undefined) {
46179 return false;
46180 }
46181 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name);
46182 }
46183 function narrowTypeByDiscriminant(type, access, narrowType) {
46184 var propName = getAccessedPropertyName(access);
46185 if (propName === undefined) {
46186 return type;
46187 }
46188 var propType = getTypeOfPropertyOfType(type, propName);
46189 var narrowedPropType = propType && narrowType(propType);
46190 return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOrIndexSignature(t, propName), narrowedPropType); });
46191 }
46192 function narrowTypeByTruthiness(type, expr, assumeTrue) {
46193 if (isMatchingReference(reference, expr)) {
46194 return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
46195 }
46196 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
46197 return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
46198 }
46199 if (containsMatchingReferenceDiscriminant(reference, expr)) {
46200 return declaredType;
46201 }
46202 return type;
46203 }
46204 function isTypePresencePossible(type, propName, assumeTrue) {
46205 if (getIndexInfoOfType(type, 0 /* String */)) {
46206 return true;
46207 }
46208 var prop = getPropertyOfType(type, propName);
46209 if (prop) {
46210 return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
46211 }
46212 return !assumeTrue;
46213 }
46214 function narrowByInKeyword(type, literal, assumeTrue) {
46215 if ((type.flags & (1048576 /* Union */ | 524288 /* Object */)) || (type.flags & 262144 /* TypeParameter */ && type.isThisType)) {
46216 var propName_1 = ts.escapeLeadingUnderscores(literal.text);
46217 return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
46218 }
46219 return type;
46220 }
46221 function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
46222 switch (expr.operatorToken.kind) {
46223 case 59 /* EqualsToken */:
46224 return narrowTypeByTruthiness(type, expr.left, assumeTrue);
46225 case 33 /* EqualsEqualsToken */:
46226 case 34 /* ExclamationEqualsToken */:
46227 case 35 /* EqualsEqualsEqualsToken */:
46228 case 36 /* ExclamationEqualsEqualsToken */:
46229 var operator_1 = expr.operatorToken.kind;
46230 var left_1 = getReferenceCandidate(expr.left);
46231 var right_1 = getReferenceCandidate(expr.right);
46232 if (left_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
46233 return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
46234 }
46235 if (right_1.kind === 199 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
46236 return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
46237 }
46238 if (isMatchingReference(reference, left_1)) {
46239 return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
46240 }
46241 if (isMatchingReference(reference, right_1)) {
46242 return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
46243 }
46244 if (isMatchingReferenceDiscriminant(left_1, declaredType)) {
46245 return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
46246 }
46247 if (isMatchingReferenceDiscriminant(right_1, declaredType)) {
46248 return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
46249 }
46250 if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) {
46251 return declaredType;
46252 }
46253 break;
46254 case 94 /* InstanceOfKeyword */:
46255 return narrowTypeByInstanceof(type, expr, assumeTrue);
46256 case 93 /* InKeyword */:
46257 var target = getReferenceCandidate(expr.right);
46258 if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
46259 return narrowByInKeyword(type, expr.left, assumeTrue);
46260 }
46261 break;
46262 case 27 /* CommaToken */:
46263 return narrowType(type, expr.right, assumeTrue);
46264 }
46265 return type;
46266 }
46267 function narrowTypeByEquality(type, operator, value, assumeTrue) {
46268 if (type.flags & 1 /* Any */) {
46269 return type;
46270 }
46271 if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) {
46272 assumeTrue = !assumeTrue;
46273 }
46274 var valueType = getTypeOfExpression(value);
46275 if ((type.flags & 2 /* Unknown */) && (operator === 35 /* EqualsEqualsEqualsToken */) && assumeTrue) {
46276 if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
46277 return valueType;
46278 }
46279 if (valueType.flags & 524288 /* Object */) {
46280 return nonPrimitiveType;
46281 }
46282 return type;
46283 }
46284 if (valueType.flags & 98304 /* Nullable */) {
46285 if (!strictNullChecks) {
46286 return type;
46287 }
46288 var doubleEquals = operator === 33 /* EqualsEqualsToken */ || operator === 34 /* ExclamationEqualsToken */;
46289 var facts = doubleEquals ?
46290 assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
46291 valueType.flags & 65536 /* Null */ ?
46292 assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
46293 assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
46294 return getTypeWithFacts(type, facts);
46295 }
46296 if (type.flags & 67637251 /* NotUnionOrUnit */) {
46297 return type;
46298 }
46299 if (assumeTrue) {
46300 var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); });
46301 return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType);
46302 }
46303 if (isUnitType(valueType)) {
46304 var regularType_1 = getRegularTypeOfLiteralType(valueType);
46305 return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; });
46306 }
46307 return type;
46308 }
46309 function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
46310 // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands
46311 var target = getReferenceCandidate(typeOfExpr.expression);
46312 if (!isMatchingReference(reference, target)) {
46313 // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the
46314 // narrowed type of 'y' to its declared type.
46315 if (containsMatchingReference(reference, target)) {
46316 return declaredType;
46317 }
46318 return type;
46319 }
46320 if (operator === 34 /* ExclamationEqualsToken */ || operator === 36 /* ExclamationEqualsEqualsToken */) {
46321 assumeTrue = !assumeTrue;
46322 }
46323 if (type.flags & 1 /* Any */ && literal.text === "function") {
46324 return type;
46325 }
46326 var facts = assumeTrue ?
46327 typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
46328 typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
46329 return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts);
46330 function narrowTypeForTypeof(type) {
46331 if (type.flags & 2 /* Unknown */ && literal.text === "object") {
46332 return getUnionType([nonPrimitiveType, nullType]);
46333 }
46334 // We narrow a non-union type to an exact primitive type if the non-union type
46335 // is a supertype of that primitive type. For example, type 'any' can be narrowed
46336 // to one of the primitive types.
46337 var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
46338 if (targetType) {
46339 if (isTypeSubtypeOf(type, targetType)) {
46340 return type;
46341 }
46342 if (isTypeSubtypeOf(targetType, type)) {
46343 return targetType;
46344 }
46345 if (type.flags & 63176704 /* Instantiable */) {
46346 var constraint = getBaseConstraintOfType(type) || anyType;
46347 if (isTypeSubtypeOf(targetType, constraint)) {
46348 return getIntersectionType([type, targetType]);
46349 }
46350 }
46351 }
46352 return type;
46353 }
46354 }
46355 function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
46356 // We only narrow if all case expressions specify
46357 // values with unit types, except for the case where
46358 // `type` is unknown. In this instance we map object
46359 // types to the nonPrimitive type and narrow with that.
46360 var switchTypes = getSwitchClauseTypes(switchStatement);
46361 if (!switchTypes.length) {
46362 return type;
46363 }
46364 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
46365 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
46366 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
46367 var groundClauseTypes = void 0;
46368 for (var i = 0; i < clauseTypes.length; i += 1) {
46369 var t = clauseTypes[i];
46370 if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
46371 if (groundClauseTypes !== undefined) {
46372 groundClauseTypes.push(t);
46373 }
46374 }
46375 else if (t.flags & 524288 /* Object */) {
46376 if (groundClauseTypes === undefined) {
46377 groundClauseTypes = clauseTypes.slice(0, i);
46378 }
46379 groundClauseTypes.push(nonPrimitiveType);
46380 }
46381 else {
46382 return type;
46383 }
46384 }
46385 return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
46386 }
46387 var discriminantType = getUnionType(clauseTypes);
46388 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
46389 replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
46390 if (!hasDefaultClause) {
46391 return caseType;
46392 }
46393 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
46394 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
46395 }
46396 function getImpliedTypeFromTypeofCase(type, text) {
46397 switch (text) {
46398 case "function":
46399 return type.flags & 1 /* Any */ ? type : globalFunctionType;
46400 case "object":
46401 return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
46402 default:
46403 return typeofTypesByName.get(text) || type;
46404 }
46405 }
46406 function narrowTypeForTypeofSwitch(candidate) {
46407 return function (type) {
46408 if (isTypeSubtypeOf(candidate, type)) {
46409 return candidate;
46410 }
46411 if (type.flags & 63176704 /* Instantiable */) {
46412 var constraint = getBaseConstraintOfType(type) || anyType;
46413 if (isTypeSubtypeOf(candidate, constraint)) {
46414 return getIntersectionType([type, candidate]);
46415 }
46416 }
46417 return type;
46418 };
46419 }
46420 function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
46421 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement);
46422 if (!switchWitnesses.length) {
46423 return type;
46424 }
46425 // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
46426 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
46427 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
46428 var clauseWitnesses;
46429 var switchFacts;
46430 if (defaultCaseLocation > -1) {
46431 // We no longer need the undefined denoting an
46432 // explicit default case. Remove the undefined and
46433 // fix-up clauseStart and clauseEnd. This means
46434 // that we don't have to worry about undefined
46435 // in the witness array.
46436 var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
46437 // The adjusted clause start and end after removing the `default` statement.
46438 var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
46439 var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
46440 clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
46441 switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
46442 }
46443 else {
46444 clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
46445 switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
46446 }
46447 if (hasDefaultClause) {
46448 return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
46449 }
46450 /*
46451 The implied type is the raw type suggested by a
46452 value being caught in this clause.
46453
46454 When the clause contains a default case we ignore
46455 the implied type and try to narrow using any facts
46456 we can learn: see `switchFacts`.
46457
46458 Example:
46459 switch (typeof x) {
46460 case 'number':
46461 case 'string': break;
46462 default: break;
46463 case 'number':
46464 case 'boolean': break
46465 }
46466
46467 In the first clause (case `number` and `string`) the
46468 implied type is number | string.
46469
46470 In the default clause we de not compute an implied type.
46471
46472 In the third clause (case `number` and `boolean`)
46473 the naive implied type is number | boolean, however
46474 we use the type facts to narrow the implied type to
46475 boolean. We know that number cannot be selected
46476 because it is caught in the first clause.
46477 */
46478 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts);
46479 if (impliedType.flags & 1048576 /* Union */) {
46480 impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type));
46481 }
46482 return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts);
46483 }
46484 function narrowTypeByInstanceof(type, expr, assumeTrue) {
46485 var left = getReferenceCandidate(expr.left);
46486 if (!isMatchingReference(reference, left)) {
46487 // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the
46488 // narrowed type of 'y' to its declared type. We do this because preceding 'x.y'
46489 // references might reference a different 'y' property. However, we make an exception
46490 // for property accesses where x is a synthetic 'this' expression, indicating that we
46491 // were called from isPropertyInitializedInConstructor. Without this exception,
46492 // initializations of 'this' properties that occur before a 'this instanceof XXX'
46493 // check would not be considered.
46494 if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) {
46495 return declaredType;
46496 }
46497 return type;
46498 }
46499 // Check that right operand is a function type with a prototype property
46500 var rightType = getTypeOfExpression(expr.right);
46501 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
46502 return type;
46503 }
46504 var targetType;
46505 var prototypeProperty = getPropertyOfType(rightType, "prototype");
46506 if (prototypeProperty) {
46507 // Target type is type of the prototype property
46508 var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
46509 if (!isTypeAny(prototypePropertyType)) {
46510 targetType = prototypePropertyType;
46511 }
46512 }
46513 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
46514 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
46515 return type;
46516 }
46517 if (!targetType) {
46518 var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
46519 targetType = constructSignatures.length ?
46520 getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
46521 emptyObjectType;
46522 }
46523 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
46524 }
46525 function getNarrowedType(type, candidate, assumeTrue, isRelated) {
46526 if (!assumeTrue) {
46527 return filterType(type, function (t) { return !isRelated(t, candidate); });
46528 }
46529 // If the current type is a union type, remove all constituents that couldn't be instances of
46530 // the candidate type. If one or more constituents remain, return a union of those.
46531 if (type.flags & 1048576 /* Union */) {
46532 var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
46533 if (!(assignableType.flags & 131072 /* Never */)) {
46534 return assignableType;
46535 }
46536 }
46537 // If the candidate type is a subtype of the target type, narrow to the candidate type.
46538 // Otherwise, if the target type is assignable to the candidate type, keep the target type.
46539 // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
46540 // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
46541 // two types.
46542 return isTypeSubtypeOf(candidate, type) ? candidate :
46543 isTypeAssignableTo(type, candidate) ? type :
46544 isTypeAssignableTo(candidate, type) ? candidate :
46545 getIntersectionType([type, candidate]);
46546 }
46547 function narrowTypeByTypePredicate(type, callExpression, assumeTrue) {
46548 if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) {
46549 return type;
46550 }
46551 var signature = getResolvedSignature(callExpression);
46552 var predicate = getTypePredicateOfSignature(signature);
46553 if (!predicate) {
46554 return type;
46555 }
46556 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
46557 if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) {
46558 return type;
46559 }
46560 if (ts.isIdentifierTypePredicate(predicate)) {
46561 var predicateArgument = callExpression.arguments[predicate.parameterIndex];
46562 if (predicateArgument) {
46563 if (isMatchingReference(reference, predicateArgument)) {
46564 return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
46565 }
46566 if (containsMatchingReference(reference, predicateArgument)) {
46567 return declaredType;
46568 }
46569 }
46570 }
46571 else {
46572 var invokedExpression = ts.skipParentheses(callExpression.expression);
46573 if (ts.isAccessExpression(invokedExpression)) {
46574 var possibleReference = ts.skipParentheses(invokedExpression.expression);
46575 if (isMatchingReference(reference, possibleReference)) {
46576 return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
46577 }
46578 if (containsMatchingReference(reference, possibleReference)) {
46579 return declaredType;
46580 }
46581 }
46582 }
46583 return type;
46584 }
46585 // Narrow the given type based on the given expression having the assumed boolean value. The returned type
46586 // will be a subtype or the same type as the argument.
46587 function narrowType(type, expr, assumeTrue) {
46588 switch (expr.kind) {
46589 case 72 /* Identifier */:
46590 case 100 /* ThisKeyword */:
46591 case 98 /* SuperKeyword */:
46592 case 189 /* PropertyAccessExpression */:
46593 case 190 /* ElementAccessExpression */:
46594 return narrowTypeByTruthiness(type, expr, assumeTrue);
46595 case 191 /* CallExpression */:
46596 return narrowTypeByTypePredicate(type, expr, assumeTrue);
46597 case 195 /* ParenthesizedExpression */:
46598 return narrowType(type, expr.expression, assumeTrue);
46599 case 204 /* BinaryExpression */:
46600 return narrowTypeByBinaryExpression(type, expr, assumeTrue);
46601 case 202 /* PrefixUnaryExpression */:
46602 if (expr.operator === 52 /* ExclamationToken */) {
46603 return narrowType(type, expr.operand, !assumeTrue);
46604 }
46605 break;
46606 }
46607 return type;
46608 }
46609 }
46610 function getTypeOfSymbolAtLocation(symbol, location) {
46611 symbol = symbol.exportSymbol || symbol;
46612 // If we have an identifier or a property access at the given location, if the location is
46613 // an dotted name expression, and if the location is not an assignment target, obtain the type
46614 // of the expression (which will reflect control flow analysis). If the expression indeed
46615 // resolved to the given symbol, return the narrowed type.
46616 if (location.kind === 72 /* Identifier */) {
46617 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
46618 location = location.parent;
46619 }
46620 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
46621 var type = getTypeOfExpression(location);
46622 if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
46623 return type;
46624 }
46625 }
46626 }
46627 // The location isn't a reference to the given symbol, meaning we're being asked
46628 // a hypothetical question of what type the symbol would have if there was a reference
46629 // to it at the given location. Since we have no control flow information for the
46630 // hypothetical reference (control flow information is created and attached by the
46631 // binder), we simply return the declared type of the symbol.
46632 return getTypeOfSymbol(symbol);
46633 }
46634 function getControlFlowContainer(node) {
46635 return ts.findAncestor(node.parent, function (node) {
46636 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
46637 node.kind === 245 /* ModuleBlock */ ||
46638 node.kind === 284 /* SourceFile */ ||
46639 node.kind === 154 /* PropertyDeclaration */;
46640 });
46641 }
46642 // Check if a parameter is assigned anywhere within its declaring function.
46643 function isParameterAssigned(symbol) {
46644 var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
46645 var links = getNodeLinks(func);
46646 if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
46647 links.flags |= 8388608 /* AssignmentsMarked */;
46648 if (!hasParentWithAssignmentsMarked(func)) {
46649 markParameterAssignments(func);
46650 }
46651 }
46652 return symbol.isAssigned || false;
46653 }
46654 function hasParentWithAssignmentsMarked(node) {
46655 return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
46656 }
46657 function markParameterAssignments(node) {
46658 if (node.kind === 72 /* Identifier */) {
46659 if (ts.isAssignmentTarget(node)) {
46660 var symbol = getResolvedSymbol(node);
46661 if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 151 /* Parameter */) {
46662 symbol.isAssigned = true;
46663 }
46664 }
46665 }
46666 else {
46667 ts.forEachChild(node, markParameterAssignments);
46668 }
46669 }
46670 function isConstVariable(symbol) {
46671 return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
46672 }
46673 /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
46674 function removeOptionalityFromDeclaredType(declaredType, declaration) {
46675 var annotationIncludesUndefined = strictNullChecks &&
46676 declaration.kind === 151 /* Parameter */ &&
46677 declaration.initializer &&
46678 getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
46679 !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
46680 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
46681 }
46682 function isConstraintPosition(node) {
46683 var parent = node.parent;
46684 return parent.kind === 189 /* PropertyAccessExpression */ ||
46685 parent.kind === 191 /* CallExpression */ && parent.expression === node ||
46686 parent.kind === 190 /* ElementAccessExpression */ && parent.expression === node ||
46687 parent.kind === 186 /* BindingElement */ && parent.name === node && !!parent.initializer;
46688 }
46689 function typeHasNullableConstraint(type) {
46690 return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 98304 /* Nullable */);
46691 }
46692 function getConstraintForLocation(type, node) {
46693 // When a node is the left hand expression of a property access, element access, or call expression,
46694 // and the type of the node includes type variables with constraints that are nullable, we fetch the
46695 // apparent type of the node *before* performing control flow analysis such that narrowings apply to
46696 // the constraint type.
46697 if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
46698 return mapType(getWidenedType(type), getBaseConstraintOrType);
46699 }
46700 return type;
46701 }
46702 function markAliasReferenced(symbol, location) {
46703 if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
46704 markAliasSymbolAsReferenced(symbol);
46705 }
46706 }
46707 function checkIdentifier(node) {
46708 var symbol = getResolvedSymbol(node);
46709 if (symbol === unknownSymbol) {
46710 return errorType;
46711 }
46712 // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
46713 // Although in down-level emit of arrow function, we emit it using function expression which means that
46714 // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
46715 // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
46716 // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
46717 // can explicitly bound arguments objects
46718 if (symbol === argumentsSymbol) {
46719 var container = ts.getContainingFunction(node);
46720 if (languageVersion < 2 /* ES2015 */) {
46721 if (container.kind === 197 /* ArrowFunction */) {
46722 error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
46723 }
46724 else if (ts.hasModifier(container, 256 /* Async */)) {
46725 error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method);
46726 }
46727 }
46728 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
46729 return getTypeOfSymbol(symbol);
46730 }
46731 // We should only mark aliases as referenced if there isn't a local value declaration
46732 // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
46733 if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
46734 markAliasReferenced(symbol, node);
46735 }
46736 var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
46737 var declaration = localOrExportSymbol.valueDeclaration;
46738 if (localOrExportSymbol.flags & 32 /* Class */) {
46739 // Due to the emit for class decorators, any reference to the class from inside of the class body
46740 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
46741 // behavior of class names in ES6.
46742 if (declaration.kind === 240 /* ClassDeclaration */
46743 && ts.nodeIsDecorated(declaration)) {
46744 var container = ts.getContainingClass(node);
46745 while (container !== undefined) {
46746 if (container === declaration && container.name !== node) {
46747 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
46748 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
46749 break;
46750 }
46751 container = ts.getContainingClass(container);
46752 }
46753 }
46754 else if (declaration.kind === 209 /* ClassExpression */) {
46755 // When we emit a class expression with static members that contain a reference
46756 // to the constructor in the initializer, we will need to substitute that
46757 // binding with an alias as the class name is not in scope.
46758 var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
46759 while (container.kind !== 284 /* SourceFile */) {
46760 if (container.parent === declaration) {
46761 if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
46762 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
46763 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
46764 }
46765 break;
46766 }
46767 container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
46768 }
46769 }
46770 }
46771 checkNestedBlockScopedBinding(node, symbol);
46772 var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
46773 var assignmentKind = ts.getAssignmentTargetKind(node);
46774 if (assignmentKind) {
46775 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
46776 !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
46777 error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
46778 return errorType;
46779 }
46780 if (isReadonlySymbol(localOrExportSymbol)) {
46781 if (localOrExportSymbol.flags & 3 /* Variable */) {
46782 error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
46783 }
46784 else {
46785 error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
46786 }
46787 return errorType;
46788 }
46789 }
46790 var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
46791 // We only narrow variables and parameters occurring in a non-assignment position. For all other
46792 // entities we simply return the declared type.
46793 if (localOrExportSymbol.flags & 3 /* Variable */) {
46794 if (assignmentKind === 1 /* Definite */) {
46795 return type;
46796 }
46797 }
46798 else if (isAlias) {
46799 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
46800 }
46801 else {
46802 return type;
46803 }
46804 if (!declaration) {
46805 return type;
46806 }
46807 // The declaration container is the innermost function that encloses the declaration of the variable
46808 // or parameter. The flow container is the innermost function starting with which we analyze the control
46809 // flow graph to determine the control flow based type.
46810 var isParameter = ts.getRootDeclaration(declaration).kind === 151 /* Parameter */;
46811 var declarationContainer = getControlFlowContainer(declaration);
46812 var flowContainer = getControlFlowContainer(node);
46813 var isOuterVariable = flowContainer !== declarationContainer;
46814 var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
46815 var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
46816 // When the control flow originates in a function expression or arrow function and we are referencing
46817 // a const variable or parameter from an outer function, we extend the origin of the control flow
46818 // analysis to include the immediately enclosing function.
46819 while (flowContainer !== declarationContainer && (flowContainer.kind === 196 /* FunctionExpression */ ||
46820 flowContainer.kind === 197 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
46821 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
46822 flowContainer = getControlFlowContainer(flowContainer);
46823 }
46824 // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
46825 // the entire control flow graph from the variable's declaration (i.e. when the flow container and
46826 // declaration container are the same).
46827 var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports ||
46828 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 ||
46829 isInTypeQuery(node) || node.parent.kind === 257 /* ExportSpecifier */) ||
46830 node.parent.kind === 213 /* NonNullExpression */ ||
46831 declaration.kind === 237 /* VariableDeclaration */ && declaration.exclamationToken ||
46832 declaration.flags & 4194304 /* Ambient */;
46833 var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
46834 type === autoType || type === autoArrayType ? undefinedType :
46835 getOptionalType(type);
46836 var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
46837 // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
46838 // from declaration to use, and when the variable's declared type doesn't include undefined but the
46839 // control flow based type does include undefined.
46840 if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
46841 if (flowType === autoType || flowType === autoArrayType) {
46842 if (noImplicitAny) {
46843 error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType));
46844 error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
46845 }
46846 return convertAutoToAny(flowType);
46847 }
46848 }
46849 else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
46850 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
46851 // Return the declared type to reduce follow-on errors
46852 return type;
46853 }
46854 return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
46855 }
46856 function isInsideFunction(node, threshold) {
46857 return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
46858 }
46859 function getPartOfForStatementContainingNode(node, container) {
46860 return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
46861 }
46862 function checkNestedBlockScopedBinding(node, symbol) {
46863 if (languageVersion >= 2 /* ES2015 */ ||
46864 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
46865 ts.isSourceFile(symbol.valueDeclaration) ||
46866 symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) {
46867 return;
46868 }
46869 // 1. walk from the use site up to the declaration and check
46870 // if there is anything function like between declaration and use-site (is binding/class is captured in function).
46871 // 2. walk from the declaration up to the boundary of lexical environment and check
46872 // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
46873 var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
46874 var usedInFunction = isInsideFunction(node.parent, container);
46875 var current = container;
46876 var containedInIterationStatement = false;
46877 while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
46878 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
46879 containedInIterationStatement = true;
46880 break;
46881 }
46882 current = current.parent;
46883 }
46884 if (containedInIterationStatement) {
46885 if (usedInFunction) {
46886 // mark iteration statement as containing block-scoped binding captured in some function
46887 var capturesBlockScopeBindingInLoopBody = true;
46888 if (ts.isForStatement(container) &&
46889 ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container) {
46890 var part = getPartOfForStatementContainingNode(node.parent, container);
46891 if (part) {
46892 var links = getNodeLinks(part);
46893 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
46894 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
46895 ts.pushIfUnique(capturedBindings, symbol);
46896 if (part === container.initializer) {
46897 capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
46898 }
46899 }
46900 }
46901 if (capturesBlockScopeBindingInLoopBody) {
46902 getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
46903 }
46904 }
46905 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
46906 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
46907 if (container.kind === 225 /* ForStatement */ &&
46908 ts.getAncestor(symbol.valueDeclaration, 238 /* VariableDeclarationList */).parent === container &&
46909 isAssignedInBodyOfForStatement(node, container)) {
46910 getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
46911 }
46912 // set 'declared inside loop' bit on the block-scoped binding
46913 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
46914 }
46915 if (usedInFunction) {
46916 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
46917 }
46918 }
46919 function isBindingCapturedByNode(node, decl) {
46920 var links = getNodeLinks(node);
46921 return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
46922 }
46923 function isAssignedInBodyOfForStatement(node, container) {
46924 // skip parenthesized nodes
46925 var current = node;
46926 while (current.parent.kind === 195 /* ParenthesizedExpression */) {
46927 current = current.parent;
46928 }
46929 // check if node is used as LHS in some assignment expression
46930 var isAssigned = false;
46931 if (ts.isAssignmentTarget(current)) {
46932 isAssigned = true;
46933 }
46934 else if ((current.parent.kind === 202 /* PrefixUnaryExpression */ || current.parent.kind === 203 /* PostfixUnaryExpression */)) {
46935 var expr = current.parent;
46936 isAssigned = expr.operator === 44 /* PlusPlusToken */ || expr.operator === 45 /* MinusMinusToken */;
46937 }
46938 if (!isAssigned) {
46939 return false;
46940 }
46941 // at this point we know that node is the target of assignment
46942 // now check that modification happens inside the statement part of the ForStatement
46943 return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
46944 }
46945 function captureLexicalThis(node, container) {
46946 getNodeLinks(node).flags |= 2 /* LexicalThis */;
46947 if (container.kind === 154 /* PropertyDeclaration */ || container.kind === 157 /* Constructor */) {
46948 var classNode = container.parent;
46949 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
46950 }
46951 else {
46952 getNodeLinks(container).flags |= 4 /* CaptureThis */;
46953 }
46954 }
46955 function findFirstSuperCall(n) {
46956 if (ts.isSuperCall(n)) {
46957 return n;
46958 }
46959 else if (ts.isFunctionLike(n)) {
46960 return undefined;
46961 }
46962 return ts.forEachChild(n, findFirstSuperCall);
46963 }
46964 /**
46965 * Return a cached result if super-statement is already found.
46966 * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor
46967 *
46968 * @param constructor constructor-function to look for super statement
46969 */
46970 function getSuperCallInConstructor(constructor) {
46971 var links = getNodeLinks(constructor);
46972 // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result
46973 if (links.hasSuperCall === undefined) {
46974 links.superCall = findFirstSuperCall(constructor.body);
46975 links.hasSuperCall = links.superCall ? true : false;
46976 }
46977 return links.superCall;
46978 }
46979 /**
46980 * Check if the given class-declaration extends null then return true.
46981 * Otherwise, return false
46982 * @param classDecl a class declaration to check if it extends null
46983 */
46984 function classDeclarationExtendsNull(classDecl) {
46985 var classSymbol = getSymbolOfNode(classDecl);
46986 var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
46987 var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
46988 return baseConstructorType === nullWideningType;
46989 }
46990 function checkThisBeforeSuper(node, container, diagnosticMessage) {
46991 var containingClassDecl = container.parent;
46992 var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
46993 // If a containing class does not have extends clause or the class extends null
46994 // skip checking whether super statement is called before "this" accessing.
46995 if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
46996 var superCall = getSuperCallInConstructor(container);
46997 // We should give an error in the following cases:
46998 // - No super-call
46999 // - "this" is accessing before super-call.
47000 // i.e super(this)
47001 // this.x; super();
47002 // We want to make sure that super-call is done before accessing "this" so that
47003 // "this" is not accessed as a parameter of the super-call.
47004 if (!superCall || superCall.end > node.pos) {
47005 // In ES6, super inside constructor of class-declaration has to precede "this" accessing
47006 error(node, diagnosticMessage);
47007 }
47008 }
47009 }
47010 function checkThisExpression(node) {
47011 // Stop at the first arrow function so that we can
47012 // tell whether 'this' needs to be captured.
47013 var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
47014 var capturedByArrowFunction = false;
47015 if (container.kind === 157 /* Constructor */) {
47016 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
47017 }
47018 // Now skip arrow functions to get the "real" owner of 'this'.
47019 if (container.kind === 197 /* ArrowFunction */) {
47020 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
47021 capturedByArrowFunction = true;
47022 }
47023 switch (container.kind) {
47024 case 244 /* ModuleDeclaration */:
47025 error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
47026 // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
47027 break;
47028 case 243 /* EnumDeclaration */:
47029 error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
47030 // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
47031 break;
47032 case 157 /* Constructor */:
47033 if (isInConstructorArgumentInitializer(node, container)) {
47034 error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
47035 // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
47036 }
47037 break;
47038 case 154 /* PropertyDeclaration */:
47039 case 153 /* PropertySignature */:
47040 if (ts.hasModifier(container, 32 /* Static */)) {
47041 error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
47042 // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
47043 }
47044 break;
47045 case 149 /* ComputedPropertyName */:
47046 error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
47047 break;
47048 }
47049 // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
47050 if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
47051 captureLexicalThis(node, container);
47052 }
47053 var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
47054 if (noImplicitThis) {
47055 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
47056 if (type === globalThisType_1 && capturedByArrowFunction) {
47057 error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
47058 }
47059 else if (!type) {
47060 // With noImplicitThis, functions may not reference 'this' if it has type 'any'
47061 var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
47062 if (!ts.isSourceFile(container)) {
47063 var outsideThis = tryGetThisTypeAt(container);
47064 if (outsideThis && outsideThis !== globalThisType_1) {
47065 ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
47066 }
47067 }
47068 }
47069 }
47070 return type || anyType;
47071 }
47072 function tryGetThisTypeAt(node, includeGlobalThis, container) {
47073 if (includeGlobalThis === void 0) { includeGlobalThis = true; }
47074 if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
47075 var isInJS = ts.isInJSFile(node);
47076 if (ts.isFunctionLike(container) &&
47077 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
47078 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
47079 // If this is a function in a JS file, it might be a class method.
47080 var className = getClassNameFromPrototypeMethod(container);
47081 if (isInJS && className) {
47082 var classSymbol = checkExpression(className).symbol;
47083 if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
47084 var classType = getJSClassType(classSymbol);
47085 if (classType) {
47086 return getFlowTypeOfReference(node, classType);
47087 }
47088 }
47089 }
47090 // Check if it's a constructor definition, can be either a variable decl or function decl
47091 // i.e.
47092 // * /** @constructor */ function [name]() { ... }
47093 // * /** @constructor */ var x = function() { ... }
47094 else if (isInJS &&
47095 (container.kind === 196 /* FunctionExpression */ || container.kind === 239 /* FunctionDeclaration */) &&
47096 ts.getJSDocClassTag(container)) {
47097 var classType = getJSClassType(getMergedSymbol(container.symbol));
47098 if (classType) {
47099 return getFlowTypeOfReference(node, classType);
47100 }
47101 }
47102 var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container);
47103 if (thisType) {
47104 return getFlowTypeOfReference(node, thisType);
47105 }
47106 }
47107 if (ts.isClassLike(container.parent)) {
47108 var symbol = getSymbolOfNode(container.parent);
47109 var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
47110 return getFlowTypeOfReference(node, type);
47111 }
47112 if (isInJS) {
47113 var type = getTypeForThisExpressionFromJSDoc(container);
47114 if (type && type !== errorType) {
47115 return getFlowTypeOfReference(node, type);
47116 }
47117 }
47118 if (ts.isSourceFile(container)) {
47119 // look up in the source file's locals or exports
47120 if (container.commonJsModuleIndicator) {
47121 var fileSymbol = getSymbolOfNode(container);
47122 return fileSymbol && getTypeOfSymbol(fileSymbol);
47123 }
47124 else if (includeGlobalThis) {
47125 return getTypeOfSymbol(globalThisSymbol);
47126 }
47127 }
47128 }
47129 function getClassNameFromPrototypeMethod(container) {
47130 // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
47131 if (container.kind === 196 /* FunctionExpression */ &&
47132 ts.isBinaryExpression(container.parent) &&
47133 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
47134 // Get the 'x' of 'x.prototype.y = container'
47135 return container.parent // x.prototype.y = container
47136 .left // x.prototype.y
47137 .expression // x.prototype
47138 .expression; // x
47139 }
47140 // x.prototype = { method() { } }
47141 else if (container.kind === 156 /* MethodDeclaration */ &&
47142 container.parent.kind === 188 /* ObjectLiteralExpression */ &&
47143 ts.isBinaryExpression(container.parent.parent) &&
47144 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
47145 return container.parent.parent.left.expression;
47146 }
47147 // x.prototype = { method: function() { } }
47148 else if (container.kind === 196 /* FunctionExpression */ &&
47149 container.parent.kind === 275 /* PropertyAssignment */ &&
47150 container.parent.parent.kind === 188 /* ObjectLiteralExpression */ &&
47151 ts.isBinaryExpression(container.parent.parent.parent) &&
47152 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
47153 return container.parent.parent.parent.left.expression;
47154 }
47155 // Object.defineProperty(x, "method", { value: function() { } });
47156 // Object.defineProperty(x, "method", { set: (x: () => void) => void });
47157 // Object.defineProperty(x, "method", { get: () => function() { }) });
47158 else if (container.kind === 196 /* FunctionExpression */ &&
47159 ts.isPropertyAssignment(container.parent) &&
47160 ts.isIdentifier(container.parent.name) &&
47161 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
47162 ts.isObjectLiteralExpression(container.parent.parent) &&
47163 ts.isCallExpression(container.parent.parent.parent) &&
47164 container.parent.parent.parent.arguments[2] === container.parent.parent &&
47165 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
47166 return container.parent.parent.parent.arguments[0].expression;
47167 }
47168 // Object.defineProperty(x, "method", { value() { } });
47169 // Object.defineProperty(x, "method", { set(x: () => void) {} });
47170 // Object.defineProperty(x, "method", { get() { return () => {} } });
47171 else if (ts.isMethodDeclaration(container) &&
47172 ts.isIdentifier(container.name) &&
47173 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
47174 ts.isObjectLiteralExpression(container.parent) &&
47175 ts.isCallExpression(container.parent.parent) &&
47176 container.parent.parent.arguments[2] === container.parent &&
47177 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
47178 return container.parent.parent.arguments[0].expression;
47179 }
47180 }
47181 function getTypeForThisExpressionFromJSDoc(node) {
47182 var jsdocType = ts.getJSDocType(node);
47183 if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
47184 var jsDocFunctionType = jsdocType;
47185 if (jsDocFunctionType.parameters.length > 0 &&
47186 jsDocFunctionType.parameters[0].name &&
47187 jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
47188 return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
47189 }
47190 }
47191 var thisTag = ts.getJSDocThisTag(node);
47192 if (thisTag && thisTag.typeExpression) {
47193 return getTypeFromTypeNode(thisTag.typeExpression);
47194 }
47195 }
47196 function isInConstructorArgumentInitializer(node, constructorDecl) {
47197 return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 151 /* Parameter */ && n.parent === constructorDecl; });
47198 }
47199 function checkSuperExpression(node) {
47200 var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node;
47201 var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
47202 var needToCaptureLexicalThis = false;
47203 // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
47204 if (!isCallExpression) {
47205 while (container && container.kind === 197 /* ArrowFunction */) {
47206 container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
47207 needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
47208 }
47209 }
47210 var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
47211 var nodeCheckFlag = 0;
47212 if (!canUseSuperExpression) {
47213 // issue more specific error if super is used in computed property name
47214 // class A { foo() { return "1" }}
47215 // class B {
47216 // [super.foo()]() {}
47217 // }
47218 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 149 /* ComputedPropertyName */; });
47219 if (current && current.kind === 149 /* ComputedPropertyName */) {
47220 error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
47221 }
47222 else if (isCallExpression) {
47223 error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
47224 }
47225 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */)) {
47226 error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
47227 }
47228 else {
47229 error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
47230 }
47231 return errorType;
47232 }
47233 if (!isCallExpression && container.kind === 157 /* Constructor */) {
47234 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
47235 }
47236 if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) {
47237 nodeCheckFlag = 512 /* SuperStatic */;
47238 }
47239 else {
47240 nodeCheckFlag = 256 /* SuperInstance */;
47241 }
47242 getNodeLinks(node).flags |= nodeCheckFlag;
47243 // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
47244 // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
47245 // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
47246 // uses an arrow function, which is permitted to reference `super`.
47247 //
47248 // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
47249 // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
47250 // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
47251 //
47252 // The simplest case is reading a value, in which case we will emit something like the following:
47253 //
47254 // // ts
47255 // ...
47256 // async asyncMethod() {
47257 // let x = await super.asyncMethod();
47258 // return x;
47259 // }
47260 // ...
47261 //
47262 // // js
47263 // ...
47264 // asyncMethod() {
47265 // const _super = Object.create(null, {
47266 // asyncMethod: { get: () => super.asyncMethod },
47267 // });
47268 // return __awaiter(this, arguments, Promise, function *() {
47269 // let x = yield _super.asyncMethod.call(this);
47270 // return x;
47271 // });
47272 // }
47273 // ...
47274 //
47275 // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
47276 // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
47277 //
47278 // // ts
47279 // ...
47280 // async asyncMethod(ar: Promise<any[]>) {
47281 // [super.a, super.b] = await ar;
47282 // }
47283 // ...
47284 //
47285 // // js
47286 // ...
47287 // asyncMethod(ar) {
47288 // const _super = Object.create(null, {
47289 // a: { get: () => super.a, set: (v) => super.a = v },
47290 // b: { get: () => super.b, set: (v) => super.b = v }
47291 // };
47292 // return __awaiter(this, arguments, Promise, function *() {
47293 // [_super.a, _super.b] = yield ar;
47294 // });
47295 // }
47296 // ...
47297 //
47298 // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
47299 // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
47300 //
47301 // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
47302 if (container.kind === 156 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) {
47303 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
47304 getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
47305 }
47306 else {
47307 getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
47308 }
47309 }
47310 if (needToCaptureLexicalThis) {
47311 // call expressions are allowed only in constructors so they should always capture correct 'this'
47312 // super property access expressions can also appear in arrow functions -
47313 // in this case they should also use correct lexical this
47314 captureLexicalThis(node.parent, container);
47315 }
47316 if (container.parent.kind === 188 /* ObjectLiteralExpression */) {
47317 if (languageVersion < 2 /* ES2015 */) {
47318 error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
47319 return errorType;
47320 }
47321 else {
47322 // for object literal assume that type of 'super' is 'any'
47323 return anyType;
47324 }
47325 }
47326 // at this point the only legal case for parent is ClassLikeDeclaration
47327 var classLikeDeclaration = container.parent;
47328 if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
47329 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
47330 return errorType;
47331 }
47332 var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
47333 var baseClassType = classType && getBaseTypes(classType)[0];
47334 if (!baseClassType) {
47335 return errorType;
47336 }
47337 if (container.kind === 157 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
47338 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
47339 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
47340 return errorType;
47341 }
47342 return nodeCheckFlag === 512 /* SuperStatic */
47343 ? getBaseConstructorTypeOfClass(classType)
47344 : getTypeWithThisArgument(baseClassType, classType.thisType);
47345 function isLegalUsageOfSuperExpression(container) {
47346 if (!container) {
47347 return false;
47348 }
47349 if (isCallExpression) {
47350 // TS 1.0 SPEC (April 2014): 4.8.1
47351 // Super calls are only permitted in constructors of derived classes
47352 return container.kind === 157 /* Constructor */;
47353 }
47354 else {
47355 // TS 1.0 SPEC (April 2014)
47356 // 'super' property access is allowed
47357 // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
47358 // - In a static member function or static member accessor
47359 // topmost container must be something that is directly nested in the class declaration\object literal expression
47360 if (ts.isClassLike(container.parent) || container.parent.kind === 188 /* ObjectLiteralExpression */) {
47361 if (ts.hasModifier(container, 32 /* Static */)) {
47362 return container.kind === 156 /* MethodDeclaration */ ||
47363 container.kind === 155 /* MethodSignature */ ||
47364 container.kind === 158 /* GetAccessor */ ||
47365 container.kind === 159 /* SetAccessor */;
47366 }
47367 else {
47368 return container.kind === 156 /* MethodDeclaration */ ||
47369 container.kind === 155 /* MethodSignature */ ||
47370 container.kind === 158 /* GetAccessor */ ||
47371 container.kind === 159 /* SetAccessor */ ||
47372 container.kind === 154 /* PropertyDeclaration */ ||
47373 container.kind === 153 /* PropertySignature */ ||
47374 container.kind === 157 /* Constructor */;
47375 }
47376 }
47377 }
47378 return false;
47379 }
47380 }
47381 function getContainingObjectLiteral(func) {
47382 return (func.kind === 156 /* MethodDeclaration */ ||
47383 func.kind === 158 /* GetAccessor */ ||
47384 func.kind === 159 /* SetAccessor */) && func.parent.kind === 188 /* ObjectLiteralExpression */ ? func.parent :
47385 func.kind === 196 /* FunctionExpression */ && func.parent.kind === 275 /* PropertyAssignment */ ? func.parent.parent :
47386 undefined;
47387 }
47388 function getThisTypeArgument(type) {
47389 return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined;
47390 }
47391 function getThisTypeFromContextualType(type) {
47392 return mapType(type, function (t) {
47393 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
47394 });
47395 }
47396 function getContextualThisParameterType(func) {
47397 if (func.kind === 197 /* ArrowFunction */) {
47398 return undefined;
47399 }
47400 if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
47401 var contextualSignature = getContextualSignature(func);
47402 if (contextualSignature) {
47403 var thisParameter = contextualSignature.thisParameter;
47404 if (thisParameter) {
47405 return getTypeOfSymbol(thisParameter);
47406 }
47407 }
47408 }
47409 var inJs = ts.isInJSFile(func);
47410 if (noImplicitThis || inJs) {
47411 var containingLiteral = getContainingObjectLiteral(func);
47412 if (containingLiteral) {
47413 // We have an object literal method. Check if the containing object literal has a contextual type
47414 // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
47415 // any directly enclosing object literals.
47416 var contextualType = getApparentTypeOfContextualType(containingLiteral);
47417 var literal = containingLiteral;
47418 var type = contextualType;
47419 while (type) {
47420 var thisType = getThisTypeFromContextualType(type);
47421 if (thisType) {
47422 return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
47423 }
47424 if (literal.parent.kind !== 275 /* PropertyAssignment */) {
47425 break;
47426 }
47427 literal = literal.parent.parent;
47428 type = getApparentTypeOfContextualType(literal);
47429 }
47430 // There was no contextual ThisType<T> for the containing object literal, so the contextual type
47431 // for 'this' is the non-null form of the contextual type for the containing object literal or
47432 // the type of the object literal itself.
47433 return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral);
47434 }
47435 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
47436 // contextual type for 'this' is 'obj'.
47437 var parent = func.parent;
47438 if (parent.kind === 204 /* BinaryExpression */ && parent.operatorToken.kind === 59 /* EqualsToken */) {
47439 var target = parent.left;
47440 if (target.kind === 189 /* PropertyAccessExpression */ || target.kind === 190 /* ElementAccessExpression */) {
47441 var expression = target.expression;
47442 // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
47443 if (inJs && ts.isIdentifier(expression)) {
47444 var sourceFile = ts.getSourceFileOfNode(parent);
47445 if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
47446 return undefined;
47447 }
47448 }
47449 return checkExpressionCached(expression);
47450 }
47451 }
47452 }
47453 return undefined;
47454 }
47455 // Return contextual type of parameter or undefined if no contextual type is available
47456 function getContextuallyTypedParameterType(parameter) {
47457 var func = parameter.parent;
47458 if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
47459 return undefined;
47460 }
47461 var iife = ts.getImmediatelyInvokedFunctionExpression(func);
47462 if (iife && iife.arguments) {
47463 var args = getEffectiveCallArguments(iife);
47464 var indexOfParameter = func.parameters.indexOf(parameter);
47465 if (parameter.dotDotDotToken) {
47466 return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined);
47467 }
47468 var links = getNodeLinks(iife);
47469 var cached = links.resolvedSignature;
47470 links.resolvedSignature = anySignature;
47471 var type = indexOfParameter < args.length ?
47472 getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
47473 parameter.initializer ? undefined : undefinedWideningType;
47474 links.resolvedSignature = cached;
47475 return type;
47476 }
47477 var contextualSignature = getContextualSignature(func);
47478 if (contextualSignature) {
47479 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
47480 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
47481 getRestTypeAtPosition(contextualSignature, index) :
47482 tryGetTypeAtPosition(contextualSignature, index);
47483 }
47484 }
47485 function getContextualTypeForVariableLikeDeclaration(declaration) {
47486 var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
47487 if (typeNode) {
47488 return getTypeFromTypeNode(typeNode);
47489 }
47490 switch (declaration.kind) {
47491 case 151 /* Parameter */:
47492 return getContextuallyTypedParameterType(declaration);
47493 case 186 /* BindingElement */:
47494 return getContextualTypeForBindingElement(declaration);
47495 // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent
47496 }
47497 }
47498 function getContextualTypeForBindingElement(declaration) {
47499 var parentDeclaration = declaration.parent.parent;
47500 var name = declaration.propertyName || declaration.name;
47501 var parentType = getContextualTypeForVariableLikeDeclaration(parentDeclaration);
47502 if (parentType && !ts.isBindingPattern(name) && !isComputedNonLiteralName(name)) {
47503 var nameType = getLiteralTypeFromPropertyName(name);
47504 if (isTypeUsableAsPropertyName(nameType)) {
47505 var text = getPropertyNameFromType(nameType);
47506 return getTypeOfPropertyOfType(parentType, text);
47507 }
47508 }
47509 }
47510 // In a variable, parameter or property declaration with a type annotation,
47511 // the contextual type of an initializer expression is the type of the variable, parameter or property.
47512 // Otherwise, in a parameter declaration of a contextually typed function expression,
47513 // the contextual type of an initializer expression is the contextual type of the parameter.
47514 // Otherwise, in a variable or parameter declaration with a binding pattern name,
47515 // the contextual type of an initializer expression is the type implied by the binding pattern.
47516 // Otherwise, in a binding pattern inside a variable or parameter declaration,
47517 // the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
47518 function getContextualTypeForInitializerExpression(node) {
47519 var declaration = node.parent;
47520 if (ts.hasInitializer(declaration) && node === declaration.initializer) {
47521 var result = getContextualTypeForVariableLikeDeclaration(declaration);
47522 if (result) {
47523 return result;
47524 }
47525 if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable
47526 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
47527 }
47528 }
47529 return undefined;
47530 }
47531 function getContextualTypeForReturnExpression(node) {
47532 var func = ts.getContainingFunction(node);
47533 if (func) {
47534 var functionFlags = ts.getFunctionFlags(func);
47535 if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
47536 return undefined;
47537 }
47538 var contextualReturnType = getContextualReturnType(func);
47539 if (contextualReturnType) {
47540 if (functionFlags & 2 /* Async */) { // Async function
47541 var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType);
47542 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
47543 }
47544 return contextualReturnType; // Regular function
47545 }
47546 }
47547 return undefined;
47548 }
47549 function getContextualTypeForAwaitOperand(node) {
47550 var contextualType = getContextualType(node);
47551 if (contextualType) {
47552 var contextualAwaitedType = getAwaitedType(contextualType);
47553 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
47554 }
47555 return undefined;
47556 }
47557 function getContextualTypeForYieldOperand(node) {
47558 var func = ts.getContainingFunction(node);
47559 if (func) {
47560 var functionFlags = ts.getFunctionFlags(func);
47561 var contextualReturnType = getContextualReturnType(func);
47562 if (contextualReturnType) {
47563 return node.asteriskToken
47564 ? contextualReturnType
47565 : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
47566 }
47567 }
47568 return undefined;
47569 }
47570 function isInParameterInitializerBeforeContainingFunction(node) {
47571 var inBindingInitializer = false;
47572 while (node.parent && !ts.isFunctionLike(node.parent)) {
47573 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
47574 return true;
47575 }
47576 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
47577 inBindingInitializer = true;
47578 }
47579 node = node.parent;
47580 }
47581 return false;
47582 }
47583 function getContextualReturnType(functionDecl) {
47584 // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
47585 // corresponding set accessor has a type annotation, return statements in the function are contextually typed
47586 var returnType = getReturnTypeFromAnnotation(functionDecl);
47587 if (returnType) {
47588 return returnType;
47589 }
47590 // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
47591 // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
47592 var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
47593 if (signature && !isResolvingReturnTypeOfSignature(signature)) {
47594 return getReturnTypeOfSignature(signature);
47595 }
47596 return undefined;
47597 }
47598 // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
47599 function getContextualTypeForArgument(callTarget, arg) {
47600 var args = getEffectiveCallArguments(callTarget);
47601 var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
47602 return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
47603 }
47604 function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
47605 // If we're already in the process of resolving the given signature, don't resolve again as
47606 // that could cause infinite recursion. Instead, return anySignature.
47607 var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
47608 if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
47609 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
47610 }
47611 return getTypeAtPosition(signature, argIndex);
47612 }
47613 function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
47614 if (template.parent.kind === 193 /* TaggedTemplateExpression */) {
47615 return getContextualTypeForArgument(template.parent, substitutionExpression);
47616 }
47617 return undefined;
47618 }
47619 function getContextualTypeForBinaryOperand(node) {
47620 var binaryExpression = node.parent;
47621 var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
47622 switch (operatorToken.kind) {
47623 case 59 /* EqualsToken */:
47624 if (node !== right) {
47625 return undefined;
47626 }
47627 var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
47628 if (!contextSensitive) {
47629 return undefined;
47630 }
47631 return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
47632 case 55 /* BarBarToken */:
47633 // When an || expression has a contextual type, the operands are contextually typed by that type. When an ||
47634 // expression has no contextual type, the right operand is contextually typed by the type of the left operand,
47635 // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}`
47636 var type = getContextualType(binaryExpression);
47637 return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ?
47638 getTypeOfExpression(left) : type;
47639 case 54 /* AmpersandAmpersandToken */:
47640 case 27 /* CommaToken */:
47641 return node === right ? getContextualType(binaryExpression) : undefined;
47642 default:
47643 return undefined;
47644 }
47645 }
47646 // In an assignment expression, the right operand is contextually typed by the type of the left operand.
47647 // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
47648 function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
47649 var kind = ts.getAssignmentDeclarationKind(binaryExpression);
47650 switch (kind) {
47651 case 0 /* None */:
47652 return true;
47653 case 5 /* Property */:
47654 case 1 /* ExportsProperty */:
47655 case 6 /* Prototype */:
47656 case 3 /* PrototypeProperty */:
47657 // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
47658 // See `bindStaticPropertyAssignment` in `binder.ts`.
47659 if (!binaryExpression.left.symbol) {
47660 return true;
47661 }
47662 else {
47663 var decl = binaryExpression.left.symbol.valueDeclaration;
47664 if (!decl) {
47665 return false;
47666 }
47667 var lhs = binaryExpression.left;
47668 var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
47669 if (overallAnnotation) {
47670 return getTypeFromTypeNode(overallAnnotation);
47671 }
47672 else if (ts.isIdentifier(lhs.expression)) {
47673 var id = lhs.expression;
47674 var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true);
47675 if (parentSymbol) {
47676 var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
47677 if (annotated) {
47678 var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText);
47679 return type || false;
47680 }
47681 return false;
47682 }
47683 }
47684 return !ts.isInJSFile(decl);
47685 }
47686 case 2 /* ModuleExports */:
47687 case 4 /* ThisProperty */:
47688 if (!binaryExpression.symbol)
47689 return true;
47690 if (binaryExpression.symbol.valueDeclaration) {
47691 var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
47692 if (annotated) {
47693 var type = getTypeFromTypeNode(annotated);
47694 if (type) {
47695 return type;
47696 }
47697 }
47698 }
47699 if (kind === 2 /* ModuleExports */)
47700 return false;
47701 var thisAccess = binaryExpression.left;
47702 if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
47703 return false;
47704 }
47705 var thisType = checkThisExpression(thisAccess.expression);
47706 return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false;
47707 case 7 /* ObjectDefinePropertyValue */:
47708 case 8 /* ObjectDefinePropertyExports */:
47709 case 9 /* ObjectDefinePrototypeProperty */:
47710 return ts.Debug.fail("Does not apply");
47711 default:
47712 return ts.Debug.assertNever(kind);
47713 }
47714 }
47715 function getTypeOfPropertyOfContextualType(type, name) {
47716 return mapType(type, function (t) {
47717 if (isGenericMappedType(t)) {
47718 var constraint = getConstraintTypeFromMappedType(t);
47719 var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
47720 var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
47721 if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
47722 return substituteIndexedMappedType(t, propertyNameType);
47723 }
47724 }
47725 else if (t.flags & 3670016 /* StructuredType */) {
47726 var prop = getPropertyOfType(t, name);
47727 if (prop) {
47728 return getTypeOfSymbol(prop);
47729 }
47730 if (isTupleType(t)) {
47731 var restType = getRestTypeOfTupleType(t);
47732 if (restType && isNumericLiteralName(name) && +name >= 0) {
47733 return restType;
47734 }
47735 }
47736 return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
47737 getIndexTypeOfContextualType(t, 0 /* String */);
47738 }
47739 return undefined;
47740 }, /*noReductions*/ true);
47741 }
47742 function getIndexTypeOfContextualType(type, kind) {
47743 return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
47744 }
47745 // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
47746 // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
47747 // exists. Otherwise, it is the type of the string index signature in T, if one exists.
47748 function getContextualTypeForObjectLiteralMethod(node) {
47749 ts.Debug.assert(ts.isObjectLiteralMethod(node));
47750 if (node.flags & 8388608 /* InWithStatement */) {
47751 // We cannot answer semantic questions within a with block, do not proceed any further
47752 return undefined;
47753 }
47754 return getContextualTypeForObjectLiteralElement(node);
47755 }
47756 function getContextualTypeForObjectLiteralElement(element) {
47757 var objectLiteral = element.parent;
47758 var type = getApparentTypeOfContextualType(objectLiteral);
47759 if (type) {
47760 if (!hasNonBindableDynamicName(element)) {
47761 // For a (non-symbol) computed property, there is no reason to look up the name
47762 // in the type. It will just be "__computed", which does not appear in any
47763 // SymbolTable.
47764 var symbolName_2 = getSymbolOfNode(element).escapedName;
47765 var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2);
47766 if (propertyType) {
47767 return propertyType;
47768 }
47769 }
47770 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
47771 getIndexTypeOfContextualType(type, 0 /* String */);
47772 }
47773 return undefined;
47774 }
47775 // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
47776 // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
47777 // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
47778 // type of T.
47779 function getContextualTypeForElementExpression(arrayContextualType, index) {
47780 return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
47781 || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false));
47782 }
47783 // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
47784 function getContextualTypeForConditionalOperand(node) {
47785 var conditional = node.parent;
47786 return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined;
47787 }
47788 function getContextualTypeForChildJsxExpression(node, child) {
47789 var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
47790 // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
47791 var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
47792 if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
47793 return undefined;
47794 }
47795 var childIndex = node.children.indexOf(child);
47796 var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
47797 return childFieldType && mapType(childFieldType, function (t) {
47798 if (isArrayLikeType(t)) {
47799 return getIndexedAccessType(t, getLiteralType(childIndex));
47800 }
47801 else {
47802 return t;
47803 }
47804 }, /*noReductions*/ true);
47805 }
47806 function getContextualTypeForJsxExpression(node) {
47807 var exprParent = node.parent;
47808 return ts.isJsxAttributeLike(exprParent)
47809 ? getContextualType(node)
47810 : ts.isJsxElement(exprParent)
47811 ? getContextualTypeForChildJsxExpression(exprParent, node)
47812 : undefined;
47813 }
47814 function getContextualTypeForJsxAttribute(attribute) {
47815 // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
47816 // which is a type of the parameter of the signature we are trying out.
47817 // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
47818 if (ts.isJsxAttribute(attribute)) {
47819 var attributesType = getApparentTypeOfContextualType(attribute.parent);
47820 if (!attributesType || isTypeAny(attributesType)) {
47821 return undefined;
47822 }
47823 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
47824 }
47825 else {
47826 return getContextualType(attribute.parent);
47827 }
47828 }
47829 // Return true if the given expression is possibly a discriminant value. We limit the kinds of
47830 // expressions we check to those that don't depend on their contextual type in order not to cause
47831 // recursive (and possibly infinite) invocations of getContextualType.
47832 function isPossiblyDiscriminantValue(node) {
47833 switch (node.kind) {
47834 case 10 /* StringLiteral */:
47835 case 8 /* NumericLiteral */:
47836 case 9 /* BigIntLiteral */:
47837 case 14 /* NoSubstitutionTemplateLiteral */:
47838 case 102 /* TrueKeyword */:
47839 case 87 /* FalseKeyword */:
47840 case 96 /* NullKeyword */:
47841 case 72 /* Identifier */:
47842 case 141 /* UndefinedKeyword */:
47843 return true;
47844 case 189 /* PropertyAccessExpression */:
47845 case 195 /* ParenthesizedExpression */:
47846 return isPossiblyDiscriminantValue(node.expression);
47847 case 270 /* JsxExpression */:
47848 return !node.expression || isPossiblyDiscriminantValue(node.expression);
47849 }
47850 return false;
47851 }
47852 function discriminateContextualTypeByObjectMembers(node, contextualType) {
47853 return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 275 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
47854 }
47855 function discriminateContextualTypeByJSXAttributes(node, contextualType) {
47856 return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
47857 }
47858 // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
47859 // be "pushed" onto a node using the contextualType property.
47860 function getApparentTypeOfContextualType(node) {
47861 var contextualType = instantiateContextualType(getContextualType(node), node);
47862 if (contextualType) {
47863 var apparentType = mapType(contextualType, getApparentType, /*noReductions*/ true);
47864 if (apparentType.flags & 1048576 /* Union */) {
47865 if (ts.isObjectLiteralExpression(node)) {
47866 return discriminateContextualTypeByObjectMembers(node, apparentType);
47867 }
47868 else if (ts.isJsxAttributes(node)) {
47869 return discriminateContextualTypeByJSXAttributes(node, apparentType);
47870 }
47871 }
47872 return apparentType;
47873 }
47874 }
47875 // If the given contextual type contains instantiable types and if a mapper representing
47876 // return type inferences is available, instantiate those types using that mapper.
47877 function instantiateContextualType(contextualType, node) {
47878 if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
47879 var inferenceContext = getInferenceContext(node);
47880 if (inferenceContext && inferenceContext.returnMapper) {
47881 return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
47882 }
47883 }
47884 return contextualType;
47885 }
47886 // This function is similar to instantiateType, except that (a) it only instantiates types that
47887 // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
47888 // no reductions on instantiated union types.
47889 function instantiateInstantiableTypes(type, mapper) {
47890 if (type.flags & 63176704 /* Instantiable */) {
47891 return instantiateType(type, mapper);
47892 }
47893 if (type.flags & 1048576 /* Union */) {
47894 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
47895 }
47896 if (type.flags & 2097152 /* Intersection */) {
47897 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
47898 }
47899 return type;
47900 }
47901 /**
47902 * Woah! Do you really want to use this function?
47903 *
47904 * Unless you're trying to get the *non-apparent* type for a
47905 * value-literal type or you're authoring relevant portions of this algorithm,
47906 * you probably meant to use 'getApparentTypeOfContextualType'.
47907 * Otherwise this may not be very useful.
47908 *
47909 * In cases where you *are* working on this function, you should understand
47910 * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
47911 *
47912 * - Use 'getContextualType' when you are simply going to propagate the result to the expression.
47913 * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
47914 *
47915 * @param node the expression whose contextual type will be returned.
47916 * @returns the contextual type of an expression.
47917 */
47918 function getContextualType(node) {
47919 if (node.flags & 8388608 /* InWithStatement */) {
47920 // We cannot answer semantic questions within a with block, do not proceed any further
47921 return undefined;
47922 }
47923 if (node.contextualType) {
47924 return node.contextualType;
47925 }
47926 var parent = node.parent;
47927 switch (parent.kind) {
47928 case 237 /* VariableDeclaration */:
47929 case 151 /* Parameter */:
47930 case 154 /* PropertyDeclaration */:
47931 case 153 /* PropertySignature */:
47932 case 186 /* BindingElement */:
47933 return getContextualTypeForInitializerExpression(node);
47934 case 197 /* ArrowFunction */:
47935 case 230 /* ReturnStatement */:
47936 return getContextualTypeForReturnExpression(node);
47937 case 207 /* YieldExpression */:
47938 return getContextualTypeForYieldOperand(parent);
47939 case 201 /* AwaitExpression */:
47940 return getContextualTypeForAwaitOperand(parent);
47941 case 191 /* CallExpression */:
47942 case 192 /* NewExpression */:
47943 return getContextualTypeForArgument(parent, node);
47944 case 194 /* TypeAssertionExpression */:
47945 case 212 /* AsExpression */:
47946 return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
47947 case 204 /* BinaryExpression */:
47948 return getContextualTypeForBinaryOperand(node);
47949 case 275 /* PropertyAssignment */:
47950 case 276 /* ShorthandPropertyAssignment */:
47951 return getContextualTypeForObjectLiteralElement(parent);
47952 case 277 /* SpreadAssignment */:
47953 return getApparentTypeOfContextualType(parent.parent);
47954 case 187 /* ArrayLiteralExpression */: {
47955 var arrayLiteral = parent;
47956 var type = getApparentTypeOfContextualType(arrayLiteral);
47957 return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
47958 }
47959 case 205 /* ConditionalExpression */:
47960 return getContextualTypeForConditionalOperand(node);
47961 case 216 /* TemplateSpan */:
47962 ts.Debug.assert(parent.parent.kind === 206 /* TemplateExpression */);
47963 return getContextualTypeForSubstitutionExpression(parent.parent, node);
47964 case 195 /* ParenthesizedExpression */: {
47965 // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
47966 var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
47967 return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent);
47968 }
47969 case 270 /* JsxExpression */:
47970 return getContextualTypeForJsxExpression(parent);
47971 case 267 /* JsxAttribute */:
47972 case 269 /* JsxSpreadAttribute */:
47973 return getContextualTypeForJsxAttribute(parent);
47974 case 262 /* JsxOpeningElement */:
47975 case 261 /* JsxSelfClosingElement */:
47976 return getContextualJsxElementAttributesType(parent);
47977 }
47978 return undefined;
47979 }
47980 function getInferenceContext(node) {
47981 var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
47982 return ancestor && ancestor.inferenceContext;
47983 }
47984 function getContextualJsxElementAttributesType(node) {
47985 if (ts.isJsxOpeningElement(node) && node.parent.contextualType) {
47986 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
47987 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
47988 // (as below) instead!
47989 return node.parent.contextualType;
47990 }
47991 return getContextualTypeForArgumentAtIndex(node, 0);
47992 }
47993 function getEffectiveFirstArgumentForJsxSignature(signature, node) {
47994 return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node);
47995 }
47996 function getJsxPropsTypeFromCallSignature(sig, context) {
47997 var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType);
47998 propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
47999 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
48000 if (intrinsicAttribs !== errorType) {
48001 propsType = intersectTypes(intrinsicAttribs, propsType);
48002 }
48003 return propsType;
48004 }
48005 function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
48006 if (sig.unionSignatures) {
48007 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
48008 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
48009 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
48010 // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input.
48011 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
48012 var results = [];
48013 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
48014 var signature = _a[_i];
48015 var instance = getReturnTypeOfSignature(signature);
48016 if (isTypeAny(instance)) {
48017 return instance;
48018 }
48019 var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
48020 if (!propType) {
48021 return;
48022 }
48023 results.push(propType);
48024 }
48025 return getIntersectionType(results);
48026 }
48027 var instanceType = getReturnTypeOfSignature(sig);
48028 return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
48029 }
48030 function getStaticTypeOfReferencedJsxConstructor(context) {
48031 if (isJsxIntrinsicIdentifier(context.tagName)) {
48032 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
48033 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
48034 return getOrCreateTypeFromSignature(fakeSignature);
48035 }
48036 var tagType = checkExpressionCached(context.tagName);
48037 if (tagType.flags & 128 /* StringLiteral */) {
48038 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
48039 if (!result) {
48040 return errorType;
48041 }
48042 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
48043 return getOrCreateTypeFromSignature(fakeSignature);
48044 }
48045 return tagType;
48046 }
48047 function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
48048 var managedSym = getJsxLibraryManagedAttributes(ns);
48049 if (managedSym) {
48050 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
48051 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
48052 if (ts.length(declaredManagedType.typeParameters) >= 2) {
48053 var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
48054 return createTypeReference(declaredManagedType, args);
48055 }
48056 else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
48057 var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
48058 return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
48059 }
48060 }
48061 return attributesType;
48062 }
48063 function getJsxPropsTypeFromClassType(sig, context) {
48064 var ns = getJsxNamespaceAt(context);
48065 var forcedLookupLocation = getJsxElementPropertiesName(ns);
48066 var attributesType = forcedLookupLocation === undefined
48067 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
48068 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType)
48069 : forcedLookupLocation === ""
48070 // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
48071 ? getReturnTypeOfSignature(sig)
48072 // Otherwise get the type of the property on the signature return type
48073 : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
48074 if (!attributesType) {
48075 // There is no property named 'props' on this instance type
48076 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
48077 error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
48078 }
48079 return emptyObjectType;
48080 }
48081 attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
48082 if (isTypeAny(attributesType)) {
48083 // Props is of type 'any' or unknown
48084 return attributesType;
48085 }
48086 else {
48087 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
48088 var apparentAttributesType = attributesType;
48089 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
48090 if (intrinsicClassAttribs !== errorType) {
48091 var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
48092 var hostClassType = getReturnTypeOfSignature(sig);
48093 apparentAttributesType = intersectTypes(typeParams
48094 ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
48095 : intrinsicClassAttribs, apparentAttributesType);
48096 }
48097 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
48098 if (intrinsicAttribs !== errorType) {
48099 apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
48100 }
48101 return apparentAttributesType;
48102 }
48103 }
48104 // If the given type is an object or union type with a single signature, and if that signature has at
48105 // least as many parameters as the given function, return the signature. Otherwise return undefined.
48106 function getContextualCallSignature(type, node) {
48107 var signatures = getSignaturesOfType(type, 0 /* Call */);
48108 if (signatures.length === 1) {
48109 var signature = signatures[0];
48110 if (!isAritySmaller(signature, node)) {
48111 return signature;
48112 }
48113 }
48114 }
48115 /** If the contextual signature has fewer parameters than the function expression, do not use it */
48116 function isAritySmaller(signature, target) {
48117 var targetParameterCount = 0;
48118 for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
48119 var param = target.parameters[targetParameterCount];
48120 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
48121 break;
48122 }
48123 }
48124 if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
48125 targetParameterCount--;
48126 }
48127 return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
48128 }
48129 function isFunctionExpressionOrArrowFunction(node) {
48130 return node.kind === 196 /* FunctionExpression */ || node.kind === 197 /* ArrowFunction */;
48131 }
48132 function getContextualSignatureForFunctionLikeDeclaration(node) {
48133 // Only function expressions, arrow functions, and object literal methods are contextually typed.
48134 return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
48135 ? getContextualSignature(node)
48136 : undefined;
48137 }
48138 function getContextualTypeForFunctionLikeDeclaration(node) {
48139 return ts.isObjectLiteralMethod(node) ?
48140 getContextualTypeForObjectLiteralMethod(node) :
48141 getApparentTypeOfContextualType(node);
48142 }
48143 // Return the contextual signature for a given expression node. A contextual type provides a
48144 // contextual signature if it has a single call signature and if that call signature is non-generic.
48145 // If the contextual type is a union type, get the signature from each type possible and if they are
48146 // all identical ignoring their return type, the result is same signature but with return type as
48147 // union type of return types from these signatures
48148 function getContextualSignature(node) {
48149 ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
48150 var typeTagSignature = getSignatureOfTypeTag(node);
48151 if (typeTagSignature) {
48152 return typeTagSignature;
48153 }
48154 var type = getContextualTypeForFunctionLikeDeclaration(node);
48155 if (!type) {
48156 return undefined;
48157 }
48158 if (!(type.flags & 1048576 /* Union */)) {
48159 return getContextualCallSignature(type, node);
48160 }
48161 var signatureList;
48162 var types = type.types;
48163 for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
48164 var current = types_15[_i];
48165 var signature = getContextualCallSignature(current, node);
48166 if (signature) {
48167 if (!signatureList) {
48168 // This signature will contribute to contextual union signature
48169 signatureList = [signature];
48170 }
48171 else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
48172 // Signatures aren't identical, do not use
48173 return undefined;
48174 }
48175 else {
48176 // Use this signature for contextual union signature
48177 signatureList.push(signature);
48178 }
48179 }
48180 }
48181 // Result is union of signatures collected (return type is union of return types of this signature set)
48182 return signatureList && createUnionSignature(signatureList[0], signatureList);
48183 }
48184 function checkSpreadExpression(node, checkMode) {
48185 if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
48186 checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */);
48187 }
48188 var arrayOrIterableType = checkExpression(node.expression, checkMode);
48189 return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false);
48190 }
48191 function hasDefaultValue(node) {
48192 return (node.kind === 186 /* BindingElement */ && !!node.initializer) ||
48193 (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 59 /* EqualsToken */);
48194 }
48195 function checkArrayLiteral(node, checkMode, forceTuple) {
48196 var elements = node.elements;
48197 var elementCount = elements.length;
48198 var hasNonEndingSpreadElement = false;
48199 var elementTypes = [];
48200 var inDestructuringPattern = ts.isAssignmentTarget(node);
48201 var contextualType = getApparentTypeOfContextualType(node);
48202 var inConstContext = isConstContext(node);
48203 for (var index = 0; index < elementCount; index++) {
48204 var e = elements[index];
48205 if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) {
48206 // Given the following situation:
48207 // var c: {};
48208 // [...c] = ["", 0];
48209 //
48210 // c is represented in the tree as a spread element in an array literal.
48211 // But c really functions as a rest element, and its purpose is to provide
48212 // a contextual type for the right hand side of the assignment. Therefore,
48213 // instead of calling checkExpression on "...c", which will give an error
48214 // if c is not iterable/array-like, we need to act as if we are trying to
48215 // get the contextual element type from it. So we do something similar to
48216 // getContextualTypeForElementExpression, which will crucially not error
48217 // if there is no index type / iterated type.
48218 var restArrayType = checkExpression(e.expression, checkMode, forceTuple);
48219 var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) ||
48220 getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false);
48221 if (restElementType) {
48222 elementTypes.push(restElementType);
48223 }
48224 }
48225 else {
48226 var elementContextualType = getContextualTypeForElementExpression(contextualType, index);
48227 var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
48228 elementTypes.push(type);
48229 }
48230 if (index < elementCount - 1 && e.kind === 208 /* SpreadElement */) {
48231 hasNonEndingSpreadElement = true;
48232 }
48233 }
48234 if (!hasNonEndingSpreadElement) {
48235 var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 208 /* SpreadElement */;
48236 var minLength = elementCount - (hasRestElement ? 1 : 0);
48237 // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
48238 // that we get the same behavior for "var [x, y] = []" and "[x, y] = []".
48239 var tupleResult = void 0;
48240 if (inDestructuringPattern && minLength > 0) {
48241 var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement));
48242 type.pattern = node;
48243 return type;
48244 }
48245 else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) {
48246 return tupleResult;
48247 }
48248 else if (forceTuple) {
48249 return createTupleType(elementTypes, minLength, hasRestElement);
48250 }
48251 }
48252 return createArrayType(elementTypes.length ?
48253 getUnionType(elementTypes, 2 /* Subtype */) :
48254 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext);
48255 }
48256 function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
48257 if (elementCount === void 0) { elementCount = elementTypes.length; }
48258 if (readonly === void 0) { readonly = false; }
48259 // Infer a tuple type when the contextual type is or contains a tuple-like type
48260 if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
48261 var minLength = elementCount - (hasRestElement ? 1 : 0);
48262 var pattern = contextualType && contextualType.pattern;
48263 // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting
48264 // tuple type with the corresponding binding or assignment element types to make the lengths equal.
48265 if (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) {
48266 var patternElements = pattern.elements;
48267 for (var i = elementCount; i < patternElements.length; i++) {
48268 var e = patternElements[i];
48269 if (hasDefaultValue(e)) {
48270 elementTypes.push(contextualType.typeArguments[i]);
48271 }
48272 else if (i < patternElements.length - 1 || !(e.kind === 186 /* BindingElement */ && e.dotDotDotToken || e.kind === 208 /* SpreadElement */)) {
48273 if (e.kind !== 210 /* OmittedExpression */) {
48274 error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
48275 }
48276 elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType);
48277 }
48278 }
48279 }
48280 return createTupleType(elementTypes, minLength, hasRestElement, readonly);
48281 }
48282 }
48283 function isNumericName(name) {
48284 switch (name.kind) {
48285 case 149 /* ComputedPropertyName */:
48286 return isNumericComputedName(name);
48287 case 72 /* Identifier */:
48288 return isNumericLiteralName(name.escapedText);
48289 case 8 /* NumericLiteral */:
48290 case 10 /* StringLiteral */:
48291 return isNumericLiteralName(name.text);
48292 default:
48293 return false;
48294 }
48295 }
48296 function isNumericComputedName(name) {
48297 // It seems odd to consider an expression of type Any to result in a numeric name,
48298 // but this behavior is consistent with checkIndexedAccess
48299 return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
48300 }
48301 function isInfinityOrNaNString(name) {
48302 return name === "Infinity" || name === "-Infinity" || name === "NaN";
48303 }
48304 function isNumericLiteralName(name) {
48305 // The intent of numeric names is that
48306 // - they are names with text in a numeric form, and that
48307 // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
48308 // acquired by applying the abstract 'ToNumber' operation on the name's text.
48309 //
48310 // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
48311 // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
48312 //
48313 // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
48314 // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
48315 // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
48316 // because their 'ToString' representation is not equal to their original text.
48317 // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
48318 //
48319 // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
48320 // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
48321 // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
48322 //
48323 // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
48324 // This is desired behavior, because when indexing with them as numeric entities, you are indexing
48325 // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
48326 return (+name).toString() === name;
48327 }
48328 function checkComputedPropertyName(node) {
48329 var links = getNodeLinks(node.expression);
48330 if (!links.resolvedType) {
48331 links.resolvedType = checkExpression(node.expression);
48332 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
48333 // type, and any union of these types (like string | number).
48334 if (links.resolvedType.flags & 98304 /* Nullable */ ||
48335 !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
48336 !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
48337 error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
48338 }
48339 else {
48340 checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
48341 }
48342 }
48343 return links.resolvedType;
48344 }
48345 function getObjectLiteralIndexInfo(node, offset, properties, kind) {
48346 var propTypes = [];
48347 for (var i = 0; i < properties.length; i++) {
48348 if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
48349 propTypes.push(getTypeOfSymbol(properties[i]));
48350 }
48351 }
48352 var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
48353 return createIndexInfo(unionType, isConstContext(node));
48354 }
48355 function getImmediateAliasedSymbol(symbol) {
48356 ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
48357 var links = getSymbolLinks(symbol);
48358 if (!links.immediateTarget) {
48359 var node = getDeclarationOfAliasSymbol(symbol);
48360 if (!node)
48361 return ts.Debug.fail();
48362 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
48363 }
48364 return links.immediateTarget;
48365 }
48366 function checkObjectLiteral(node, checkMode) {
48367 var inDestructuringPattern = ts.isAssignmentTarget(node);
48368 // Grammar checking
48369 checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
48370 var propertiesTable;
48371 var propertiesArray = [];
48372 var spread = emptyObjectType;
48373 var contextualType = getApparentTypeOfContextualType(node);
48374 var contextualTypeHasPattern = contextualType && contextualType.pattern &&
48375 (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */);
48376 var inConstContext = isConstContext(node);
48377 var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
48378 var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
48379 var enumTag = ts.getJSDocEnumTag(node);
48380 var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
48381 var objectFlags = freshObjectLiteralFlag;
48382 var patternWithComputedProperties = false;
48383 var hasComputedStringProperty = false;
48384 var hasComputedNumberProperty = false;
48385 propertiesTable = ts.createSymbolTable();
48386 var offset = 0;
48387 for (var i = 0; i < node.properties.length; i++) {
48388 var memberDecl = node.properties[i];
48389 var member = getSymbolOfNode(memberDecl);
48390 var computedNameType = memberDecl.name && memberDecl.name.kind === 149 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
48391 checkComputedPropertyName(memberDecl.name) : undefined;
48392 if (memberDecl.kind === 275 /* PropertyAssignment */ ||
48393 memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ||
48394 ts.isObjectLiteralMethod(memberDecl)) {
48395 var type = memberDecl.kind === 275 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
48396 memberDecl.kind === 276 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) :
48397 checkObjectLiteralMethod(memberDecl, checkMode);
48398 if (isInJavascript) {
48399 var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
48400 if (jsDocType) {
48401 checkTypeAssignableTo(type, jsDocType, memberDecl);
48402 type = jsDocType;
48403 }
48404 else if (enumTag && enumTag.typeExpression) {
48405 checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
48406 }
48407 }
48408 objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */;
48409 var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
48410 var prop = nameType ?
48411 createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 2048 /* Late */) :
48412 createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
48413 if (nameType) {
48414 prop.nameType = nameType;
48415 }
48416 if (inDestructuringPattern) {
48417 // If object literal is an assignment pattern and if the assignment pattern specifies a default value
48418 // for the property, make the property optional.
48419 var isOptional = (memberDecl.kind === 275 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
48420 (memberDecl.kind === 276 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
48421 if (isOptional) {
48422 prop.flags |= 16777216 /* Optional */;
48423 }
48424 }
48425 else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
48426 // If object literal is contextually typed by the implied type of a binding pattern, and if the
48427 // binding pattern specifies a default value for the property, make the property optional.
48428 var impliedProp = getPropertyOfType(contextualType, member.escapedName);
48429 if (impliedProp) {
48430 prop.flags |= impliedProp.flags & 16777216 /* Optional */;
48431 }
48432 else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
48433 error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
48434 }
48435 }
48436 prop.declarations = member.declarations;
48437 prop.parent = member.parent;
48438 if (member.valueDeclaration) {
48439 prop.valueDeclaration = member.valueDeclaration;
48440 }
48441 prop.type = type;
48442 prop.target = member;
48443 member = prop;
48444 }
48445 else if (memberDecl.kind === 277 /* SpreadAssignment */) {
48446 if (languageVersion < 2 /* ES2015 */) {
48447 checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
48448 }
48449 if (propertiesArray.length > 0) {
48450 spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
48451 propertiesArray = [];
48452 propertiesTable = ts.createSymbolTable();
48453 hasComputedStringProperty = false;
48454 hasComputedNumberProperty = false;
48455 }
48456 var type = checkExpression(memberDecl.expression);
48457 if (!isValidSpreadType(type)) {
48458 error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
48459 return errorType;
48460 }
48461 spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
48462 offset = i + 1;
48463 continue;
48464 }
48465 else {
48466 // TypeScript 1.0 spec (April 2014)
48467 // A get accessor declaration is processed in the same manner as
48468 // an ordinary function declaration(section 6.1) with no parameters.
48469 // A set accessor declaration is processed in the same manner
48470 // as an ordinary function declaration with a single parameter and a Void return type.
48471 ts.Debug.assert(memberDecl.kind === 158 /* GetAccessor */ || memberDecl.kind === 159 /* SetAccessor */);
48472 checkNodeDeferred(memberDecl);
48473 }
48474 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
48475 if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
48476 if (isTypeAssignableTo(computedNameType, numberType)) {
48477 hasComputedNumberProperty = true;
48478 }
48479 else {
48480 hasComputedStringProperty = true;
48481 }
48482 if (inDestructuringPattern) {
48483 patternWithComputedProperties = true;
48484 }
48485 }
48486 }
48487 else {
48488 propertiesTable.set(member.escapedName, member);
48489 }
48490 propertiesArray.push(member);
48491 }
48492 // If object literal is contextually typed by the implied type of a binding pattern, augment the result
48493 // type with those properties for which the binding pattern specifies a default value.
48494 if (contextualTypeHasPattern) {
48495 for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) {
48496 var prop = _a[_i];
48497 if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) {
48498 if (!(prop.flags & 16777216 /* Optional */)) {
48499 error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
48500 }
48501 propertiesTable.set(prop.escapedName, prop);
48502 propertiesArray.push(prop);
48503 }
48504 }
48505 }
48506 if (spread !== emptyObjectType) {
48507 if (propertiesArray.length > 0) {
48508 spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
48509 }
48510 return spread;
48511 }
48512 return createObjectLiteralType();
48513 function createObjectLiteralType() {
48514 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
48515 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
48516 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
48517 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
48518 if (isJSObjectLiteral) {
48519 result.objectFlags |= 16384 /* JSLiteral */;
48520 }
48521 if (patternWithComputedProperties) {
48522 result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
48523 }
48524 if (inDestructuringPattern) {
48525 result.pattern = node;
48526 }
48527 return result;
48528 }
48529 }
48530 function isValidSpreadType(type) {
48531 return !!(type.flags & (3 /* AnyOrUnknown */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
48532 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
48533 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
48534 }
48535 function checkJsxSelfClosingElementDeferred(node) {
48536 checkJsxOpeningLikeElementOrOpeningFragment(node);
48537 }
48538 function checkJsxSelfClosingElement(node, _checkMode) {
48539 checkNodeDeferred(node);
48540 return getJsxElementTypeAt(node) || anyType;
48541 }
48542 function checkJsxElementDeferred(node) {
48543 // Check attributes
48544 checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
48545 // Perform resolution on the closing tag so that rename/go to definition/etc work
48546 if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
48547 getIntrinsicTagSymbol(node.closingElement);
48548 }
48549 else {
48550 checkExpression(node.closingElement.tagName);
48551 }
48552 checkJsxChildren(node);
48553 }
48554 function checkJsxElement(node, _checkMode) {
48555 checkNodeDeferred(node);
48556 return getJsxElementTypeAt(node) || anyType;
48557 }
48558 function checkJsxFragment(node) {
48559 checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
48560 if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
48561 error(node, compilerOptions.jsxFactory
48562 ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
48563 : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
48564 }
48565 checkJsxChildren(node);
48566 return getJsxElementTypeAt(node) || anyType;
48567 }
48568 /**
48569 * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
48570 */
48571 function isUnhyphenatedJsxName(name) {
48572 // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
48573 return !ts.stringContains(name, "-");
48574 }
48575 /**
48576 * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
48577 */
48578 function isJsxIntrinsicIdentifier(tagName) {
48579 return tagName.kind === 72 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
48580 }
48581 function checkJsxAttribute(node, checkMode) {
48582 return node.initializer
48583 ? checkExpressionForMutableLocation(node.initializer, checkMode)
48584 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
48585 }
48586 /**
48587 * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
48588 *
48589 * @param openingLikeElement a JSX opening-like element
48590 * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
48591 * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
48592 * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
48593 * which also calls getSpreadType.
48594 */
48595 function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
48596 var attributes = openingLikeElement.attributes;
48597 var attributesTable = ts.createSymbolTable();
48598 var spread = emptyJsxObjectType;
48599 var hasSpreadAnyType = false;
48600 var typeToIntersect;
48601 var explicitlySpecifyChildrenAttribute = false;
48602 var objectFlags = 4096 /* JsxAttributes */;
48603 var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
48604 for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
48605 var attributeDecl = _a[_i];
48606 var member = attributeDecl.symbol;
48607 if (ts.isJsxAttribute(attributeDecl)) {
48608 var exprType = checkJsxAttribute(attributeDecl, checkMode);
48609 objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */;
48610 var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
48611 attributeSymbol.declarations = member.declarations;
48612 attributeSymbol.parent = member.parent;
48613 if (member.valueDeclaration) {
48614 attributeSymbol.valueDeclaration = member.valueDeclaration;
48615 }
48616 attributeSymbol.type = exprType;
48617 attributeSymbol.target = member;
48618 attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
48619 if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
48620 explicitlySpecifyChildrenAttribute = true;
48621 }
48622 }
48623 else {
48624 ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */);
48625 if (attributesTable.size > 0) {
48626 spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
48627 attributesTable = ts.createSymbolTable();
48628 }
48629 var exprType = checkExpressionCached(attributeDecl.expression, checkMode);
48630 if (isTypeAny(exprType)) {
48631 hasSpreadAnyType = true;
48632 }
48633 if (isValidSpreadType(exprType)) {
48634 spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
48635 }
48636 else {
48637 typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
48638 }
48639 }
48640 }
48641 if (!hasSpreadAnyType) {
48642 if (attributesTable.size > 0) {
48643 spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
48644 }
48645 }
48646 // Handle children attribute
48647 var parent = openingLikeElement.parent.kind === 260 /* JsxElement */ ? openingLikeElement.parent : undefined;
48648 // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
48649 if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
48650 var childrenTypes = checkJsxChildren(parent, checkMode);
48651 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
48652 // Error if there is a attribute named "children" explicitly specified and children element.
48653 // This is because children element will overwrite the value from attributes.
48654 // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
48655 if (explicitlySpecifyChildrenAttribute) {
48656 error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
48657 }
48658 var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
48659 var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
48660 // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process
48661 var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName);
48662 childrenPropSymbol.type = childrenTypes.length === 1 ?
48663 childrenTypes[0] :
48664 (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes)));
48665 // Fake up a property declaration for the children
48666 childrenPropSymbol.valueDeclaration = ts.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined);
48667 childrenPropSymbol.valueDeclaration.parent = attributes;
48668 childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
48669 var childPropMap = ts.createSymbolTable();
48670 childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
48671 spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
48672 }
48673 }
48674 if (hasSpreadAnyType) {
48675 return anyType;
48676 }
48677 if (typeToIntersect && spread !== emptyJsxObjectType) {
48678 return getIntersectionType([typeToIntersect, spread]);
48679 }
48680 return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
48681 /**
48682 * Create anonymous type from given attributes symbol table.
48683 * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
48684 * @param attributesTable a symbol table of attributes property
48685 */
48686 function createJsxAttributesType() {
48687 objectFlags |= freshObjectLiteralFlag;
48688 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
48689 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
48690 return result;
48691 }
48692 }
48693 function checkJsxChildren(node, checkMode) {
48694 var childrenTypes = [];
48695 for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
48696 var child = _a[_i];
48697 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
48698 // because then type of children property will have constituent of string type.
48699 if (child.kind === 11 /* JsxText */) {
48700 if (!child.containsOnlyTriviaWhiteSpaces) {
48701 childrenTypes.push(stringType);
48702 }
48703 }
48704 else {
48705 childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
48706 }
48707 }
48708 return childrenTypes;
48709 }
48710 /**
48711 * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
48712 * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
48713 * @param node a JSXAttributes to be resolved of its type
48714 */
48715 function checkJsxAttributes(node, checkMode) {
48716 return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
48717 }
48718 function getJsxType(name, location) {
48719 var namespace = getJsxNamespaceAt(location);
48720 var exports = namespace && getExportsOfSymbol(namespace);
48721 var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */);
48722 return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
48723 }
48724 /**
48725 * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
48726 * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
48727 * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
48728 * May also return unknownSymbol if both of these lookups fail.
48729 */
48730 function getIntrinsicTagSymbol(node) {
48731 var links = getNodeLinks(node);
48732 if (!links.resolvedSymbol) {
48733 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
48734 if (intrinsicElementsType !== errorType) {
48735 // Property case
48736 if (!ts.isIdentifier(node.tagName))
48737 return ts.Debug.fail();
48738 var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
48739 if (intrinsicProp) {
48740 links.jsxFlags |= 1 /* IntrinsicNamedElement */;
48741 return links.resolvedSymbol = intrinsicProp;
48742 }
48743 // Intrinsic string indexer case
48744 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
48745 if (indexSignatureType) {
48746 links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
48747 return links.resolvedSymbol = intrinsicElementsType.symbol;
48748 }
48749 // Wasn't found
48750 error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
48751 return links.resolvedSymbol = unknownSymbol;
48752 }
48753 else {
48754 if (noImplicitAny) {
48755 error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
48756 }
48757 return links.resolvedSymbol = unknownSymbol;
48758 }
48759 }
48760 return links.resolvedSymbol;
48761 }
48762 function getJsxNamespaceAt(location) {
48763 var links = location && getNodeLinks(location);
48764 if (links && links.jsxNamespace) {
48765 return links.jsxNamespace;
48766 }
48767 if (!links || links.jsxNamespace !== false) {
48768 var namespaceName = getJsxNamespace(location);
48769 var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
48770 if (resolvedNamespace) {
48771 var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
48772 if (candidate) {
48773 if (links) {
48774 links.jsxNamespace = candidate;
48775 }
48776 return candidate;
48777 }
48778 if (links) {
48779 links.jsxNamespace = false;
48780 }
48781 }
48782 }
48783 // JSX global fallback
48784 return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217
48785 }
48786 /**
48787 * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
48788 * Get a single property from that container if existed. Report an error if there are more than one property.
48789 *
48790 * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
48791 * if other string is given or the container doesn't exist, return undefined.
48792 */
48793 function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
48794 // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
48795 var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */);
48796 // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
48797 var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
48798 // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
48799 var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
48800 if (propertiesOfJsxElementAttribPropInterface) {
48801 // Element Attributes has zero properties, so the element attributes type will be the class instance type
48802 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
48803 return "";
48804 }
48805 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
48806 // property of the class instance type
48807 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
48808 return propertiesOfJsxElementAttribPropInterface[0].escapedName;
48809 }
48810 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
48811 // More than one property on ElementAttributesProperty is an error
48812 error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
48813 }
48814 }
48815 return undefined;
48816 }
48817 function getJsxLibraryManagedAttributes(jsxNamespace) {
48818 // JSX.LibraryManagedAttributes [symbol]
48819 return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */);
48820 }
48821 /// e.g. "props" for React.d.ts,
48822 /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
48823 /// non-intrinsic elements' attributes type is 'any'),
48824 /// or '' if it has 0 properties (which means every
48825 /// non-intrinsic elements' attributes type is the element instance type)
48826 function getJsxElementPropertiesName(jsxNamespace) {
48827 return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
48828 }
48829 function getJsxElementChildrenPropertyName(jsxNamespace) {
48830 return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
48831 }
48832 function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
48833 if (elementType.flags & 4 /* String */) {
48834 return [anySignature];
48835 }
48836 else if (elementType.flags & 128 /* StringLiteral */) {
48837 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
48838 if (!intrinsicType) {
48839 error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
48840 return ts.emptyArray;
48841 }
48842 else {
48843 var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
48844 return [fakeSignature];
48845 }
48846 }
48847 var apparentElemType = getApparentType(elementType);
48848 // Resolve the signatures, preferring constructor
48849 var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
48850 if (signatures.length === 0) {
48851 // No construct signatures, try call signatures
48852 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
48853 }
48854 if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
48855 // If each member has some combination of new/call signatures; make a union signature list for those
48856 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
48857 }
48858 return signatures;
48859 }
48860 function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
48861 // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type
48862 // For example:
48863 // var CustomTag: "h1" = "h1";
48864 // <CustomTag> Hello World </CustomTag>
48865 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
48866 if (intrinsicElementsType !== errorType) {
48867 var stringLiteralTypeName = type.value;
48868 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
48869 if (intrinsicProp) {
48870 return getTypeOfSymbol(intrinsicProp);
48871 }
48872 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
48873 if (indexSignatureType) {
48874 return indexSignatureType;
48875 }
48876 return undefined;
48877 }
48878 // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
48879 return anyType;
48880 }
48881 function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
48882 if (refKind === 1 /* Function */) {
48883 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
48884 if (sfcReturnConstraint) {
48885 checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
48886 }
48887 }
48888 else if (refKind === 0 /* Component */) {
48889 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
48890 if (classConstraint) {
48891 // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that
48892 checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
48893 }
48894 }
48895 else { // Mixed
48896 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
48897 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
48898 if (!sfcReturnConstraint || !classConstraint) {
48899 return;
48900 }
48901 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
48902 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
48903 }
48904 }
48905 /**
48906 * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
48907 * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
48908 * @param node an intrinsic JSX opening-like element
48909 */
48910 function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
48911 ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
48912 var links = getNodeLinks(node);
48913 if (!links.resolvedJsxElementAttributesType) {
48914 var symbol = getIntrinsicTagSymbol(node);
48915 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
48916 return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
48917 }
48918 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
48919 return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type;
48920 }
48921 else {
48922 return links.resolvedJsxElementAttributesType = errorType;
48923 }
48924 }
48925 return links.resolvedJsxElementAttributesType;
48926 }
48927 function getJsxElementClassTypeAt(location) {
48928 var type = getJsxType(JsxNames.ElementClass, location);
48929 if (type === errorType)
48930 return undefined;
48931 return type;
48932 }
48933 function getJsxElementTypeAt(location) {
48934 return getJsxType(JsxNames.Element, location);
48935 }
48936 function getJsxStatelessElementTypeAt(location) {
48937 var jsxElementType = getJsxElementTypeAt(location);
48938 if (jsxElementType) {
48939 return getUnionType([jsxElementType, nullType]);
48940 }
48941 }
48942 /**
48943 * Returns all the properties of the Jsx.IntrinsicElements interface
48944 */
48945 function getJsxIntrinsicTagNamesAt(location) {
48946 var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
48947 return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
48948 }
48949 function checkJsxPreconditions(errorNode) {
48950 // Preconditions for using JSX
48951 if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
48952 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
48953 }
48954 if (getJsxElementTypeAt(errorNode) === undefined) {
48955 if (noImplicitAny) {
48956 error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
48957 }
48958 }
48959 }
48960 function checkJsxOpeningLikeElementOrOpeningFragment(node) {
48961 var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
48962 if (isNodeOpeningLikeElement) {
48963 checkGrammarJsxElement(node);
48964 }
48965 checkJsxPreconditions(node);
48966 // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
48967 // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
48968 var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
48969 var reactNamespace = getJsxNamespace(node);
48970 var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
48971 var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
48972 if (reactSym) {
48973 // Mark local symbol as referenced here because it might not have been marked
48974 // if jsx emit was not react as there wont be error being emitted
48975 reactSym.isReferenced = 67108863 /* All */;
48976 // If react symbol is alias, mark it as referenced
48977 if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) {
48978 markAliasSymbolAsReferenced(reactSym);
48979 }
48980 }
48981 if (isNodeOpeningLikeElement) {
48982 var sig = getResolvedSignature(node);
48983 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node);
48984 }
48985 }
48986 /**
48987 * Check if a property with the given name is known anywhere in the given type. In an object type, a property
48988 * is considered known if
48989 * 1. the object type is empty and the check is for assignability, or
48990 * 2. if the object type has index signatures, or
48991 * 3. if the property is actually declared in the object type
48992 * (this means that 'toString', for example, is not usually a known property).
48993 * 4. In a union or intersection type,
48994 * a property is considered known if it is known in any constituent type.
48995 * @param targetType a type to search a given name in
48996 * @param name a property name to search
48997 * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
48998 */
48999 function isKnownProperty(targetType, name, isComparingJsxAttributes) {
49000 if (targetType.flags & 524288 /* Object */) {
49001 var resolved = resolveStructuredTypeMembers(targetType);
49002 if (resolved.stringIndexInfo ||
49003 resolved.numberIndexInfo && isNumericLiteralName(name) ||
49004 getPropertyOfObjectType(targetType, name) ||
49005 isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
49006 // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
49007 return true;
49008 }
49009 }
49010 else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
49011 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
49012 var t = _a[_i];
49013 if (isKnownProperty(t, name, isComparingJsxAttributes)) {
49014 return true;
49015 }
49016 }
49017 }
49018 return false;
49019 }
49020 function isExcessPropertyCheckTarget(type) {
49021 return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
49022 type.flags & 67108864 /* NonPrimitive */ ||
49023 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
49024 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
49025 }
49026 function checkJsxExpression(node, checkMode) {
49027 if (node.expression) {
49028 var type = checkExpression(node.expression, checkMode);
49029 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
49030 error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
49031 }
49032 return type;
49033 }
49034 else {
49035 return errorType;
49036 }
49037 }
49038 function getDeclarationNodeFlagsFromSymbol(s) {
49039 return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
49040 }
49041 /**
49042 * Return whether this symbol is a member of a prototype somewhere
49043 * Note that this is not tracked well within the compiler, so the answer may be incorrect.
49044 */
49045 function isPrototypeProperty(symbol) {
49046 if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
49047 return true;
49048 }
49049 if (ts.isInJSFile(symbol.valueDeclaration)) {
49050 var parent = symbol.valueDeclaration.parent;
49051 return parent && ts.isBinaryExpression(parent) &&
49052 ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
49053 }
49054 }
49055 /**
49056 * Check whether the requested property access is valid.
49057 * Returns true if node is a valid property access, and false otherwise.
49058 * @param node The node to be checked.
49059 * @param isSuper True if the access is from `super.`.
49060 * @param type The type of the object whose property is being accessed. (Not the type of the property.)
49061 * @param prop The symbol for the property being accessed.
49062 */
49063 function checkPropertyAccessibility(node, isSuper, type, prop) {
49064 var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
49065 var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name;
49066 if (ts.getCheckFlags(prop) & 512 /* ContainsPrivate */) {
49067 // Synthetic property with private constituent property
49068 error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type));
49069 return false;
49070 }
49071 if (isSuper) {
49072 // TS 1.0 spec (April 2014): 4.8.2
49073 // - In a constructor, instance member function, instance member accessor, or
49074 // instance member variable initializer where this references a derived class instance,
49075 // a super property access is permitted and must specify a public instance member function of the base class.
49076 // - In a static member function or static member accessor
49077 // where this references the constructor function object of a derived class,
49078 // a super property access is permitted and must specify a public static member function of the base class.
49079 if (languageVersion < 2 /* ES2015 */) {
49080 if (symbolHasNonMethodDeclaration(prop)) {
49081 error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
49082 return false;
49083 }
49084 }
49085 if (flags & 128 /* Abstract */) {
49086 // A method cannot be accessed in a super property access if the method is abstract.
49087 // This error could mask a private property access error. But, a member
49088 // cannot simultaneously be private and abstract, so this will trigger an
49089 // additional error elsewhere.
49090 error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
49091 return false;
49092 }
49093 }
49094 // Referencing abstract properties within their own constructors is not allowed
49095 if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
49096 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
49097 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
49098 error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217
49099 return false;
49100 }
49101 }
49102 // Public properties are otherwise accessible.
49103 if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
49104 return true;
49105 }
49106 // Property is known to be private or protected at this point
49107 // Private property is accessible if the property is within the declaring class
49108 if (flags & 8 /* Private */) {
49109 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
49110 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
49111 error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
49112 return false;
49113 }
49114 return true;
49115 }
49116 // Property is known to be protected at this point
49117 // All protected properties of a supertype are accessible in a super access
49118 if (isSuper) {
49119 return true;
49120 }
49121 // Find the first enclosing class that has the declaring classes of the protected constituents
49122 // of the property as base classes
49123 var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
49124 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
49125 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
49126 });
49127 // A protected property is accessible if the property is within the declaring class or classes derived from it
49128 if (!enclosingClass) {
49129 // allow PropertyAccessibility if context is in function with this parameter
49130 // static member access is disallow
49131 var thisParameter = void 0;
49132 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
49133 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
49134 return false;
49135 }
49136 var thisType = getTypeFromTypeNode(thisParameter.type);
49137 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType);
49138 }
49139 // No further restrictions for static properties
49140 if (flags & 32 /* Static */) {
49141 return true;
49142 }
49143 if (type.flags & 262144 /* TypeParameter */) {
49144 // get the original type -- represented as the type constraint of the 'this' type
49145 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
49146 }
49147 if (!type || !hasBaseType(type, enclosingClass)) {
49148 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
49149 return false;
49150 }
49151 return true;
49152 }
49153 function getThisParameterFromNodeContext(node) {
49154 var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
49155 return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
49156 }
49157 function symbolHasNonMethodDeclaration(symbol) {
49158 return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
49159 }
49160 function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) {
49161 return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic);
49162 }
49163 function getNonNullableTypeIfNeeded(type) {
49164 var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
49165 if (kind) {
49166 return getNonNullableType(type);
49167 }
49168 return type;
49169 }
49170 function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) {
49171 if (type.flags & 2 /* Unknown */) {
49172 error(node, ts.Diagnostics.Object_is_of_type_unknown);
49173 return errorType;
49174 }
49175 var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
49176 if (kind) {
49177 error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ?
49178 (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) :
49179 (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) :
49180 (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null));
49181 var t = getNonNullableType(type);
49182 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
49183 }
49184 return type;
49185 }
49186 function checkPropertyAccessExpression(node) {
49187 return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name);
49188 }
49189 function checkQualifiedName(node) {
49190 return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right);
49191 }
49192 function checkPropertyAccessExpressionOrQualifiedName(node, left, right) {
49193 var propType;
49194 var leftType = checkNonNullExpression(left);
49195 var parentSymbol = getNodeLinks(left).resolvedSymbol;
49196 var apparentType = getApparentType(getWidenedType(leftType));
49197 if (isTypeAny(apparentType) || apparentType === silentNeverType) {
49198 if (ts.isIdentifier(left) && parentSymbol) {
49199 markAliasReferenced(parentSymbol, node);
49200 }
49201 return apparentType;
49202 }
49203 var assignmentKind = ts.getAssignmentTargetKind(node);
49204 var prop = getPropertyOfType(apparentType, right.escapedText);
49205 if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
49206 markAliasReferenced(parentSymbol, node);
49207 }
49208 if (!prop) {
49209 var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */);
49210 if (!(indexInfo && indexInfo.type)) {
49211 if (isJSLiteralType(leftType)) {
49212 return anyType;
49213 }
49214 if (leftType.symbol === globalThisSymbol) {
49215 if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
49216 error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
49217 }
49218 else if (noImplicitAny) {
49219 error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
49220 }
49221 return anyType;
49222 }
49223 if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
49224 reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType);
49225 }
49226 return errorType;
49227 }
49228 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
49229 error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
49230 }
49231 propType = indexInfo.type;
49232 }
49233 else {
49234 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
49235 markPropertyAsReferenced(prop, node, left.kind === 100 /* ThisKeyword */);
49236 getNodeLinks(node).resolvedSymbol = prop;
49237 checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop);
49238 if (assignmentKind) {
49239 if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) {
49240 error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
49241 return errorType;
49242 }
49243 }
49244 propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
49245 }
49246 // Only compute control flow type if this is a property access expression that isn't an
49247 // assignment target, and the referenced property was declared as a variable, property,
49248 // accessor, or optional method.
49249 if (node.kind !== 189 /* PropertyAccessExpression */ ||
49250 assignmentKind === 1 /* Definite */ ||
49251 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
49252 return propType;
49253 }
49254 // If strict null checks and strict property initialization checks are enabled, if we have
49255 // a this.xxx property access, if the property is an instance property without an initializer,
49256 // and if we are in a constructor of the same class as the property declaration, assume that
49257 // the property is uninitialized at the top of the control flow.
49258 var assumeUninitialized = false;
49259 if (strictNullChecks && strictPropertyInitialization && left.kind === 100 /* ThisKeyword */) {
49260 var declaration = prop && prop.valueDeclaration;
49261 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
49262 var flowContainer = getControlFlowContainer(node);
49263 if (flowContainer.kind === 157 /* Constructor */ && flowContainer.parent === declaration.parent) {
49264 assumeUninitialized = true;
49265 }
49266 }
49267 }
49268 else if (strictNullChecks && prop && prop.valueDeclaration &&
49269 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
49270 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
49271 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
49272 assumeUninitialized = true;
49273 }
49274 var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
49275 if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
49276 error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
49277 // Return the declared type to reduce follow-on errors
49278 return propType;
49279 }
49280 return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
49281 }
49282 function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
49283 var valueDeclaration = prop.valueDeclaration;
49284 if (!valueDeclaration) {
49285 return;
49286 }
49287 var diagnosticMessage;
49288 var declarationName = ts.idText(right);
49289 if (isInPropertyInitializer(node) &&
49290 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
49291 && !isPropertyDeclaredInAncestorClass(prop)) {
49292 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
49293 }
49294 else if (valueDeclaration.kind === 240 /* ClassDeclaration */ &&
49295 node.parent.kind !== 164 /* TypeReference */ &&
49296 !(valueDeclaration.flags & 4194304 /* Ambient */) &&
49297 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
49298 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
49299 }
49300 if (diagnosticMessage) {
49301 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
49302 }
49303 }
49304 function isInPropertyInitializer(node) {
49305 return !!ts.findAncestor(node, function (node) {
49306 switch (node.kind) {
49307 case 154 /* PropertyDeclaration */:
49308 return true;
49309 case 275 /* PropertyAssignment */:
49310 case 156 /* MethodDeclaration */:
49311 case 158 /* GetAccessor */:
49312 case 159 /* SetAccessor */:
49313 case 277 /* SpreadAssignment */:
49314 case 149 /* ComputedPropertyName */:
49315 case 216 /* TemplateSpan */:
49316 case 270 /* JsxExpression */:
49317 case 267 /* JsxAttribute */:
49318 case 268 /* JsxAttributes */:
49319 case 269 /* JsxSpreadAttribute */:
49320 case 262 /* JsxOpeningElement */:
49321 case 211 /* ExpressionWithTypeArguments */:
49322 case 273 /* HeritageClause */:
49323 return false;
49324 default:
49325 return ts.isExpressionNode(node) ? false : "quit";
49326 }
49327 });
49328 }
49329 /**
49330 * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
49331 * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
49332 */
49333 function isPropertyDeclaredInAncestorClass(prop) {
49334 if (!(prop.parent.flags & 32 /* Class */)) {
49335 return false;
49336 }
49337 var classType = getTypeOfSymbol(prop.parent);
49338 while (true) {
49339 classType = classType.symbol && getSuperClass(classType);
49340 if (!classType) {
49341 return false;
49342 }
49343 var superProperty = getPropertyOfType(classType, prop.escapedName);
49344 if (superProperty && superProperty.valueDeclaration) {
49345 return true;
49346 }
49347 }
49348 }
49349 function getSuperClass(classType) {
49350 var x = getBaseTypes(classType);
49351 if (x.length === 0) {
49352 return undefined;
49353 }
49354 return getIntersectionType(x);
49355 }
49356 function reportNonexistentProperty(propNode, containingType) {
49357 var errorInfo;
49358 var relatedInfo;
49359 if (containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
49360 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
49361 var subtype = _a[_i];
49362 if (!getPropertyOfType(subtype, propNode.escapedText)) {
49363 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
49364 break;
49365 }
49366 }
49367 }
49368 if (typeHasStaticProperty(propNode.escapedText, containingType)) {
49369 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
49370 }
49371 else {
49372 var promisedType = getPromisedTypeOfPromise(containingType);
49373 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
49374 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType));
49375 }
49376 else {
49377 var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
49378 if (suggestion !== undefined) {
49379 var suggestedName = ts.symbolName(suggestion);
49380 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName);
49381 relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
49382 }
49383 else {
49384 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
49385 }
49386 }
49387 }
49388 var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
49389 if (relatedInfo) {
49390 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
49391 }
49392 diagnostics.add(resultDiagnostic);
49393 }
49394 function typeHasStaticProperty(propName, containingType) {
49395 var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
49396 return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */);
49397 }
49398 function getSuggestedSymbolForNonexistentProperty(name, containingType) {
49399 return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */);
49400 }
49401 function getSuggestionForNonexistentProperty(name, containingType) {
49402 var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
49403 return suggestion && ts.symbolName(suggestion);
49404 }
49405 function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
49406 ts.Debug.assert(outerName !== undefined, "outername should always be defined");
49407 var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
49408 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
49409 var symbol = getSymbol(symbols, name, meaning);
49410 // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function
49411 // So the table *contains* `x` but `x` isn't actually in scope.
49412 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
49413 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
49414 });
49415 return result;
49416 }
49417 function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
49418 var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
49419 return symbolResult && ts.symbolName(symbolResult);
49420 }
49421 function getSuggestedSymbolForNonexistentModule(name, targetModule) {
49422 return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
49423 }
49424 function getSuggestionForNonexistentExport(name, targetModule) {
49425 var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
49426 return suggestion && ts.symbolName(suggestion);
49427 }
49428 /**
49429 * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
49430 * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
49431 *
49432 * If there is a candidate that's the same except for case, return that.
49433 * If there is a candidate that's within one edit of the name, return that.
49434 * Otherwise, return the candidate with the smallest Levenshtein distance,
49435 * except for candidates:
49436 * * With no name
49437 * * Whose meaning doesn't match the `meaning` parameter.
49438 * * Whose length differs from the target name by more than 0.34 of the length of the name.
49439 * * Whose levenshtein distance is more than 0.4 of the length of the name
49440 * (0.4 allows 1 substitution/transposition for every 5 characters,
49441 * and 1 insertion/deletion at 3 characters)
49442 */
49443 function getSpellingSuggestionForName(name, symbols, meaning) {
49444 return ts.getSpellingSuggestion(name, symbols, getCandidateName);
49445 function getCandidateName(candidate) {
49446 var candidateName = ts.symbolName(candidate);
49447 return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined;
49448 }
49449 }
49450 function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
49451 if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) {
49452 return;
49453 }
49454 if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) {
49455 return;
49456 }
49457 if (isThisAccess) {
49458 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
49459 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
49460 if (containingMethod && containingMethod.symbol === prop) {
49461 return;
49462 }
49463 }
49464 (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
49465 }
49466 function isValidPropertyAccess(node, propertyName) {
49467 switch (node.kind) {
49468 case 189 /* PropertyAccessExpression */:
49469 return isValidPropertyAccessWithType(node, node.expression.kind === 98 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
49470 case 148 /* QualifiedName */:
49471 return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
49472 case 183 /* ImportType */:
49473 return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
49474 }
49475 }
49476 function isValidPropertyAccessForCompletions(node, type, property) {
49477 return isValidPropertyAccessWithType(node, node.kind === 189 /* PropertyAccessExpression */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type)
49478 && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type));
49479 }
49480 function isValidMethodAccess(method, actualThisType) {
49481 var propType = getTypeOfPropertyOfType(actualThisType, method.escapedName);
49482 var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */);
49483 ts.Debug.assert(signatures.length !== 0);
49484 return signatures.some(function (sig) {
49485 var signatureThisType = getThisTypeOfSignature(sig);
49486 return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType));
49487 });
49488 }
49489 function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) {
49490 if (!sig.typeParameters) {
49491 return signatureThisType;
49492 }
49493 var context = createInferenceContext(sig.typeParameters, sig, 0 /* None */);
49494 inferTypes(context.inferences, actualThisType, signatureThisType);
49495 return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context)));
49496 }
49497 function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
49498 if (type === errorType || isTypeAny(type)) {
49499 return true;
49500 }
49501 var prop = getPropertyOfType(type, propertyName);
49502 return prop ? checkPropertyAccessibility(node, isSuper, type, prop)
49503 // In js files properties of unions are allowed in completion
49504 : ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
49505 }
49506 /**
49507 * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
49508 */
49509 function getForInVariableSymbol(node) {
49510 var initializer = node.initializer;
49511 if (initializer.kind === 238 /* VariableDeclarationList */) {
49512 var variable = initializer.declarations[0];
49513 if (variable && !ts.isBindingPattern(variable.name)) {
49514 return getSymbolOfNode(variable);
49515 }
49516 }
49517 else if (initializer.kind === 72 /* Identifier */) {
49518 return getResolvedSymbol(initializer);
49519 }
49520 return undefined;
49521 }
49522 /**
49523 * Return true if the given type is considered to have numeric property names.
49524 */
49525 function hasNumericPropertyNames(type) {
49526 return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
49527 }
49528 /**
49529 * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
49530 * that references a for-in variable for an object with numeric property names.
49531 */
49532 function isForInVariableForNumericPropertyNames(expr) {
49533 var e = ts.skipParentheses(expr);
49534 if (e.kind === 72 /* Identifier */) {
49535 var symbol = getResolvedSymbol(e);
49536 if (symbol.flags & 3 /* Variable */) {
49537 var child = expr;
49538 var node = expr.parent;
49539 while (node) {
49540 if (node.kind === 226 /* ForInStatement */ &&
49541 child === node.statement &&
49542 getForInVariableSymbol(node) === symbol &&
49543 hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
49544 return true;
49545 }
49546 child = node;
49547 node = node.parent;
49548 }
49549 }
49550 }
49551 return false;
49552 }
49553 function checkIndexedAccess(node) {
49554 var objectType = checkNonNullExpression(node.expression);
49555 var indexExpression = node.argumentExpression;
49556 if (!indexExpression) {
49557 var sourceFile = ts.getSourceFileOfNode(node);
49558 if (node.parent.kind === 192 /* NewExpression */ && node.parent.expression === node) {
49559 var start = ts.skipTrivia(sourceFile.text, node.expression.end);
49560 var end = node.end;
49561 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead);
49562 }
49563 else {
49564 var start = node.end - "]".length;
49565 var end = node.end;
49566 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected);
49567 }
49568 return errorType;
49569 }
49570 var indexType = checkExpression(indexExpression);
49571 if (objectType === errorType || objectType === silentNeverType) {
49572 return objectType;
49573 }
49574 if (isConstEnumObjectType(objectType) && indexExpression.kind !== 10 /* StringLiteral */) {
49575 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
49576 return errorType;
49577 }
49578 return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node);
49579 }
49580 function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
49581 if (expressionType === errorType) {
49582 // There is already an error, so no need to report one.
49583 return false;
49584 }
49585 if (!ts.isWellKnownSymbolSyntactically(expression)) {
49586 return false;
49587 }
49588 // Make sure the property type is the primitive symbol type
49589 if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
49590 if (reportError) {
49591 error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
49592 }
49593 return false;
49594 }
49595 // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
49596 // global Symbol object
49597 var leftHandSide = expression.expression;
49598 var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
49599 if (!leftHandSideSymbol) {
49600 return false;
49601 }
49602 var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
49603 if (!globalESSymbol) {
49604 // Already errored when we tried to look up the symbol
49605 return false;
49606 }
49607 if (leftHandSideSymbol !== globalESSymbol) {
49608 if (reportError) {
49609 error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
49610 }
49611 return false;
49612 }
49613 return true;
49614 }
49615 function callLikeExpressionMayHaveTypeArguments(node) {
49616 return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
49617 }
49618 function resolveUntypedCall(node) {
49619 if (callLikeExpressionMayHaveTypeArguments(node)) {
49620 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
49621 // This gets us diagnostics for the type arguments and marks them as referenced.
49622 ts.forEach(node.typeArguments, checkSourceElement);
49623 }
49624 if (node.kind === 193 /* TaggedTemplateExpression */) {
49625 checkExpression(node.template);
49626 }
49627 else if (ts.isJsxOpeningLikeElement(node)) {
49628 checkExpression(node.attributes);
49629 }
49630 else if (node.kind !== 152 /* Decorator */) {
49631 ts.forEach(node.arguments, function (argument) {
49632 checkExpression(argument);
49633 });
49634 }
49635 return anySignature;
49636 }
49637 function resolveErrorCall(node) {
49638 resolveUntypedCall(node);
49639 return unknownSignature;
49640 }
49641 // Re-order candidate signatures into the result array. Assumes the result array to be empty.
49642 // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
49643 // A nit here is that we reorder only signatures that belong to the same symbol,
49644 // so order how inherited signatures are processed is still preserved.
49645 // interface A { (x: string): void }
49646 // interface B extends A { (x: 'foo'): string }
49647 // const b: B;
49648 // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
49649 function reorderCandidates(signatures, result) {
49650 var lastParent;
49651 var lastSymbol;
49652 var cutoffIndex = 0;
49653 var index;
49654 var specializedIndex = -1;
49655 var spliceIndex;
49656 ts.Debug.assert(!result.length);
49657 for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
49658 var signature = signatures_3[_i];
49659 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
49660 var parent = signature.declaration && signature.declaration.parent;
49661 if (!lastSymbol || symbol === lastSymbol) {
49662 if (lastParent && parent === lastParent) {
49663 index = index + 1;
49664 }
49665 else {
49666 lastParent = parent;
49667 index = cutoffIndex;
49668 }
49669 }
49670 else {
49671 // current declaration belongs to a different symbol
49672 // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
49673 index = cutoffIndex = result.length;
49674 lastParent = parent;
49675 }
49676 lastSymbol = symbol;
49677 // specialized signatures always need to be placed before non-specialized signatures regardless
49678 // of the cutoff position; see GH#1133
49679 if (signature.hasLiteralTypes) {
49680 specializedIndex++;
49681 spliceIndex = specializedIndex;
49682 // The cutoff index always needs to be greater than or equal to the specialized signature index
49683 // in order to prevent non-specialized signatures from being added before a specialized
49684 // signature.
49685 cutoffIndex++;
49686 }
49687 else {
49688 spliceIndex = index;
49689 }
49690 result.splice(spliceIndex, 0, signature);
49691 }
49692 }
49693 function isSpreadArgument(arg) {
49694 return !!arg && (arg.kind === 208 /* SpreadElement */ || arg.kind === 215 /* SyntheticExpression */ && arg.isSpread);
49695 }
49696 function getSpreadArgumentIndex(args) {
49697 return ts.findIndex(args, isSpreadArgument);
49698 }
49699 function acceptsVoid(t) {
49700 return !!(t.flags & 16384 /* Void */);
49701 }
49702 function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
49703 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
49704 var argCount;
49705 var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
49706 var effectiveParameterCount = getParameterCount(signature);
49707 var effectiveMinimumArguments = getMinArgumentCount(signature);
49708 if (node.kind === 193 /* TaggedTemplateExpression */) {
49709 argCount = args.length;
49710 if (node.template.kind === 206 /* TemplateExpression */) {
49711 // If a tagged template expression lacks a tail literal, the call is incomplete.
49712 // Specifically, a template only can end in a TemplateTail or a Missing literal.
49713 var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
49714 callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
49715 }
49716 else {
49717 // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
49718 // then this might actually turn out to be a TemplateHead in the future;
49719 // so we consider the call to be incomplete.
49720 var templateLiteral = node.template;
49721 ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
49722 callIsIncomplete = !!templateLiteral.isUnterminated;
49723 }
49724 }
49725 else if (node.kind === 152 /* Decorator */) {
49726 argCount = getDecoratorArgumentCount(node, signature);
49727 }
49728 else if (ts.isJsxOpeningLikeElement(node)) {
49729 callIsIncomplete = node.attributes.end === node.end;
49730 if (callIsIncomplete) {
49731 return true;
49732 }
49733 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
49734 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
49735 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
49736 }
49737 else {
49738 if (!node.arguments) {
49739 // This only happens when we have something of the form: 'new C'
49740 ts.Debug.assert(node.kind === 192 /* NewExpression */);
49741 return getMinArgumentCount(signature) === 0;
49742 }
49743 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
49744 // If we are missing the close parenthesis, the call is incomplete.
49745 callIsIncomplete = node.arguments.end === node.end;
49746 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
49747 var spreadArgIndex = getSpreadArgumentIndex(args);
49748 if (spreadArgIndex >= 0) {
49749 return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
49750 }
49751 }
49752 // Too many arguments implies incorrect arity.
49753 if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
49754 return false;
49755 }
49756 // If the call is incomplete, we should skip the lower bound check.
49757 // JSX signatures can have extra parameters provided by the library which we don't check
49758 if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
49759 return true;
49760 }
49761 for (var i = argCount; i < effectiveMinimumArguments; i++) {
49762 var type = getTypeAtPosition(signature, i);
49763 if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
49764 return false;
49765 }
49766 }
49767 return true;
49768 }
49769 function hasCorrectTypeArgumentArity(signature, typeArguments) {
49770 // If the user supplied type arguments, but the number of type arguments does not match
49771 // the declared number of type parameters, the call has an incorrect arity.
49772 var numTypeParameters = ts.length(signature.typeParameters);
49773 var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
49774 return !typeArguments ||
49775 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
49776 }
49777 // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
49778 function getSingleCallSignature(type) {
49779 if (type.flags & 524288 /* Object */) {
49780 var resolved = resolveStructuredTypeMembers(type);
49781 if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 &&
49782 resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
49783 return resolved.callSignatures[0];
49784 }
49785 }
49786 return undefined;
49787 }
49788 // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
49789 function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
49790 var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
49791 // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
49792 // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
49793 // for T but leave it possible to later infer '[any]' back to A.
49794 var restType = getEffectiveRestType(contextualSignature);
49795 var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
49796 var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
49797 applyToParameterTypes(sourceSignature, signature, function (source, target) {
49798 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
49799 inferTypes(context.inferences, source, target);
49800 });
49801 if (!inferenceContext) {
49802 applyToReturnTypes(contextualSignature, signature, function (source, target) {
49803 inferTypes(context.inferences, source, target, 8 /* ReturnType */);
49804 });
49805 }
49806 return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
49807 }
49808 function inferJsxTypeArguments(node, signature, checkMode, context) {
49809 var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
49810 var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
49811 inferTypes(context.inferences, checkAttrType, paramType);
49812 return getInferredTypes(context);
49813 }
49814 function inferTypeArguments(node, signature, args, checkMode, context) {
49815 if (ts.isJsxOpeningLikeElement(node)) {
49816 return inferJsxTypeArguments(node, signature, checkMode, context);
49817 }
49818 // If a contextual type is available, infer from that type to the return type of the call expression. For
49819 // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
49820 // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
49821 // return type of 'wrap'.
49822 if (node.kind !== 152 /* Decorator */) {
49823 var contextualType = getContextualType(node);
49824 if (contextualType) {
49825 // We clone the inference context to avoid disturbing a resolution in progress for an
49826 // outer call expression. Effectively we just want a snapshot of whatever has been
49827 // inferred for any outer call expression so far.
49828 var outerMapper = getMapperFromContext(cloneInferenceContext(getInferenceContext(node), 1 /* NoDefault */));
49829 var instantiatedType = instantiateType(contextualType, outerMapper);
49830 // If the contextual type is a generic function type with a single call signature, we
49831 // instantiate the type with its own type parameters and type arguments. This ensures that
49832 // the type parameters are not erased to type any during type inference such that they can
49833 // be inferred as actual types from the contextual type. For example:
49834 // declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
49835 // const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
49836 // Above, the type of the 'value' parameter is inferred to be 'A'.
49837 var contextualSignature = getSingleCallSignature(instantiatedType);
49838 var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
49839 getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
49840 instantiatedType;
49841 var inferenceTargetType = getReturnTypeOfSignature(signature);
49842 // Inferences made from return types have lower priority than all other inferences.
49843 inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
49844 // Create a type mapper for instantiating generic contextual types using the inferences made
49845 // from the return type.
49846 context.returnMapper = getMapperFromContext(cloneInferredPartOfContext(context));
49847 }
49848 }
49849 var thisType = getThisTypeOfSignature(signature);
49850 if (thisType) {
49851 var thisArgumentNode = getThisArgumentOfCall(node);
49852 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
49853 inferTypes(context.inferences, thisArgumentType, thisType);
49854 }
49855 var restType = getNonArrayRestType(signature);
49856 var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
49857 for (var i = 0; i < argCount; i++) {
49858 var arg = args[i];
49859 if (arg.kind !== 210 /* OmittedExpression */) {
49860 var paramType = getTypeAtPosition(signature, i);
49861 var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
49862 inferTypes(context.inferences, argType, paramType);
49863 }
49864 }
49865 if (restType) {
49866 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context);
49867 inferTypes(context.inferences, spreadType, restType);
49868 }
49869 return getInferredTypes(context);
49870 }
49871 function getArrayifiedType(type) {
49872 if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) {
49873 return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType);
49874 }
49875 return type;
49876 }
49877 function getSpreadArgumentType(args, index, argCount, restType, context) {
49878 if (index >= argCount - 1) {
49879 var arg = args[argCount - 1];
49880 if (isSpreadArgument(arg)) {
49881 // We are inferring from a spread expression in the last argument position, i.e. both the parameter
49882 // and the argument are ...x forms.
49883 return arg.kind === 215 /* SyntheticExpression */ ?
49884 createArrayType(arg.type) :
49885 getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
49886 }
49887 }
49888 var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
49889 var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */);
49890 var types = [];
49891 var spreadIndex = -1;
49892 for (var i = index; i < argCount; i++) {
49893 var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
49894 if (spreadIndex < 0 && isSpreadArgument(args[i])) {
49895 spreadIndex = i - index;
49896 }
49897 types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
49898 }
49899 return spreadIndex < 0 ?
49900 createTupleType(types) :
49901 createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true);
49902 }
49903 function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
49904 var isJavascript = ts.isInJSFile(signature.declaration);
49905 var typeParameters = signature.typeParameters;
49906 var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
49907 var mapper;
49908 for (var i = 0; i < typeArgumentNodes.length; i++) {
49909 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
49910 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
49911 if (constraint) {
49912 var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
49913 var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
49914 if (!mapper) {
49915 mapper = createTypeMapper(typeParameters, typeArgumentTypes);
49916 }
49917 var typeArgument = typeArgumentTypes[i];
49918 if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
49919 return undefined;
49920 }
49921 }
49922 }
49923 return typeArgumentTypes;
49924 }
49925 function getJsxReferenceKind(node) {
49926 if (isJsxIntrinsicIdentifier(node.tagName)) {
49927 return 2 /* Mixed */;
49928 }
49929 var tagType = getApparentType(checkExpression(node.tagName));
49930 if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
49931 return 0 /* Component */;
49932 }
49933 if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
49934 return 1 /* Function */;
49935 }
49936 return 2 /* Mixed */;
49937 }
49938 /**
49939 * Check if the given signature can possibly be a signature called by the JSX opening-like element.
49940 * @param node a JSX opening-like element we are trying to figure its call signature
49941 * @param signature a candidate signature we are trying whether it is a call signature
49942 * @param relation a relationship to check parameter and argument type
49943 */
49944 function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
49945 // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
49946 // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
49947 // can be specified by users through attributes property.
49948 var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
49949 var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
49950 return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
49951 }
49952 function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
49953 if (ts.isJsxOpeningLikeElement(node)) {
49954 return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
49955 }
49956 var thisType = getThisTypeOfSignature(signature);
49957 if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
49958 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
49959 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
49960 // If the expression is a new expression, then the check is skipped.
49961 var thisArgumentNode = getThisArgumentOfCall(node);
49962 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
49963 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
49964 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
49965 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) {
49966 return false;
49967 }
49968 }
49969 var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
49970 var restType = getNonArrayRestType(signature);
49971 var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
49972 for (var i = 0; i < argCount; i++) {
49973 var arg = args[i];
49974 if (arg.kind !== 210 /* OmittedExpression */) {
49975 var paramType = getTypeAtPosition(signature, i);
49976 var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
49977 // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
49978 // we obtain the regular type of any object literal arguments because we may not have inferred complete
49979 // parameter types yet and therefore excess property checks may yield false positives (see #17041).
49980 var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
49981 if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
49982 return false;
49983 }
49984 }
49985 }
49986 if (restType) {
49987 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined);
49988 var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
49989 return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage);
49990 }
49991 return true;
49992 }
49993 /**
49994 * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
49995 */
49996 function getThisArgumentOfCall(node) {
49997 if (node.kind === 191 /* CallExpression */) {
49998 var callee = ts.skipOuterExpressions(node.expression);
49999 if (callee.kind === 189 /* PropertyAccessExpression */ || callee.kind === 190 /* ElementAccessExpression */) {
50000 return callee.expression;
50001 }
50002 }
50003 }
50004 function createSyntheticExpression(parent, type, isSpread) {
50005 var result = ts.createNode(215 /* SyntheticExpression */, parent.pos, parent.end);
50006 result.parent = parent;
50007 result.type = type;
50008 result.isSpread = isSpread || false;
50009 return result;
50010 }
50011 /**
50012 * Returns the effective arguments for an expression that works like a function invocation.
50013 */
50014 function getEffectiveCallArguments(node) {
50015 if (node.kind === 193 /* TaggedTemplateExpression */) {
50016 var template = node.template;
50017 var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
50018 if (template.kind === 206 /* TemplateExpression */) {
50019 ts.forEach(template.templateSpans, function (span) {
50020 args_4.push(span.expression);
50021 });
50022 }
50023 return args_4;
50024 }
50025 if (node.kind === 152 /* Decorator */) {
50026 return getEffectiveDecoratorArguments(node);
50027 }
50028 if (ts.isJsxOpeningLikeElement(node)) {
50029 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
50030 }
50031 var args = node.arguments || ts.emptyArray;
50032 var length = args.length;
50033 if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) {
50034 // We have a spread argument in the last position and no other spread arguments. If the type
50035 // of the argument is a tuple type, spread the tuple elements into the argument list. We can
50036 // call checkExpressionCached because spread expressions never have a contextual type.
50037 var spreadArgument_1 = args[length - 1];
50038 var type = checkExpressionCached(spreadArgument_1.expression);
50039 if (isTupleType(type)) {
50040 var typeArguments = type.typeArguments || ts.emptyArray;
50041 var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
50042 var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); });
50043 return ts.concatenate(args.slice(0, length - 1), syntheticArgs);
50044 }
50045 }
50046 return args;
50047 }
50048 /**
50049 * Returns the synthetic argument list for a decorator invocation.
50050 */
50051 function getEffectiveDecoratorArguments(node) {
50052 var parent = node.parent;
50053 var expr = node.expression;
50054 switch (parent.kind) {
50055 case 240 /* ClassDeclaration */:
50056 case 209 /* ClassExpression */:
50057 // For a class decorator, the `target` is the type of the class (e.g. the
50058 // "static" or "constructor" side of the class).
50059 return [
50060 createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
50061 ];
50062 case 151 /* Parameter */:
50063 // A parameter declaration decorator will have three arguments (see
50064 // `ParameterDecorator` in core.d.ts).
50065 var func = parent.parent;
50066 return [
50067 createSyntheticExpression(expr, parent.parent.kind === 157 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
50068 createSyntheticExpression(expr, anyType),
50069 createSyntheticExpression(expr, numberType)
50070 ];
50071 case 154 /* PropertyDeclaration */:
50072 case 156 /* MethodDeclaration */:
50073 case 158 /* GetAccessor */:
50074 case 159 /* SetAccessor */:
50075 // A method or accessor declaration decorator will have two or three arguments (see
50076 // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
50077 // for ES3, we will only pass two arguments.
50078 var hasPropDesc = parent.kind !== 154 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
50079 return [
50080 createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
50081 createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
50082 createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
50083 ];
50084 }
50085 return ts.Debug.fail();
50086 }
50087 /**
50088 * Returns the argument count for a decorator node that works like a function invocation.
50089 */
50090 function getDecoratorArgumentCount(node, signature) {
50091 switch (node.parent.kind) {
50092 case 240 /* ClassDeclaration */:
50093 case 209 /* ClassExpression */:
50094 return 1;
50095 case 154 /* PropertyDeclaration */:
50096 return 2;
50097 case 156 /* MethodDeclaration */:
50098 case 158 /* GetAccessor */:
50099 case 159 /* SetAccessor */:
50100 // For ES3 or decorators with only two parameters we supply only two arguments
50101 return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
50102 case 151 /* Parameter */:
50103 return 3;
50104 default:
50105 return ts.Debug.fail();
50106 }
50107 }
50108 function getArgumentArityError(node, signatures, args) {
50109 var min = Number.POSITIVE_INFINITY;
50110 var max = Number.NEGATIVE_INFINITY;
50111 var belowArgCount = Number.NEGATIVE_INFINITY;
50112 var aboveArgCount = Number.POSITIVE_INFINITY;
50113 var argCount = args.length;
50114 var closestSignature;
50115 for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
50116 var sig = signatures_4[_i];
50117 var minCount = getMinArgumentCount(sig);
50118 var maxCount = getParameterCount(sig);
50119 if (minCount < argCount && minCount > belowArgCount)
50120 belowArgCount = minCount;
50121 if (argCount < maxCount && maxCount < aboveArgCount)
50122 aboveArgCount = maxCount;
50123 if (minCount < min) {
50124 min = minCount;
50125 closestSignature = sig;
50126 }
50127 max = Math.max(max, maxCount);
50128 }
50129 var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
50130 var paramRange = hasRestParameter ? min :
50131 min < max ? min + "-" + max :
50132 min;
50133 var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
50134 if (argCount <= max && hasSpreadArgument) {
50135 argCount--;
50136 }
50137 var spanArray;
50138 var related;
50139 var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
50140 hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
50141 ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1;
50142 if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
50143 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
50144 if (paramDecl) {
50145 related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined);
50146 }
50147 }
50148 if (min < argCount && argCount < max) {
50149 return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
50150 }
50151 if (!hasSpreadArgument && argCount < min) {
50152 var diagnostic_1 = ts.createDiagnosticForNode(node, error, paramRange, argCount);
50153 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
50154 }
50155 if (hasRestParameter || hasSpreadArgument) {
50156 spanArray = ts.createNodeArray(args);
50157 if (hasSpreadArgument && argCount) {
50158 var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
50159 spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
50160 }
50161 }
50162 else {
50163 spanArray = ts.createNodeArray(args.slice(max));
50164 }
50165 spanArray.pos = ts.first(spanArray).pos;
50166 spanArray.end = ts.last(spanArray).end;
50167 if (spanArray.end === spanArray.pos) {
50168 spanArray.end++;
50169 }
50170 var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
50171 return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
50172 }
50173 function getTypeArgumentArityError(node, signatures, typeArguments) {
50174 var argCount = typeArguments.length;
50175 // No overloads exist
50176 if (signatures.length === 1) {
50177 var sig = signatures[0];
50178 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
50179 var max = ts.length(sig.typeParameters);
50180 return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, min_1 < max ? min_1 + "-" + max : min_1, argCount);
50181 }
50182 // Overloads exist
50183 var belowArgCount = -Infinity;
50184 var aboveArgCount = Infinity;
50185 for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) {
50186 var sig = signatures_5[_i];
50187 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
50188 var max = ts.length(sig.typeParameters);
50189 if (min_2 > argCount) {
50190 aboveArgCount = Math.min(aboveArgCount, min_2);
50191 }
50192 else if (max < argCount) {
50193 belowArgCount = Math.max(belowArgCount, max);
50194 }
50195 }
50196 if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
50197 return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount);
50198 }
50199 return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
50200 }
50201 function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
50202 var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
50203 var isDecorator = node.kind === 152 /* Decorator */;
50204 var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
50205 var reportErrors = !candidatesOutArray;
50206 var typeArguments;
50207 if (!isDecorator) {
50208 typeArguments = node.typeArguments;
50209 // We already perform checking on the type arguments on the class declaration itself.
50210 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 98 /* SuperKeyword */) {
50211 ts.forEach(typeArguments, checkSourceElement);
50212 }
50213 }
50214 var candidates = candidatesOutArray || [];
50215 // reorderCandidates fills up the candidates array directly
50216 reorderCandidates(signatures, candidates);
50217 if (!candidates.length) {
50218 if (reportErrors) {
50219 diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
50220 }
50221 return resolveErrorCall(node);
50222 }
50223 var args = getEffectiveCallArguments(node);
50224 // The excludeArgument array contains true for each context sensitive argument (an argument
50225 // is context sensitive it is susceptible to a one-time permanent contextual typing).
50226 //
50227 // The idea is that we will perform type argument inference & assignability checking once
50228 // without using the susceptible parameters that are functions, and once more for those
50229 // parameters, contextually typing each as we go along.
50230 //
50231 // For a tagged template, then the first argument be 'undefined' if necessary because it
50232 // represents a TemplateStringsArray.
50233 //
50234 // For a decorator, no arguments are susceptible to contextual typing due to the fact
50235 // decorators are applied to a declaration by the emitter, and not to an expression.
50236 var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
50237 var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
50238 // The following variables are captured and modified by calls to chooseOverload.
50239 // If overload resolution or type argument inference fails, we want to report the
50240 // best error possible. The best error is one which says that an argument was not
50241 // assignable to a parameter. This implies that everything else about the overload
50242 // was fine. So if there is any overload that is only incorrect because of an
50243 // argument, we will report an error on that one.
50244 //
50245 // function foo(s: string): void;
50246 // function foo(n: number): void; // Report argument error on this overload
50247 // function foo(): void;
50248 // foo(true);
50249 //
50250 // If none of the overloads even made it that far, there are two possibilities.
50251 // There was a problem with type arguments for some overload, in which case
50252 // report an error on that. Or none of the overloads even had correct arity,
50253 // in which case give an arity error.
50254 //
50255 // function foo<T extends string>(x: T): void; // Report type argument error
50256 // function foo(): void;
50257 // foo<number>(0);
50258 //
50259 var candidateForArgumentError;
50260 var candidateForArgumentArityError;
50261 var candidateForTypeArgumentError;
50262 var result;
50263 // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
50264 // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
50265 var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
50266 // Section 4.12.1:
50267 // if the candidate list contains one or more signatures for which the type of each argument
50268 // expression is a subtype of each corresponding parameter type, the return type of the first
50269 // of those signatures becomes the return type of the function call.
50270 // Otherwise, the return type of the first signature in the candidate list becomes the return
50271 // type of the function call.
50272 //
50273 // Whether the call is an error is determined by assignability of the arguments. The subtype pass
50274 // is just important for choosing the best signature. So in the case where there is only one
50275 // signature, the subtype pass is useless. So skipping it is an optimization.
50276 if (candidates.length > 1) {
50277 result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
50278 }
50279 if (!result) {
50280 result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma);
50281 }
50282 if (result) {
50283 return result;
50284 }
50285 // No signatures were applicable. Now report errors based on the last applicable signature with
50286 // no arguments excluded from assignability checks.
50287 // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
50288 // skip the checkApplicableSignature check.
50289 if (reportErrors) {
50290 if (candidateForArgumentError) {
50291 checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
50292 }
50293 else if (candidateForArgumentArityError) {
50294 diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
50295 }
50296 else if (candidateForTypeArgumentError) {
50297 checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
50298 }
50299 else {
50300 var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
50301 if (signaturesWithCorrectTypeArgumentArity.length === 0) {
50302 diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
50303 }
50304 else if (!isDecorator) {
50305 diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
50306 }
50307 else if (fallbackError) {
50308 diagnostics.add(ts.createDiagnosticForNode(node, fallbackError));
50309 }
50310 }
50311 }
50312 return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
50313 function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
50314 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
50315 candidateForArgumentError = undefined;
50316 candidateForArgumentArityError = undefined;
50317 candidateForTypeArgumentError = undefined;
50318 if (isSingleNonGenericCandidate) {
50319 var candidate = candidates[0];
50320 if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
50321 return undefined;
50322 }
50323 if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
50324 candidateForArgumentError = candidate;
50325 return undefined;
50326 }
50327 return candidate;
50328 }
50329 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
50330 var candidate = candidates[candidateIndex];
50331 if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
50332 continue;
50333 }
50334 var checkCandidate = void 0;
50335 var inferenceContext = void 0;
50336 if (candidate.typeParameters) {
50337 var typeArgumentTypes = void 0;
50338 if (typeArguments) {
50339 typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
50340 if (!typeArgumentTypes) {
50341 candidateForTypeArgumentError = candidate;
50342 continue;
50343 }
50344 }
50345 else {
50346 inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
50347 typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
50348 argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
50349 }
50350 checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
50351 // If the original signature has a generic rest type, instantiation may produce a
50352 // signature with different arity and we need to perform another arity check.
50353 if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
50354 candidateForArgumentArityError = checkCandidate;
50355 continue;
50356 }
50357 }
50358 else {
50359 checkCandidate = candidate;
50360 }
50361 if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
50362 // Give preference to error candidates that have no rest parameters (as they are more specific)
50363 if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
50364 candidateForArgumentError = checkCandidate;
50365 }
50366 continue;
50367 }
50368 if (argCheckMode) {
50369 // If one or more context sensitive arguments were excluded, we start including
50370 // them now (and keeping do so for any subsequent candidates) and perform a second
50371 // round of type inference and applicability checking for this particular candidate.
50372 argCheckMode = 0 /* Normal */;
50373 if (inferenceContext) {
50374 var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
50375 checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
50376 // If the original signature has a generic rest type, instantiation may produce a
50377 // signature with different arity and we need to perform another arity check.
50378 if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
50379 candidateForArgumentArityError = checkCandidate;
50380 continue;
50381 }
50382 }
50383 if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
50384 // Give preference to error candidates that have no rest parameters (as they are more specific)
50385 if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
50386 candidateForArgumentError = checkCandidate;
50387 }
50388 continue;
50389 }
50390 }
50391 candidates[candidateIndex] = checkCandidate;
50392 return checkCandidate;
50393 }
50394 return undefined;
50395 }
50396 }
50397 // No signature was applicable. We have already reported the errors for the invalid signature.
50398 // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature.
50399 function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
50400 ts.Debug.assert(candidates.length > 0); // Else should not have called this.
50401 // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
50402 // Don't do this if there is a `candidatesOutArray`,
50403 // because then we want the chosen best candidate to be one of the overloads, not a combination.
50404 return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
50405 ? pickLongestCandidateSignature(node, candidates, args)
50406 : createUnionOfSignaturesForOverloadFailure(candidates);
50407 }
50408 function createUnionOfSignaturesForOverloadFailure(candidates) {
50409 var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
50410 var thisParameter;
50411 if (thisParameters.length) {
50412 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
50413 }
50414 var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
50415 var parameters = [];
50416 var _loop_8 = function (i) {
50417 var symbols = ts.mapDefined(candidates, function (_a) {
50418 var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter;
50419 return hasRestParameter ?
50420 i < parameters.length - 1 ? parameters[i] : ts.last(parameters) :
50421 i < parameters.length ? parameters[i] : undefined;
50422 });
50423 ts.Debug.assert(symbols.length !== 0);
50424 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
50425 };
50426 for (var i = 0; i < maxNonRestParam; i++) {
50427 _loop_8(i);
50428 }
50429 var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; });
50430 var hasRestParameter = restParameterSymbols.length !== 0;
50431 if (hasRestParameter) {
50432 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
50433 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
50434 }
50435 return createSignature(candidates[0].declaration,
50436 /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
50437 thisParameter, parameters,
50438 /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)),
50439 /*typePredicate*/ undefined, minArgumentCount, hasRestParameter,
50440 /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; }));
50441 }
50442 function getNumNonRestParameters(signature) {
50443 var numParams = signature.parameters.length;
50444 return signature.hasRestParameter ? numParams - 1 : numParams;
50445 }
50446 function createCombinedSymbolFromTypes(sources, types) {
50447 return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
50448 }
50449 function createCombinedSymbolForOverloadFailure(sources, type) {
50450 // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
50451 return createSymbolWithType(ts.first(sources), type);
50452 }
50453 function pickLongestCandidateSignature(node, candidates, args) {
50454 // Pick the longest signature. This way we can get a contextual type for cases like:
50455 // declare function f(a: { xa: number; xb: number; }, b: number);
50456 // f({ |
50457 // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
50458 // declare function f<T>(k: keyof T);
50459 // f<Foo>("
50460 var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
50461 var candidate = candidates[bestIndex];
50462 var typeParameters = candidate.typeParameters;
50463 if (!typeParameters) {
50464 return candidate;
50465 }
50466 var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
50467 var instantiated = typeArgumentNodes
50468 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
50469 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
50470 candidates[bestIndex] = instantiated;
50471 return instantiated;
50472 }
50473 function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
50474 var typeArguments = typeArgumentNodes.map(getTypeOfNode);
50475 while (typeArguments.length > typeParameters.length) {
50476 typeArguments.pop();
50477 }
50478 while (typeArguments.length < typeParameters.length) {
50479 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
50480 }
50481 return typeArguments;
50482 }
50483 function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
50484 var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
50485 var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
50486 return createSignatureInstantiation(candidate, typeArgumentTypes);
50487 }
50488 function getLongestCandidateIndex(candidates, argsCount) {
50489 var maxParamsIndex = -1;
50490 var maxParams = -1;
50491 for (var i = 0; i < candidates.length; i++) {
50492 var candidate = candidates[i];
50493 var paramCount = getParameterCount(candidate);
50494 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
50495 return i;
50496 }
50497 if (paramCount > maxParams) {
50498 maxParams = paramCount;
50499 maxParamsIndex = i;
50500 }
50501 }
50502 return maxParamsIndex;
50503 }
50504 function resolveCallExpression(node, candidatesOutArray, checkMode) {
50505 if (node.expression.kind === 98 /* SuperKeyword */) {
50506 var superType = checkSuperExpression(node.expression);
50507 if (isTypeAny(superType)) {
50508 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
50509 var arg = _a[_i];
50510 checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
50511 }
50512 return anySignature;
50513 }
50514 if (superType !== errorType) {
50515 // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
50516 // with the type arguments specified in the extends clause.
50517 var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
50518 if (baseTypeNode) {
50519 var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
50520 return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
50521 }
50522 }
50523 return resolveUntypedCall(node);
50524 }
50525 var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined);
50526 if (funcType === silentNeverType) {
50527 return silentNeverSignature;
50528 }
50529 var apparentType = getApparentType(funcType);
50530 if (apparentType === errorType) {
50531 // Another error has already been reported
50532 return resolveErrorCall(node);
50533 }
50534 // Technically, this signatures list may be incomplete. We are taking the apparent type,
50535 // but we are not including call signatures that may have been added to the Object or
50536 // Function interface, since they have none by default. This is a bit of a leap of faith
50537 // that the user will not add any.
50538 var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
50539 var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
50540 // TS 1.0 Spec: 4.12
50541 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
50542 // types are provided for the argument expressions, and the result is always of type Any.
50543 if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
50544 // The unknownType indicates that an error already occurred (and was reported). No
50545 // need to report another error in this case.
50546 if (funcType !== errorType && node.typeArguments) {
50547 error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
50548 }
50549 return resolveUntypedCall(node);
50550 }
50551 // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
50552 // TypeScript employs overload resolution in typed function calls in order to support functions
50553 // with multiple call signatures.
50554 if (!callSignatures.length) {
50555 if (numConstructSignatures) {
50556 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
50557 }
50558 else {
50559 var relatedInformation = void 0;
50560 if (node.arguments.length === 1) {
50561 var text = ts.getSourceFileOfNode(node).text;
50562 if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
50563 relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon);
50564 }
50565 }
50566 invocationError(node, apparentType, 0 /* Call */, relatedInformation);
50567 }
50568 return resolveErrorCall(node);
50569 }
50570 // When a call to a generic function is an argument to an outer call to a generic function for which
50571 // inference is in process, we have a choice to make. If the inner call relies on inferences made from
50572 // its contextual type to its return type, deferring the inner call processing allows the best possible
50573 // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
50574 // the inner call, the inner call should be processed early. There's no sure way to know which choice is
50575 // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
50576 // If no type arguments are specified in the inner call and at least one call signature is generic and
50577 // returns a function type, we choose to defer processing. This narrowly permits function composition
50578 // operators to flow inferences through return types, but otherwise processes calls right away. We
50579 // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
50580 // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
50581 // from which we never make inferences).
50582 if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
50583 skippedGenericFunction(node, checkMode);
50584 return resolvingSignature;
50585 }
50586 // If the function is explicitly marked with `@class`, then it must be constructed.
50587 if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
50588 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
50589 return resolveErrorCall(node);
50590 }
50591 return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
50592 }
50593 function isGenericFunctionReturningFunction(signature) {
50594 return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
50595 }
50596 /**
50597 * TS 1.0 spec: 4.12
50598 * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
50599 * but is a subtype of the Function interface, the call is an untyped function call.
50600 */
50601 function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
50602 // We exclude union types because we may have a union of function types that happen to have no common signatures.
50603 return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
50604 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
50605 }
50606 function resolveNewExpression(node, candidatesOutArray, checkMode) {
50607 if (node.arguments && languageVersion < 1 /* ES5 */) {
50608 var spreadIndex = getSpreadArgumentIndex(node.arguments);
50609 if (spreadIndex >= 0) {
50610 error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
50611 }
50612 }
50613 var expressionType = checkNonNullExpression(node.expression);
50614 if (expressionType === silentNeverType) {
50615 return silentNeverSignature;
50616 }
50617 // If expressionType's apparent type(section 3.8.1) is an object type with one or
50618 // more construct signatures, the expression is processed in the same manner as a
50619 // function call, but using the construct signatures as the initial set of candidate
50620 // signatures for overload resolution. The result type of the function call becomes
50621 // the result type of the operation.
50622 expressionType = getApparentType(expressionType);
50623 if (expressionType === errorType) {
50624 // Another error has already been reported
50625 return resolveErrorCall(node);
50626 }
50627 // TS 1.0 spec: 4.11
50628 // If expressionType is of type Any, Args can be any argument
50629 // list and the result of the operation is of type Any.
50630 if (isTypeAny(expressionType)) {
50631 if (node.typeArguments) {
50632 error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
50633 }
50634 return resolveUntypedCall(node);
50635 }
50636 // Technically, this signatures list may be incomplete. We are taking the apparent type,
50637 // but we are not including construct signatures that may have been added to the Object or
50638 // Function interface, since they have none by default. This is a bit of a leap of faith
50639 // that the user will not add any.
50640 var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
50641 if (constructSignatures.length) {
50642 if (!isConstructorAccessible(node, constructSignatures[0])) {
50643 return resolveErrorCall(node);
50644 }
50645 // If the expression is a class of abstract type, then it cannot be instantiated.
50646 // Note, only class declarations can be declared abstract.
50647 // In the case of a merged class-module or class-interface declaration,
50648 // only the class declaration node will have the Abstract flag set.
50649 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
50650 if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) {
50651 error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
50652 return resolveErrorCall(node);
50653 }
50654 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
50655 }
50656 // If expressionType's apparent type is an object type with no construct signatures but
50657 // one or more call signatures, the expression is processed as a function call. A compile-time
50658 // error occurs if the result of the function call is not Void. The type of the result of the
50659 // operation is Any. It is an error to have a Void this type.
50660 var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
50661 if (callSignatures.length) {
50662 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
50663 if (!noImplicitAny) {
50664 if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
50665 error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
50666 }
50667 if (getThisTypeOfSignature(signature) === voidType) {
50668 error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
50669 }
50670 }
50671 return signature;
50672 }
50673 invocationError(node, expressionType, 1 /* Construct */);
50674 return resolveErrorCall(node);
50675 }
50676 function typeHasProtectedAccessibleBase(target, type) {
50677 var baseTypes = getBaseTypes(type);
50678 if (!ts.length(baseTypes)) {
50679 return false;
50680 }
50681 var firstBase = baseTypes[0];
50682 if (firstBase.flags & 2097152 /* Intersection */) {
50683 var types = firstBase.types;
50684 var mixinFlags = findMixins(types);
50685 var i = 0;
50686 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
50687 var intersectionMember = _a[_i];
50688 // We want to ignore mixin ctors
50689 if (!mixinFlags[i]) {
50690 if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
50691 if (intersectionMember.symbol === target) {
50692 return true;
50693 }
50694 if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
50695 return true;
50696 }
50697 }
50698 }
50699 i++;
50700 }
50701 return false;
50702 }
50703 if (firstBase.symbol === target) {
50704 return true;
50705 }
50706 return typeHasProtectedAccessibleBase(target, firstBase);
50707 }
50708 function isConstructorAccessible(node, signature) {
50709 if (!signature || !signature.declaration) {
50710 return true;
50711 }
50712 var declaration = signature.declaration;
50713 var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
50714 // Public constructor is accessible.
50715 if (!modifiers) {
50716 return true;
50717 }
50718 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
50719 var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
50720 // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
50721 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
50722 var containingClass = ts.getContainingClass(node);
50723 if (containingClass && modifiers & 16 /* Protected */) {
50724 var containingType = getTypeOfNode(containingClass);
50725 if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
50726 return true;
50727 }
50728 }
50729 if (modifiers & 8 /* Private */) {
50730 error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
50731 }
50732 if (modifiers & 16 /* Protected */) {
50733 error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
50734 }
50735 return false;
50736 }
50737 return true;
50738 }
50739 function invocationError(node, apparentType, kind, relatedInformation) {
50740 var diagnostic = error(node, (kind === 0 /* Call */ ?
50741 ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures :
50742 ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType));
50743 invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
50744 }
50745 function invocationErrorRecovery(apparentType, kind, diagnostic) {
50746 if (!apparentType.symbol) {
50747 return;
50748 }
50749 var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
50750 // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
50751 // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site
50752 if (importNode && !ts.isImportCall(importNode)) {
50753 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
50754 if (!sigs || !sigs.length)
50755 return;
50756 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.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));
50757 }
50758 }
50759 function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
50760 var tagType = checkExpression(node.tag);
50761 var apparentType = getApparentType(tagType);
50762 if (apparentType === errorType) {
50763 // Another error has already been reported
50764 return resolveErrorCall(node);
50765 }
50766 var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
50767 var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
50768 if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
50769 return resolveUntypedCall(node);
50770 }
50771 if (!callSignatures.length) {
50772 invocationError(node, apparentType, 0 /* Call */);
50773 return resolveErrorCall(node);
50774 }
50775 return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
50776 }
50777 /**
50778 * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
50779 */
50780 function getDiagnosticHeadMessageForDecoratorResolution(node) {
50781 switch (node.parent.kind) {
50782 case 240 /* ClassDeclaration */:
50783 case 209 /* ClassExpression */:
50784 return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
50785 case 151 /* Parameter */:
50786 return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
50787 case 154 /* PropertyDeclaration */:
50788 return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
50789 case 156 /* MethodDeclaration */:
50790 case 158 /* GetAccessor */:
50791 case 159 /* SetAccessor */:
50792 return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
50793 default:
50794 return ts.Debug.fail();
50795 }
50796 }
50797 /**
50798 * Resolves a decorator as if it were a call expression.
50799 */
50800 function resolveDecorator(node, candidatesOutArray, checkMode) {
50801 var funcType = checkExpression(node.expression);
50802 var apparentType = getApparentType(funcType);
50803 if (apparentType === errorType) {
50804 return resolveErrorCall(node);
50805 }
50806 var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
50807 var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
50808 if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
50809 return resolveUntypedCall(node);
50810 }
50811 if (isPotentiallyUncalledDecorator(node, callSignatures)) {
50812 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
50813 error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr);
50814 return resolveErrorCall(node);
50815 }
50816 var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
50817 if (!callSignatures.length) {
50818 var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType));
50819 errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage);
50820 var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo);
50821 diagnostics.add(diag);
50822 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
50823 return resolveErrorCall(node);
50824 }
50825 return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
50826 }
50827 function createSignatureForJSXIntrinsic(node, result) {
50828 var namespace = getJsxNamespaceAt(node);
50829 var exports = namespace && getExportsOfSymbol(namespace);
50830 // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
50831 // file would probably be preferable.
50832 var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 67897832 /* Type */);
50833 var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 67897832 /* Type */, node);
50834 var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(120 /* AnyKeyword */));
50835 var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
50836 parameterSymbol.type = result;
50837 return createSignature(declaration,
50838 /*typeParameters*/ undefined,
50839 /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType,
50840 /*returnTypePredicate*/ undefined, 1,
50841 /*hasRestparameter*/ false,
50842 /*hasLiteralTypes*/ false);
50843 }
50844 function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
50845 if (isJsxIntrinsicIdentifier(node.tagName)) {
50846 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
50847 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
50848 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
50849 return fakeSignature;
50850 }
50851 var exprTypes = checkExpression(node.tagName);
50852 var apparentType = getApparentType(exprTypes);
50853 if (apparentType === errorType) {
50854 return resolveErrorCall(node);
50855 }
50856 var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
50857 if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
50858 return resolveUntypedCall(node);
50859 }
50860 if (signatures.length === 0) {
50861 // We found no signatures at all, which is an error
50862 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
50863 return resolveErrorCall(node);
50864 }
50865 return resolveCall(node, signatures, candidatesOutArray, checkMode);
50866 }
50867 /**
50868 * Sometimes, we have a decorator that could accept zero arguments,
50869 * but is receiving too many arguments as part of the decorator invocation.
50870 * In those cases, a user may have meant to *call* the expression before using it as a decorator.
50871 */
50872 function isPotentiallyUncalledDecorator(decorator, signatures) {
50873 return signatures.length && ts.every(signatures, function (signature) {
50874 return signature.minArgumentCount === 0 &&
50875 !signature.hasRestParameter &&
50876 signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
50877 });
50878 }
50879 function resolveSignature(node, candidatesOutArray, checkMode) {
50880 switch (node.kind) {
50881 case 191 /* CallExpression */:
50882 return resolveCallExpression(node, candidatesOutArray, checkMode);
50883 case 192 /* NewExpression */:
50884 return resolveNewExpression(node, candidatesOutArray, checkMode);
50885 case 193 /* TaggedTemplateExpression */:
50886 return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
50887 case 152 /* Decorator */:
50888 return resolveDecorator(node, candidatesOutArray, checkMode);
50889 case 262 /* JsxOpeningElement */:
50890 case 261 /* JsxSelfClosingElement */:
50891 return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
50892 }
50893 throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
50894 }
50895 /**
50896 * Resolve a signature of a given call-like expression.
50897 * @param node a call-like expression to try resolve a signature for
50898 * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
50899 * the function will fill it up with appropriate candidate signatures
50900 * @return a signature of the call-like expression or undefined if one can't be found
50901 */
50902 function getResolvedSignature(node, candidatesOutArray, checkMode) {
50903 var links = getNodeLinks(node);
50904 // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
50905 // However, it is possible that either candidatesOutArray was not passed in the first time,
50906 // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
50907 // to correctly fill the candidatesOutArray.
50908 var cached = links.resolvedSignature;
50909 if (cached && cached !== resolvingSignature && !candidatesOutArray) {
50910 return cached;
50911 }
50912 links.resolvedSignature = resolvingSignature;
50913 var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
50914 // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
50915 // resolution should be deferred.
50916 if (result !== resolvingSignature) {
50917 // If signature resolution originated in control flow type analysis (for example to compute the
50918 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
50919 // types from the control flow analysis.
50920 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
50921 }
50922 return result;
50923 }
50924 /**
50925 * Indicates whether a declaration can be treated as a constructor in a JavaScript
50926 * file.
50927 */
50928 function isJSConstructor(node) {
50929 if (!node || !ts.isInJSFile(node)) {
50930 return false;
50931 }
50932 var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
50933 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
50934 undefined;
50935 if (func) {
50936 // If the node has a @class tag, treat it like a constructor.
50937 if (ts.getJSDocClassTag(node))
50938 return true;
50939 // If the symbol of the node has members, treat it like a constructor.
50940 var symbol = getSymbolOfNode(func);
50941 return !!symbol && (symbol.members !== undefined || symbol.exports !== undefined && symbol.exports.get("prototype") !== undefined);
50942 }
50943 return false;
50944 }
50945 function isJSConstructorType(type) {
50946 if (type.flags & 524288 /* Object */) {
50947 var resolved = resolveStructuredTypeMembers(type);
50948 return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration);
50949 }
50950 return false;
50951 }
50952 function getJSClassType(symbol) {
50953 var inferred;
50954 if (isJSConstructor(symbol.valueDeclaration)) {
50955 inferred = getInferredClassType(symbol);
50956 }
50957 var assigned = getAssignedClassType(symbol);
50958 return assigned && inferred ?
50959 getIntersectionType([inferred, assigned]) :
50960 assigned || inferred;
50961 }
50962 function getAssignedClassType(symbol) {
50963 var decl = symbol.valueDeclaration;
50964 var assignmentSymbol = decl && decl.parent &&
50965 (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) ||
50966 ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) ||
50967 ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent));
50968 var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype");
50969 var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
50970 return init ? checkExpression(init) : undefined;
50971 }
50972 function getAssignedJSPrototype(node) {
50973 if (!node.parent) {
50974 return false;
50975 }
50976 var parent = node.parent;
50977 while (parent && parent.kind === 189 /* PropertyAccessExpression */) {
50978 parent = parent.parent;
50979 }
50980 if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 59 /* EqualsToken */) {
50981 var right = ts.getInitializerOfBinaryExpression(parent);
50982 return ts.isObjectLiteralExpression(right) && right;
50983 }
50984 }
50985 function getInferredClassType(symbol) {
50986 var links = getSymbolLinks(symbol);
50987 if (!links.inferredClassType) {
50988 links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
50989 }
50990 return links.inferredClassType;
50991 }
50992 /**
50993 * Syntactically and semantically checks a call or new expression.
50994 * @param node The call/new expression to be checked.
50995 * @returns On success, the expression's signature's return type. On failure, anyType.
50996 */
50997 function checkCallExpression(node, checkMode) {
50998 if (!checkGrammarTypeArguments(node, node.typeArguments))
50999 checkGrammarArguments(node.arguments);
51000 var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
51001 if (signature === resolvingSignature) {
51002 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
51003 // returns a function type. We defer checking and return nonInferrableType.
51004 return nonInferrableType;
51005 }
51006 if (node.expression.kind === 98 /* SuperKeyword */) {
51007 return voidType;
51008 }
51009 if (node.kind === 192 /* NewExpression */) {
51010 var declaration = signature.declaration;
51011 if (declaration &&
51012 declaration.kind !== 157 /* Constructor */ &&
51013 declaration.kind !== 161 /* ConstructSignature */ &&
51014 declaration.kind !== 166 /* ConstructorType */ &&
51015 !ts.isJSDocConstructSignature(declaration) &&
51016 !isJSConstructor(declaration)) {
51017 // When resolved signature is a call signature (and not a construct signature) the result type is any
51018 if (noImplicitAny) {
51019 error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
51020 }
51021 return anyType;
51022 }
51023 }
51024 // In JavaScript files, calls to any identifier 'require' are treated as external module imports
51025 if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
51026 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
51027 }
51028 var returnType = getReturnTypeOfSignature(signature);
51029 // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
51030 // as a fresh unique symbol literal type.
51031 if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
51032 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
51033 }
51034 var jsAssignmentType;
51035 if (ts.isInJSFile(node)) {
51036 var decl = ts.getDeclarationOfExpando(node);
51037 if (decl) {
51038 var jsSymbol = getSymbolOfNode(decl);
51039 if (jsSymbol && ts.hasEntries(jsSymbol.exports)) {
51040 jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
51041 jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
51042 }
51043 }
51044 }
51045 return jsAssignmentType ? getIntersectionType([returnType, jsAssignmentType]) : returnType;
51046 }
51047 function isSymbolOrSymbolForCall(node) {
51048 if (!ts.isCallExpression(node))
51049 return false;
51050 var left = node.expression;
51051 if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
51052 left = left.expression;
51053 }
51054 if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
51055 return false;
51056 }
51057 // make sure `Symbol` is the global symbol
51058 var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
51059 if (!globalESSymbol) {
51060 return false;
51061 }
51062 return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
51063 }
51064 function checkImportCallExpression(node) {
51065 // Check grammar of dynamic import
51066 if (!checkGrammarArguments(node.arguments))
51067 checkGrammarImportCallExpression(node);
51068 if (node.arguments.length === 0) {
51069 return createPromiseReturnType(node, anyType);
51070 }
51071 var specifier = node.arguments[0];
51072 var specifierType = checkExpressionCached(specifier);
51073 // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
51074 for (var i = 1; i < node.arguments.length; ++i) {
51075 checkExpressionCached(node.arguments[i]);
51076 }
51077 if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
51078 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
51079 }
51080 // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
51081 var moduleSymbol = resolveExternalModuleName(node, specifier);
51082 if (moduleSymbol) {
51083 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true);
51084 if (esModuleSymbol) {
51085 return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
51086 }
51087 }
51088 return createPromiseReturnType(node, anyType);
51089 }
51090 function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
51091 if (allowSyntheticDefaultImports && type && type !== errorType) {
51092 var synthType = type;
51093 if (!synthType.syntheticType) {
51094 var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
51095 var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
51096 if (hasSyntheticDefault) {
51097 var memberTable = ts.createSymbolTable();
51098 var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
51099 newSymbol.nameType = getLiteralType("default");
51100 newSymbol.target = resolveSymbol(symbol);
51101 memberTable.set("default" /* Default */, newSymbol);
51102 var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
51103 var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
51104 anonymousSymbol.type = defaultContainingObject;
51105 synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
51106 }
51107 else {
51108 synthType.syntheticType = type;
51109 }
51110 }
51111 return synthType.syntheticType;
51112 }
51113 return type;
51114 }
51115 function isCommonJsRequire(node) {
51116 if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
51117 return false;
51118 }
51119 // Make sure require is not a local function
51120 if (!ts.isIdentifier(node.expression))
51121 return ts.Debug.fail();
51122 var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
51123 if (resolvedRequire === requireSymbol) {
51124 return true;
51125 }
51126 // project includes symbol named 'require' - make sure that it is ambient and local non-alias
51127 if (resolvedRequire.flags & 2097152 /* Alias */) {
51128 return false;
51129 }
51130 var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
51131 ? 239 /* FunctionDeclaration */
51132 : resolvedRequire.flags & 3 /* Variable */
51133 ? 237 /* VariableDeclaration */
51134 : 0 /* Unknown */;
51135 if (targetDeclarationKind !== 0 /* Unknown */) {
51136 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
51137 // function/variable declaration should be ambient
51138 return !!decl && !!(decl.flags & 4194304 /* Ambient */);
51139 }
51140 return false;
51141 }
51142 function checkTaggedTemplateExpression(node) {
51143 checkGrammarTypeArguments(node, node.typeArguments);
51144 if (languageVersion < 2 /* ES2015 */) {
51145 checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */);
51146 }
51147 return getReturnTypeOfSignature(getResolvedSignature(node));
51148 }
51149 function checkAssertion(node) {
51150 return checkAssertionWorker(node, node.type, node.expression);
51151 }
51152 function isValidConstAssertionArgument(node) {
51153 switch (node.kind) {
51154 case 10 /* StringLiteral */:
51155 case 14 /* NoSubstitutionTemplateLiteral */:
51156 case 8 /* NumericLiteral */:
51157 case 9 /* BigIntLiteral */:
51158 case 102 /* TrueKeyword */:
51159 case 87 /* FalseKeyword */:
51160 case 187 /* ArrayLiteralExpression */:
51161 case 188 /* ObjectLiteralExpression */:
51162 return true;
51163 case 195 /* ParenthesizedExpression */:
51164 return isValidConstAssertionArgument(node.expression);
51165 case 202 /* PrefixUnaryExpression */:
51166 var op = node.operator;
51167 var arg = node.operand;
51168 return op === 39 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
51169 op === 38 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
51170 }
51171 return false;
51172 }
51173 function checkAssertionWorker(errNode, type, expression, checkMode) {
51174 var exprType = checkExpression(expression, checkMode);
51175 if (ts.isConstTypeReference(type)) {
51176 if (!isValidConstAssertionArgument(expression)) {
51177 error(expression, ts.Diagnostics.A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal);
51178 }
51179 return getRegularTypeOfLiteralType(exprType);
51180 }
51181 checkSourceElement(type);
51182 exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
51183 var targetType = getTypeFromTypeNode(type);
51184 if (produceDiagnostics && targetType !== errorType) {
51185 var widenedType = getWidenedType(exprType);
51186 if (!isTypeComparableTo(targetType, widenedType)) {
51187 checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.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);
51188 }
51189 }
51190 return targetType;
51191 }
51192 function checkNonNullAssertion(node) {
51193 return getNonNullableType(checkExpression(node.expression));
51194 }
51195 function checkMetaProperty(node) {
51196 checkGrammarMetaProperty(node);
51197 if (node.keywordToken === 95 /* NewKeyword */) {
51198 return checkNewTargetMetaProperty(node);
51199 }
51200 if (node.keywordToken === 92 /* ImportKeyword */) {
51201 return checkImportMetaProperty(node);
51202 }
51203 return ts.Debug.assertNever(node.keywordToken);
51204 }
51205 function checkNewTargetMetaProperty(node) {
51206 var container = ts.getNewTargetContainer(node);
51207 if (!container) {
51208 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
51209 return errorType;
51210 }
51211 else if (container.kind === 157 /* Constructor */) {
51212 var symbol = getSymbolOfNode(container.parent);
51213 return getTypeOfSymbol(symbol);
51214 }
51215 else {
51216 var symbol = getSymbolOfNode(container);
51217 return getTypeOfSymbol(symbol);
51218 }
51219 }
51220 function checkImportMetaProperty(node) {
51221 if (languageVersion < 7 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
51222 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options);
51223 }
51224 var file = ts.getSourceFileOfNode(node);
51225 ts.Debug.assert(!!(file.flags & 1048576 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
51226 ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
51227 return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
51228 }
51229 function getTypeOfParameter(symbol) {
51230 var type = getTypeOfSymbol(symbol);
51231 if (strictNullChecks) {
51232 var declaration = symbol.valueDeclaration;
51233 if (declaration && ts.hasInitializer(declaration)) {
51234 return getOptionalType(type);
51235 }
51236 }
51237 return type;
51238 }
51239 function getParameterNameAtPosition(signature, pos) {
51240 var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
51241 if (pos < paramCount) {
51242 return signature.parameters[pos].escapedName;
51243 }
51244 var restParameter = signature.parameters[paramCount] || unknownSymbol;
51245 var restType = getTypeOfSymbol(restParameter);
51246 if (isTupleType(restType)) {
51247 var associatedNames = restType.target.associatedNames;
51248 var index = pos - paramCount;
51249 return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
51250 }
51251 return restParameter.escapedName;
51252 }
51253 function getTypeAtPosition(signature, pos) {
51254 return tryGetTypeAtPosition(signature, pos) || anyType;
51255 }
51256 function tryGetTypeAtPosition(signature, pos) {
51257 var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
51258 if (pos < paramCount) {
51259 return getTypeOfParameter(signature.parameters[pos]);
51260 }
51261 if (signature.hasRestParameter) {
51262 // We want to return the value undefined for an out of bounds parameter position,
51263 // so we need to check bounds here before calling getIndexedAccessType (which
51264 // otherwise would return the type 'undefined').
51265 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
51266 var index = pos - paramCount;
51267 if (!isTupleType(restType) || restType.target.hasRestElement || index < (restType.typeArguments || ts.emptyArray).length) {
51268 return getIndexedAccessType(restType, getLiteralType(index));
51269 }
51270 }
51271 return undefined;
51272 }
51273 function getRestTypeAtPosition(source, pos) {
51274 var paramCount = getParameterCount(source);
51275 var restType = getEffectiveRestType(source);
51276 var nonRestCount = paramCount - (restType ? 1 : 0);
51277 if (restType && pos === nonRestCount) {
51278 return restType;
51279 }
51280 var types = [];
51281 var names = [];
51282 for (var i = pos; i < nonRestCount; i++) {
51283 types.push(getTypeAtPosition(source, i));
51284 names.push(getParameterNameAtPosition(source, i));
51285 }
51286 if (restType) {
51287 types.push(getIndexedAccessType(restType, numberType));
51288 names.push(getParameterNameAtPosition(source, nonRestCount));
51289 }
51290 var minArgumentCount = getMinArgumentCount(source);
51291 var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
51292 return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
51293 }
51294 function getParameterCount(signature) {
51295 var length = signature.parameters.length;
51296 if (signature.hasRestParameter) {
51297 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
51298 if (isTupleType(restType)) {
51299 return length + (restType.typeArguments || ts.emptyArray).length - 1;
51300 }
51301 }
51302 return length;
51303 }
51304 function getMinArgumentCount(signature) {
51305 if (signature.hasRestParameter) {
51306 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
51307 if (isTupleType(restType)) {
51308 var minLength = restType.target.minLength;
51309 if (minLength > 0) {
51310 return signature.parameters.length - 1 + minLength;
51311 }
51312 }
51313 }
51314 return signature.minArgumentCount;
51315 }
51316 function hasEffectiveRestParameter(signature) {
51317 if (signature.hasRestParameter) {
51318 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
51319 return !isTupleType(restType) || restType.target.hasRestElement;
51320 }
51321 return false;
51322 }
51323 function getEffectiveRestType(signature) {
51324 if (signature.hasRestParameter) {
51325 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
51326 return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType;
51327 }
51328 return undefined;
51329 }
51330 function getNonArrayRestType(signature) {
51331 var restType = getEffectiveRestType(signature);
51332 return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined;
51333 }
51334 function getTypeOfFirstParameterOfSignature(signature) {
51335 return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
51336 }
51337 function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
51338 return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
51339 }
51340 function inferFromAnnotatedParameters(signature, context, inferenceContext) {
51341 var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
51342 for (var i = 0; i < len; i++) {
51343 var declaration = signature.parameters[i].valueDeclaration;
51344 if (declaration.type) {
51345 var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
51346 if (typeNode) {
51347 inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
51348 }
51349 }
51350 }
51351 var restType = getEffectiveRestType(context);
51352 if (restType && restType.flags & 262144 /* TypeParameter */) {
51353 // The contextual signature has a generic rest parameter. We first instantiate the contextual
51354 // signature (without fixing type parameters) and assign types to contextually typed parameters.
51355 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
51356 assignContextualParameterTypes(signature, instantiatedContext);
51357 // We then infer from a tuple type representing the parameters that correspond to the contextual
51358 // rest parameter.
51359 var restPos = getParameterCount(context) - 1;
51360 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
51361 }
51362 }
51363 function assignContextualParameterTypes(signature, context) {
51364 signature.typeParameters = context.typeParameters;
51365 if (context.thisParameter) {
51366 var parameter = signature.thisParameter;
51367 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
51368 if (!parameter) {
51369 signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
51370 }
51371 assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
51372 }
51373 }
51374 var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
51375 for (var i = 0; i < len; i++) {
51376 var parameter = signature.parameters[i];
51377 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
51378 var contextualParameterType = getTypeAtPosition(context, i);
51379 assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType);
51380 }
51381 }
51382 if (signature.hasRestParameter) {
51383 // parameter might be a transient symbol generated by use of `arguments` in the function body.
51384 var parameter = ts.last(signature.parameters);
51385 if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
51386 var contextualParameterType = getRestTypeAtPosition(context, len);
51387 assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType);
51388 }
51389 }
51390 }
51391 // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
51392 // the destructured type into the contained binding elements.
51393 function assignBindingElementTypes(pattern) {
51394 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
51395 var element = _a[_i];
51396 if (!ts.isOmittedExpression(element)) {
51397 if (element.name.kind === 72 /* Identifier */) {
51398 getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
51399 }
51400 else {
51401 assignBindingElementTypes(element.name);
51402 }
51403 }
51404 }
51405 }
51406 function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) {
51407 var links = getSymbolLinks(parameter);
51408 if (!links.type) {
51409 links.type = contextualType;
51410 var decl = parameter.valueDeclaration;
51411 if (decl.name.kind !== 72 /* Identifier */) {
51412 // if inference didn't come up with anything but {}, fall back to the binding pattern if present.
51413 if (links.type === emptyObjectType) {
51414 links.type = getTypeFromBindingPattern(decl.name);
51415 }
51416 assignBindingElementTypes(decl.name);
51417 }
51418 }
51419 }
51420 function createPromiseType(promisedType) {
51421 // creates a `Promise<T>` type where `T` is the promisedType argument
51422 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
51423 if (globalPromiseType !== emptyGenericType) {
51424 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
51425 promisedType = getAwaitedType(promisedType) || emptyObjectType;
51426 return createTypeReference(globalPromiseType, [promisedType]);
51427 }
51428 return emptyObjectType;
51429 }
51430 function createPromiseLikeType(promisedType) {
51431 // creates a `PromiseLike<T>` type where `T` is the promisedType argument
51432 var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
51433 if (globalPromiseLikeType !== emptyGenericType) {
51434 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
51435 promisedType = getAwaitedType(promisedType) || emptyObjectType;
51436 return createTypeReference(globalPromiseLikeType, [promisedType]);
51437 }
51438 return emptyObjectType;
51439 }
51440 function createPromiseReturnType(func, promisedType) {
51441 var promiseType = createPromiseType(promisedType);
51442 if (promiseType === emptyObjectType) {
51443 error(func, ts.isImportCall(func) ?
51444 ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
51445 ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option);
51446 return errorType;
51447 }
51448 else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
51449 error(func, ts.isImportCall(func) ?
51450 ts.Diagnostics.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 :
51451 ts.Diagnostics.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);
51452 }
51453 return promiseType;
51454 }
51455 function getReturnTypeFromBody(func, checkMode) {
51456 if (!func.body) {
51457 return errorType;
51458 }
51459 var functionFlags = ts.getFunctionFlags(func);
51460 var type;
51461 if (func.body.kind !== 218 /* Block */) {
51462 type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
51463 if (functionFlags & 2 /* Async */) {
51464 // From within an async function you can return either a non-promise value or a promise. Any
51465 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
51466 // return type of the body should be unwrapped to its awaited type, which we will wrap in
51467 // the native Promise<T> type later in this function.
51468 type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
51469 }
51470 }
51471 else {
51472 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
51473 if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function
51474 types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types);
51475 if (!types || types.length === 0) {
51476 var iterableIteratorAny = functionFlags & 2 /* Async */
51477 ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function
51478 : createIterableIteratorType(anyType); // Generator function
51479 if (noImplicitAny) {
51480 error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny));
51481 }
51482 return iterableIteratorAny;
51483 }
51484 }
51485 else {
51486 if (!types) {
51487 // For an async function, the return type will not be never, but rather a Promise for never.
51488 return functionFlags & 2 /* Async */
51489 ? createPromiseReturnType(func, neverType) // Async function
51490 : neverType; // Normal function
51491 }
51492 if (types.length === 0) {
51493 // For an async function, the return type will not be void, but rather a Promise for void.
51494 return functionFlags & 2 /* Async */
51495 ? createPromiseReturnType(func, voidType) // Async function
51496 : voidType; // Normal function
51497 }
51498 }
51499 // Return a union of the return expression types.
51500 type = getUnionType(types, 2 /* Subtype */);
51501 }
51502 var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
51503 if (!contextualSignature) {
51504 reportErrorsFromWidening(func, type);
51505 }
51506 if (isUnitType(type)) {
51507 var contextualType = !contextualSignature ? undefined :
51508 contextualSignature === getSignatureFromDeclaration(func) ? type :
51509 getReturnTypeOfSignature(contextualSignature);
51510 if (contextualType) {
51511 switch (functionFlags & 3 /* AsyncGenerator */) {
51512 case 3 /* AsyncGenerator */:
51513 contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ true);
51514 break;
51515 case 1 /* Generator */:
51516 contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ false);
51517 break;
51518 case 2 /* Async */:
51519 contextualType = getPromisedTypeOfPromise(contextualType);
51520 break;
51521 }
51522 }
51523 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51524 }
51525 var widenedType = getWidenedType(type);
51526 switch (functionFlags & 3 /* AsyncGenerator */) {
51527 case 3 /* AsyncGenerator */:
51528 return createAsyncIterableIteratorType(widenedType);
51529 case 1 /* Generator */:
51530 return createIterableIteratorType(widenedType);
51531 case 2 /* Async */:
51532 // From within an async function you can return either a non-promise value or a promise. Any
51533 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
51534 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
51535 return createPromiseType(widenedType);
51536 default:
51537 return widenedType;
51538 }
51539 }
51540 function checkAndAggregateYieldOperandTypes(func, checkMode) {
51541 var aggregatedTypes = [];
51542 var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
51543 ts.forEachYieldExpression(func.body, function (yieldExpression) {
51544 ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode));
51545 });
51546 return aggregatedTypes;
51547 }
51548 function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) {
51549 var errorNode = node.expression || node;
51550 var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType;
51551 // A `yield*` expression effectively yields everything that its operand yields
51552 var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType;
51553 return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
51554 ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
51555 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
51556 }
51557 /**
51558 * Collect the TypeFacts learned from a typeof switch with
51559 * total clauses `witnesses`, and the active clause ranging
51560 * from `start` to `end`. Parameter `hasDefault` denotes
51561 * whether the active clause contains a default clause.
51562 */
51563 function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
51564 var facts = 0 /* None */;
51565 // When in the default we only collect inequality facts
51566 // because default is 'in theory' a set of infinite
51567 // equalities.
51568 if (hasDefault) {
51569 // Value is not equal to any types after the active clause.
51570 for (var i = end; i < witnesses.length; i++) {
51571 facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
51572 }
51573 // Remove inequalities for types that appear in the
51574 // active clause because they appear before other
51575 // types collected so far.
51576 for (var i = start; i < end; i++) {
51577 facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
51578 }
51579 // Add inequalities for types before the active clause unconditionally.
51580 for (var i = 0; i < start; i++) {
51581 facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
51582 }
51583 }
51584 // When in an active clause without default the set of
51585 // equalities is finite.
51586 else {
51587 // Add equalities for all types in the active clause.
51588 for (var i = start; i < end; i++) {
51589 facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
51590 }
51591 // Remove equalities for types that appear before the
51592 // active clause.
51593 for (var i = 0; i < start; i++) {
51594 facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
51595 }
51596 }
51597 return facts;
51598 }
51599 function isExhaustiveSwitchStatement(node) {
51600 if (!node.possiblyExhaustive) {
51601 return false;
51602 }
51603 if (node.expression.kind === 199 /* TypeOfExpression */) {
51604 var operandType = getTypeOfExpression(node.expression.expression);
51605 // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined.
51606 var witnesses = getSwitchClauseTypeOfWitnesses(node);
51607 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
51608 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
51609 var type_5 = getBaseConstraintOfType(operandType) || operandType;
51610 return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
51611 }
51612 var type = getTypeOfExpression(node.expression);
51613 if (!isLiteralType(type)) {
51614 return false;
51615 }
51616 var switchTypes = getSwitchClauseTypes(node);
51617 if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
51618 return false;
51619 }
51620 return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
51621 }
51622 function functionHasImplicitReturn(func) {
51623 if (!(func.flags & 128 /* HasImplicitReturn */)) {
51624 return false;
51625 }
51626 if (ts.some(func.body.statements, function (statement) { return statement.kind === 232 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) {
51627 return false;
51628 }
51629 return true;
51630 }
51631 /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
51632 function checkAndAggregateReturnExpressionTypes(func, checkMode) {
51633 var functionFlags = ts.getFunctionFlags(func);
51634 var aggregatedTypes = [];
51635 var hasReturnWithNoExpression = functionHasImplicitReturn(func);
51636 var hasReturnOfTypeNever = false;
51637 ts.forEachReturnStatement(func.body, function (returnStatement) {
51638 var expr = returnStatement.expression;
51639 if (expr) {
51640 var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
51641 if (functionFlags & 2 /* Async */) {
51642 // From within an async function you can return either a non-promise value or a promise. Any
51643 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
51644 // return type of the body should be unwrapped to its awaited type, which should be wrapped in
51645 // the native Promise<T> type by the caller.
51646 type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
51647 }
51648 if (type.flags & 131072 /* Never */) {
51649 hasReturnOfTypeNever = true;
51650 }
51651 ts.pushIfUnique(aggregatedTypes, type);
51652 }
51653 else {
51654 hasReturnWithNoExpression = true;
51655 }
51656 });
51657 if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
51658 return undefined;
51659 }
51660 if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
51661 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
51662 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
51663 ts.pushIfUnique(aggregatedTypes, undefinedType);
51664 }
51665 return aggregatedTypes;
51666 }
51667 function mayReturnNever(func) {
51668 switch (func.kind) {
51669 case 196 /* FunctionExpression */:
51670 case 197 /* ArrowFunction */:
51671 return true;
51672 case 156 /* MethodDeclaration */:
51673 return func.parent.kind === 188 /* ObjectLiteralExpression */;
51674 default:
51675 return false;
51676 }
51677 }
51678 /**
51679 * TypeScript Specification 1.0 (6.3) - July 2014
51680 * An explicitly typed function whose return type isn't the Void type,
51681 * the Any type, or a union type containing the Void or Any type as a constituent
51682 * must have at least one return statement somewhere in its body.
51683 * An exception to this rule is if the function implementation consists of a single 'throw' statement.
51684 *
51685 * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
51686 */
51687 function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
51688 if (!produceDiagnostics) {
51689 return;
51690 }
51691 // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
51692 if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16384 /* Void */)) {
51693 return;
51694 }
51695 // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
51696 // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
51697 if (func.kind === 155 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 218 /* Block */ || !functionHasImplicitReturn(func)) {
51698 return;
51699 }
51700 var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */;
51701 if (returnType && returnType.flags & 131072 /* Never */) {
51702 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
51703 }
51704 else if (returnType && !hasExplicitReturn) {
51705 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
51706 // this function does not conform to the specification.
51707 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
51708 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
51709 }
51710 else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) {
51711 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
51712 }
51713 else if (compilerOptions.noImplicitReturns) {
51714 if (!returnType) {
51715 // If return type annotation is omitted check if function has any explicit return statements.
51716 // If it does not have any - its inferred return type is void - don't do any checks.
51717 // Otherwise get inferred return type from function body and report error only if it is not void / anytype
51718 if (!hasExplicitReturn) {
51719 return;
51720 }
51721 var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
51722 if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
51723 return;
51724 }
51725 }
51726 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
51727 }
51728 }
51729 function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
51730 ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
51731 checkNodeDeferred(node);
51732 // The identityMapper object is used to indicate that function expressions are wildcards
51733 if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
51734 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
51735 if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
51736 var links_1 = getNodeLinks(node);
51737 if (links_1.contextFreeType) {
51738 return links_1.contextFreeType;
51739 }
51740 var returnType = getReturnTypeFromBody(node, checkMode);
51741 var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
51742 var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
51743 returnOnlyType.objectFlags |= 524288 /* NonInferrableType */;
51744 return links_1.contextFreeType = returnOnlyType;
51745 }
51746 return anyFunctionType;
51747 }
51748 // Grammar checking
51749 var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
51750 if (!hasGrammarError && node.kind === 196 /* FunctionExpression */) {
51751 checkGrammarForGenerator(node);
51752 }
51753 var links = getNodeLinks(node);
51754 var type = getTypeOfSymbol(getMergedSymbol(node.symbol));
51755 if (isTypeAny(type)) {
51756 return type;
51757 }
51758 // Check if function expression is contextually typed and assign parameter types if so.
51759 if (!(links.flags & 1024 /* ContextChecked */)) {
51760 var contextualSignature = getContextualSignature(node);
51761 // If a type check is started at a function expression that is an argument of a function call, obtaining the
51762 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
51763 // already assigned contextual types.
51764 if (!(links.flags & 1024 /* ContextChecked */)) {
51765 links.flags |= 1024 /* ContextChecked */;
51766 if (contextualSignature) {
51767 var signature = getSignaturesOfType(type, 0 /* Call */)[0];
51768 if (isContextSensitive(node)) {
51769 var inferenceContext = getInferenceContext(node);
51770 if (checkMode && checkMode & 2 /* Inferential */) {
51771 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
51772 }
51773 var instantiatedContextualSignature = inferenceContext ?
51774 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
51775 assignContextualParameterTypes(signature, instantiatedContextualSignature);
51776 }
51777 if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
51778 var returnType = getReturnTypeFromBody(node, checkMode);
51779 if (!signature.resolvedReturnType) {
51780 signature.resolvedReturnType = returnType;
51781 }
51782 }
51783 }
51784 checkSignatureDeclaration(node);
51785 }
51786 }
51787 return type;
51788 }
51789 function getReturnOrPromisedType(node, functionFlags) {
51790 var type = getReturnTypeFromAnnotation(node);
51791 return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ?
51792 getAwaitedType(type) || errorType : type;
51793 }
51794 function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
51795 ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
51796 var functionFlags = ts.getFunctionFlags(node);
51797 var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags);
51798 if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function
51799 // return is not necessary in the body of generators
51800 checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
51801 }
51802 if (node.body) {
51803 if (!ts.getEffectiveReturnTypeNode(node)) {
51804 // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
51805 // we need. An example is the noImplicitAny errors resulting from widening the return expression
51806 // of a function. Because checking of function expression bodies is deferred, there was never an
51807 // appropriate time to do this during the main walk of the file (see the comment at the top of
51808 // checkFunctionExpressionBodies). So it must be done now.
51809 getReturnTypeOfSignature(getSignatureFromDeclaration(node));
51810 }
51811 if (node.body.kind === 218 /* Block */) {
51812 checkSourceElement(node.body);
51813 }
51814 else {
51815 // From within an async function you can return either a non-promise value or a promise. Any
51816 // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
51817 // should not be checking assignability of a promise to the return type. Instead, we need to
51818 // check assignability of the awaited type of the expression body against the promised type of
51819 // its return type annotation.
51820 var exprType = checkExpression(node.body);
51821 if (returnOrPromisedType) {
51822 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
51823 var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
51824 checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
51825 }
51826 else { // Normal function
51827 checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
51828 }
51829 }
51830 }
51831 }
51832 }
51833 function checkArithmeticOperandType(operand, type, diagnostic) {
51834 if (!isTypeAssignableTo(type, numberOrBigIntType)) {
51835 error(operand, diagnostic);
51836 return false;
51837 }
51838 return true;
51839 }
51840 function isReadonlyAssignmentDeclaration(d) {
51841 if (!ts.isCallExpression(d)) {
51842 return false;
51843 }
51844 if (!ts.isBindableObjectDefinePropertyCall(d)) {
51845 return false;
51846 }
51847 var objectLitType = checkExpressionCached(d.arguments[2]);
51848 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
51849 if (valueType) {
51850 var writableProp = getPropertyOfType(objectLitType, "writable");
51851 var writableType = writableProp && getTypeOfSymbol(writableProp);
51852 if (!writableType || writableType === falseType || writableType === regularFalseType) {
51853 return true;
51854 }
51855 // We include this definition whereupon we walk back and check the type at the declaration because
51856 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
51857 // argument types, should the type be contextualized by the call itself.
51858 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
51859 var initializer = writableProp.valueDeclaration.initializer;
51860 var rawOriginalType = checkExpression(initializer);
51861 if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
51862 return true;
51863 }
51864 }
51865 return false;
51866 }
51867 var setProp = getPropertyOfType(objectLitType, "set");
51868 return !setProp;
51869 }
51870 function isReadonlySymbol(symbol) {
51871 // The following symbols are considered read-only:
51872 // Properties with a 'readonly' modifier
51873 // Variables declared with 'const'
51874 // Get accessors without matching set accessors
51875 // Enum members
51876 // Object.defineProperty assignments with writable false or no setter
51877 // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
51878 return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
51879 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
51880 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
51881 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
51882 symbol.flags & 8 /* EnumMember */ ||
51883 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
51884 }
51885 function isReferenceToReadonlyEntity(expr, symbol) {
51886 if (isReadonlySymbol(symbol)) {
51887 // Allow assignments to readonly properties within constructors of the same class declaration.
51888 if (symbol.flags & 4 /* Property */ &&
51889 (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) &&
51890 expr.expression.kind === 100 /* ThisKeyword */) {
51891 // Look for if this is the constructor for the class that `symbol` is a property of.
51892 var func = ts.getContainingFunction(expr);
51893 if (!(func && func.kind === 157 /* Constructor */)) {
51894 return true;
51895 }
51896 // If func.parent is a class and symbol is a (readonly) property of that class, or
51897 // if func is a constructor and symbol is a (readonly) parameter property declared in it,
51898 // then symbol is writeable here.
51899 return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent);
51900 }
51901 return true;
51902 }
51903 return false;
51904 }
51905 function isReferenceThroughNamespaceImport(expr) {
51906 if (expr.kind === 189 /* PropertyAccessExpression */ || expr.kind === 190 /* ElementAccessExpression */) {
51907 var node = ts.skipParentheses(expr.expression);
51908 if (node.kind === 72 /* Identifier */) {
51909 var symbol = getNodeLinks(node).resolvedSymbol;
51910 if (symbol.flags & 2097152 /* Alias */) {
51911 var declaration = getDeclarationOfAliasSymbol(symbol);
51912 return !!declaration && declaration.kind === 251 /* NamespaceImport */;
51913 }
51914 }
51915 }
51916 return false;
51917 }
51918 function checkReferenceExpression(expr, invalidReferenceMessage) {
51919 // References are combinations of identifiers, parentheses, and property accesses.
51920 var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */);
51921 if (node.kind !== 72 /* Identifier */ && node.kind !== 189 /* PropertyAccessExpression */ && node.kind !== 190 /* ElementAccessExpression */) {
51922 error(expr, invalidReferenceMessage);
51923 return false;
51924 }
51925 return true;
51926 }
51927 function checkDeleteExpression(node) {
51928 checkExpression(node.expression);
51929 var expr = ts.skipParentheses(node.expression);
51930 if (expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) {
51931 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
51932 return booleanType;
51933 }
51934 var links = getNodeLinks(expr);
51935 var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
51936 if (symbol && isReadonlySymbol(symbol)) {
51937 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
51938 }
51939 return booleanType;
51940 }
51941 function checkTypeOfExpression(node) {
51942 checkExpression(node.expression);
51943 return typeofType;
51944 }
51945 function checkVoidExpression(node) {
51946 checkExpression(node.expression);
51947 return undefinedWideningType;
51948 }
51949 function checkAwaitExpression(node) {
51950 // Grammar checking
51951 if (produceDiagnostics) {
51952 if (!(node.flags & 16384 /* AwaitContext */)) {
51953 grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function);
51954 }
51955 if (isInParameterInitializerBeforeContainingFunction(node)) {
51956 error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
51957 }
51958 }
51959 var operandType = checkExpression(node.expression);
51960 return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
51961 }
51962 function checkPrefixUnaryExpression(node) {
51963 var operandType = checkExpression(node.operand);
51964 if (operandType === silentNeverType) {
51965 return silentNeverType;
51966 }
51967 switch (node.operand.kind) {
51968 case 8 /* NumericLiteral */:
51969 switch (node.operator) {
51970 case 39 /* MinusToken */:
51971 return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
51972 case 38 /* PlusToken */:
51973 return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
51974 }
51975 break;
51976 case 9 /* BigIntLiteral */:
51977 if (node.operator === 39 /* MinusToken */) {
51978 return getFreshTypeOfLiteralType(getLiteralType({
51979 negative: true,
51980 base10Value: ts.parsePseudoBigInt(node.operand.text)
51981 }));
51982 }
51983 }
51984 switch (node.operator) {
51985 case 38 /* PlusToken */:
51986 case 39 /* MinusToken */:
51987 case 53 /* TildeToken */:
51988 checkNonNullType(operandType, node.operand);
51989 if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
51990 error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
51991 }
51992 if (node.operator === 38 /* PlusToken */) {
51993 if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
51994 error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(operandType));
51995 }
51996 return numberType;
51997 }
51998 return getUnaryResultType(operandType);
51999 case 52 /* ExclamationToken */:
52000 checkTruthinessExpression(node.operand);
52001 var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
52002 return facts === 4194304 /* Truthy */ ? falseType :
52003 facts === 8388608 /* Falsy */ ? trueType :
52004 booleanType;
52005 case 44 /* PlusPlusToken */:
52006 case 45 /* MinusMinusToken */:
52007 var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type);
52008 if (ok) {
52009 // run check only if former checks succeeded to avoid reporting cascading errors
52010 checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access);
52011 }
52012 return getUnaryResultType(operandType);
52013 }
52014 return errorType;
52015 }
52016 function checkPostfixUnaryExpression(node) {
52017 var operandType = checkExpression(node.operand);
52018 if (operandType === silentNeverType) {
52019 return silentNeverType;
52020 }
52021 var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type);
52022 if (ok) {
52023 // run check only if former checks succeeded to avoid reporting cascading errors
52024 checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access);
52025 }
52026 return getUnaryResultType(operandType);
52027 }
52028 function getUnaryResultType(operandType) {
52029 if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
52030 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
52031 ? numberOrBigIntType
52032 : bigintType;
52033 }
52034 // If it's not a bigint type, implicit coercion will result in a number
52035 return numberType;
52036 }
52037 // Return true if type might be of the given kind. A union or intersection type might be of a given
52038 // kind if at least one constituent type is of the given kind.
52039 function maybeTypeOfKind(type, kind) {
52040 if (type.flags & kind & ~131072 /* GenericMappedType */ || kind & 131072 /* GenericMappedType */ && isGenericMappedType(type)) {
52041 return true;
52042 }
52043 if (type.flags & 3145728 /* UnionOrIntersection */) {
52044 var types = type.types;
52045 for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
52046 var t = types_16[_i];
52047 if (maybeTypeOfKind(t, kind)) {
52048 return true;
52049 }
52050 }
52051 }
52052 return false;
52053 }
52054 function isTypeAssignableToKind(source, kind, strict) {
52055 if (source.flags & kind) {
52056 return true;
52057 }
52058 if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
52059 return false;
52060 }
52061 return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
52062 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
52063 !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
52064 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
52065 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
52066 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
52067 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
52068 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
52069 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
52070 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
52071 }
52072 function allTypesAssignableToKind(source, kind, strict) {
52073 return source.flags & 1048576 /* Union */ ?
52074 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
52075 isTypeAssignableToKind(source, kind, strict);
52076 }
52077 function isConstEnumObjectType(type) {
52078 return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
52079 }
52080 function isConstEnumSymbol(symbol) {
52081 return (symbol.flags & 128 /* ConstEnum */) !== 0;
52082 }
52083 function checkInstanceOfExpression(left, right, leftType, rightType) {
52084 if (leftType === silentNeverType || rightType === silentNeverType) {
52085 return silentNeverType;
52086 }
52087 // TypeScript 1.0 spec (April 2014): 4.15.4
52088 // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
52089 // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
52090 // The result is always of the Boolean primitive type.
52091 // NOTE: do not raise error if leftType is unknown as related error was already reported
52092 if (!isTypeAny(leftType) &&
52093 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
52094 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
52095 }
52096 // NOTE: do not raise error if right is unknown as related error was already reported
52097 if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
52098 error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type);
52099 }
52100 return booleanType;
52101 }
52102 function checkInExpression(left, right, leftType, rightType) {
52103 if (leftType === silentNeverType || rightType === silentNeverType) {
52104 return silentNeverType;
52105 }
52106 leftType = checkNonNullType(leftType, left);
52107 rightType = checkNonNullType(rightType, right);
52108 // TypeScript 1.0 spec (April 2014): 4.15.5
52109 // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
52110 // and the right operand to be of type Any, an object type, or a type parameter type.
52111 // The result is always of the Boolean primitive type.
52112 if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) {
52113 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
52114 }
52115 if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
52116 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
52117 }
52118 return booleanType;
52119 }
52120 function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
52121 var properties = node.properties;
52122 if (strictNullChecks && properties.length === 0) {
52123 return checkNonNullType(sourceType, node);
52124 }
52125 for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
52126 var p = properties_5[_i];
52127 checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis);
52128 }
52129 return sourceType;
52130 }
52131 /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
52132 function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) {
52133 if (rightIsThis === void 0) { rightIsThis = false; }
52134 if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) {
52135 var name = property.name;
52136 var exprType = getLiteralTypeFromPropertyName(name);
52137 if (isTypeUsableAsPropertyName(exprType)) {
52138 var text = getPropertyNameFromType(exprType);
52139 var prop = getPropertyOfType(objectLiteralType, text);
52140 if (prop) {
52141 markPropertyAsReferenced(prop, property, rightIsThis);
52142 checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
52143 }
52144 }
52145 var elementType = getIndexedAccessType(objectLiteralType, exprType, name);
52146 var type = getFlowTypeOfDestructuring(property, elementType);
52147 return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
52148 }
52149 else if (property.kind === 277 /* SpreadAssignment */) {
52150 if (languageVersion < 7 /* ESNext */) {
52151 checkExternalEmitHelpers(property, 4 /* Rest */);
52152 }
52153 var nonRestNames = [];
52154 if (allProperties) {
52155 for (var i = 0; i < allProperties.length - 1; i++) {
52156 nonRestNames.push(allProperties[i].name);
52157 }
52158 }
52159 var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
52160 checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
52161 return checkDestructuringAssignment(property.expression, type);
52162 }
52163 else {
52164 error(property, ts.Diagnostics.Property_assignment_expected);
52165 }
52166 }
52167 function checkArrayLiteralAssignment(node, sourceType, checkMode) {
52168 var elements = node.elements;
52169 if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
52170 checkExternalEmitHelpers(node, 512 /* Read */);
52171 }
52172 // This elementType will be used if the specific property corresponding to this index is not
52173 // present (aka the tuple element property). This call also checks that the parentType is in
52174 // fact an iterable or array (depending on target language).
52175 var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType;
52176 for (var i = 0; i < elements.length; i++) {
52177 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
52178 }
52179 return sourceType;
52180 }
52181 function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
52182 var elements = node.elements;
52183 var element = elements[elementIndex];
52184 if (element.kind !== 210 /* OmittedExpression */) {
52185 if (element.kind !== 208 /* SpreadElement */) {
52186 var indexType = getLiteralType(elementIndex);
52187 if (isArrayLikeType(sourceType)) {
52188 // We create a synthetic expression so that getIndexedAccessType doesn't get confused
52189 // when the element is a SyntaxKind.ElementAccessExpression.
52190 var elementType_2 = getIndexedAccessType(sourceType, indexType, createSyntheticExpression(element, indexType));
52191 var type = getFlowTypeOfDestructuring(element, elementType_2);
52192 return checkDestructuringAssignment(element, type, checkMode);
52193 }
52194 return checkDestructuringAssignment(element, elementType, checkMode);
52195 }
52196 if (elementIndex < elements.length - 1) {
52197 error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
52198 }
52199 else {
52200 var restExpression = element.expression;
52201 if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) {
52202 error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
52203 }
52204 else {
52205 checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
52206 var type = everyType(sourceType, isTupleType) ?
52207 mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
52208 createArrayType(elementType);
52209 return checkDestructuringAssignment(restExpression, type, checkMode);
52210 }
52211 }
52212 }
52213 return undefined;
52214 }
52215 function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
52216 var target;
52217 if (exprOrAssignment.kind === 276 /* ShorthandPropertyAssignment */) {
52218 var prop = exprOrAssignment;
52219 if (prop.objectAssignmentInitializer) {
52220 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
52221 // undefined from the final type.
52222 if (strictNullChecks &&
52223 !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
52224 sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
52225 }
52226 checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
52227 }
52228 target = exprOrAssignment.name;
52229 }
52230 else {
52231 target = exprOrAssignment;
52232 }
52233 if (target.kind === 204 /* BinaryExpression */ && target.operatorToken.kind === 59 /* EqualsToken */) {
52234 checkBinaryExpression(target, checkMode);
52235 target = target.left;
52236 }
52237 if (target.kind === 188 /* ObjectLiteralExpression */) {
52238 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
52239 }
52240 if (target.kind === 187 /* ArrayLiteralExpression */) {
52241 return checkArrayLiteralAssignment(target, sourceType, checkMode);
52242 }
52243 return checkReferenceAssignment(target, sourceType, checkMode);
52244 }
52245 function checkReferenceAssignment(target, sourceType, checkMode) {
52246 var targetType = checkExpression(target, checkMode);
52247 var error = target.parent.kind === 277 /* SpreadAssignment */ ?
52248 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
52249 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
52250 if (checkReferenceExpression(target, error)) {
52251 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
52252 }
52253 return sourceType;
52254 }
52255 /**
52256 * This is a *shallow* check: An expression is side-effect-free if the
52257 * evaluation of the expression *itself* cannot produce side effects.
52258 * For example, x++ / 3 is side-effect free because the / operator
52259 * does not have side effects.
52260 * The intent is to "smell test" an expression for correctness in positions where
52261 * its value is discarded (e.g. the left side of the comma operator).
52262 */
52263 function isSideEffectFree(node) {
52264 node = ts.skipParentheses(node);
52265 switch (node.kind) {
52266 case 72 /* Identifier */:
52267 case 10 /* StringLiteral */:
52268 case 13 /* RegularExpressionLiteral */:
52269 case 193 /* TaggedTemplateExpression */:
52270 case 206 /* TemplateExpression */:
52271 case 14 /* NoSubstitutionTemplateLiteral */:
52272 case 8 /* NumericLiteral */:
52273 case 9 /* BigIntLiteral */:
52274 case 102 /* TrueKeyword */:
52275 case 87 /* FalseKeyword */:
52276 case 96 /* NullKeyword */:
52277 case 141 /* UndefinedKeyword */:
52278 case 196 /* FunctionExpression */:
52279 case 209 /* ClassExpression */:
52280 case 197 /* ArrowFunction */:
52281 case 187 /* ArrayLiteralExpression */:
52282 case 188 /* ObjectLiteralExpression */:
52283 case 199 /* TypeOfExpression */:
52284 case 213 /* NonNullExpression */:
52285 case 261 /* JsxSelfClosingElement */:
52286 case 260 /* JsxElement */:
52287 return true;
52288 case 205 /* ConditionalExpression */:
52289 return isSideEffectFree(node.whenTrue) &&
52290 isSideEffectFree(node.whenFalse);
52291 case 204 /* BinaryExpression */:
52292 if (ts.isAssignmentOperator(node.operatorToken.kind)) {
52293 return false;
52294 }
52295 return isSideEffectFree(node.left) &&
52296 isSideEffectFree(node.right);
52297 case 202 /* PrefixUnaryExpression */:
52298 case 203 /* PostfixUnaryExpression */:
52299 // Unary operators ~, !, +, and - have no side effects.
52300 // The rest do.
52301 switch (node.operator) {
52302 case 52 /* ExclamationToken */:
52303 case 38 /* PlusToken */:
52304 case 39 /* MinusToken */:
52305 case 53 /* TildeToken */:
52306 return true;
52307 }
52308 return false;
52309 // Some forms listed here for clarity
52310 case 200 /* VoidExpression */: // Explicit opt-out
52311 case 194 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
52312 case 212 /* AsExpression */: // Not SEF, but can produce useful type warnings
52313 default:
52314 return false;
52315 }
52316 }
52317 function isTypeEqualityComparableTo(source, target) {
52318 return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
52319 }
52320 function checkBinaryExpression(node, checkMode) {
52321 if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
52322 return checkExpression(node.right, checkMode);
52323 }
52324 return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node);
52325 }
52326 function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
52327 var operator = operatorToken.kind;
52328 if (operator === 59 /* EqualsToken */ && (left.kind === 188 /* ObjectLiteralExpression */ || left.kind === 187 /* ArrayLiteralExpression */)) {
52329 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 100 /* ThisKeyword */);
52330 }
52331 var leftType;
52332 if (operator === 54 /* AmpersandAmpersandToken */ || operator === 55 /* BarBarToken */) {
52333 leftType = checkTruthinessExpression(left, checkMode);
52334 }
52335 else {
52336 leftType = checkExpression(left, checkMode);
52337 }
52338 var rightType = checkExpression(right, checkMode);
52339 switch (operator) {
52340 case 40 /* AsteriskToken */:
52341 case 41 /* AsteriskAsteriskToken */:
52342 case 62 /* AsteriskEqualsToken */:
52343 case 63 /* AsteriskAsteriskEqualsToken */:
52344 case 42 /* SlashToken */:
52345 case 64 /* SlashEqualsToken */:
52346 case 43 /* PercentToken */:
52347 case 65 /* PercentEqualsToken */:
52348 case 39 /* MinusToken */:
52349 case 61 /* MinusEqualsToken */:
52350 case 46 /* LessThanLessThanToken */:
52351 case 66 /* LessThanLessThanEqualsToken */:
52352 case 47 /* GreaterThanGreaterThanToken */:
52353 case 67 /* GreaterThanGreaterThanEqualsToken */:
52354 case 48 /* GreaterThanGreaterThanGreaterThanToken */:
52355 case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
52356 case 50 /* BarToken */:
52357 case 70 /* BarEqualsToken */:
52358 case 51 /* CaretToken */:
52359 case 71 /* CaretEqualsToken */:
52360 case 49 /* AmpersandToken */:
52361 case 69 /* AmpersandEqualsToken */:
52362 if (leftType === silentNeverType || rightType === silentNeverType) {
52363 return silentNeverType;
52364 }
52365 leftType = checkNonNullType(leftType, left);
52366 rightType = checkNonNullType(rightType, right);
52367 var suggestedOperator = void 0;
52368 // if a user tries to apply a bitwise operator to 2 boolean operands
52369 // try and return them a helpful suggestion
52370 if ((leftType.flags & 528 /* BooleanLike */) &&
52371 (rightType.flags & 528 /* BooleanLike */) &&
52372 (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
52373 error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator));
52374 return numberType;
52375 }
52376 else {
52377 // otherwise just check each operand separately and report errors as normal
52378 var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type);
52379 var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type);
52380 var resultType_1;
52381 // If both are any or unknown, allow operation; assume it will resolve to number
52382 if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
52383 // Or, if neither could be bigint, implicit coercion results in a number result
52384 !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
52385 resultType_1 = numberType;
52386 }
52387 // At least one is assignable to bigint, so both should be only assignable to bigint
52388 else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */)) {
52389 switch (operator) {
52390 case 48 /* GreaterThanGreaterThanGreaterThanToken */:
52391 case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
52392 reportOperatorError();
52393 }
52394 resultType_1 = bigintType;
52395 }
52396 else {
52397 reportOperatorError();
52398 resultType_1 = errorType;
52399 }
52400 if (leftOk && rightOk) {
52401 checkAssignmentOperator(resultType_1);
52402 }
52403 return resultType_1;
52404 }
52405 case 38 /* PlusToken */:
52406 case 60 /* PlusEqualsToken */:
52407 if (leftType === silentNeverType || rightType === silentNeverType) {
52408 return silentNeverType;
52409 }
52410 if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) {
52411 leftType = checkNonNullType(leftType, left);
52412 rightType = checkNonNullType(rightType, right);
52413 }
52414 var resultType = void 0;
52415 if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
52416 // Operands of an enum type are treated as having the primitive type Number.
52417 // If both operands are of the Number primitive type, the result is of the Number primitive type.
52418 resultType = numberType;
52419 }
52420 else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
52421 // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
52422 resultType = bigintType;
52423 }
52424 else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) {
52425 // If one or both operands are of the String primitive type, the result is of the String primitive type.
52426 resultType = stringType;
52427 }
52428 else if (isTypeAny(leftType) || isTypeAny(rightType)) {
52429 // Otherwise, the result is of type Any.
52430 // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
52431 resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
52432 }
52433 // Symbols are not allowed at all in arithmetic expressions
52434 if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
52435 return resultType;
52436 }
52437 if (!resultType) {
52438 reportOperatorError();
52439 return anyType;
52440 }
52441 if (operator === 60 /* PlusEqualsToken */) {
52442 checkAssignmentOperator(resultType);
52443 }
52444 return resultType;
52445 case 28 /* LessThanToken */:
52446 case 30 /* GreaterThanToken */:
52447 case 31 /* LessThanEqualsToken */:
52448 case 32 /* GreaterThanEqualsToken */:
52449 if (checkForDisallowedESSymbolOperand(operator)) {
52450 leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
52451 rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
52452 if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) ||
52453 (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)))) {
52454 reportOperatorError();
52455 }
52456 }
52457 return booleanType;
52458 case 33 /* EqualsEqualsToken */:
52459 case 34 /* ExclamationEqualsToken */:
52460 case 35 /* EqualsEqualsEqualsToken */:
52461 case 36 /* ExclamationEqualsEqualsToken */:
52462 var leftIsLiteral = isLiteralType(leftType);
52463 var rightIsLiteral = isLiteralType(rightType);
52464 if (!leftIsLiteral || !rightIsLiteral) {
52465 leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType;
52466 rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType;
52467 }
52468 if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) {
52469 reportOperatorError();
52470 }
52471 return booleanType;
52472 case 94 /* InstanceOfKeyword */:
52473 return checkInstanceOfExpression(left, right, leftType, rightType);
52474 case 93 /* InKeyword */:
52475 return checkInExpression(left, right, leftType, rightType);
52476 case 54 /* AmpersandAmpersandToken */:
52477 return getTypeFacts(leftType) & 4194304 /* Truthy */ ?
52478 getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
52479 leftType;
52480 case 55 /* BarBarToken */:
52481 return getTypeFacts(leftType) & 8388608 /* Falsy */ ?
52482 getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
52483 leftType;
52484 case 59 /* EqualsToken */:
52485 var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
52486 checkAssignmentDeclaration(declKind, rightType);
52487 if (isAssignmentDeclaration(declKind)) {
52488 if (!(rightType.flags & 524288 /* Object */) ||
52489 declKind !== 2 /* ModuleExports */ &&
52490 declKind !== 6 /* Prototype */ &&
52491 !isEmptyObjectType(rightType) &&
52492 !isFunctionObjectType(rightType) &&
52493 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
52494 // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
52495 checkAssignmentOperator(rightType);
52496 }
52497 return leftType;
52498 }
52499 else {
52500 checkAssignmentOperator(rightType);
52501 return getRegularTypeOfObjectLiteral(rightType);
52502 }
52503 case 27 /* CommaToken */:
52504 if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
52505 error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
52506 }
52507 return rightType;
52508 default:
52509 return ts.Debug.fail();
52510 }
52511 function checkAssignmentDeclaration(kind, rightType) {
52512 if (kind === 2 /* ModuleExports */) {
52513 for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
52514 var prop = _a[_i];
52515 var propType = getTypeOfSymbol(prop);
52516 if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
52517 var name = prop.escapedName;
52518 var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false);
52519 if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
52520 grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name));
52521 return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name));
52522 }
52523 }
52524 }
52525 }
52526 }
52527 function isEvalNode(node) {
52528 return node.kind === 72 /* Identifier */ && node.escapedText === "eval";
52529 }
52530 // Return true if there was no error, false if there was an error.
52531 function checkForDisallowedESSymbolOperand(operator) {
52532 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
52533 maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
52534 undefined;
52535 if (offendingSymbolOperand) {
52536 error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
52537 return false;
52538 }
52539 return true;
52540 }
52541 function getSuggestedBooleanOperator(operator) {
52542 switch (operator) {
52543 case 50 /* BarToken */:
52544 case 70 /* BarEqualsToken */:
52545 return 55 /* BarBarToken */;
52546 case 51 /* CaretToken */:
52547 case 71 /* CaretEqualsToken */:
52548 return 36 /* ExclamationEqualsEqualsToken */;
52549 case 49 /* AmpersandToken */:
52550 case 69 /* AmpersandEqualsToken */:
52551 return 54 /* AmpersandAmpersandToken */;
52552 default:
52553 return undefined;
52554 }
52555 }
52556 function checkAssignmentOperator(valueType) {
52557 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
52558 // TypeScript 1.0 spec (April 2014): 4.17
52559 // An assignment of the form
52560 // VarExpr = ValueExpr
52561 // requires VarExpr to be classified as a reference
52562 // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
52563 // and the type of the non-compound operation to be assignable to the type of VarExpr.
52564 if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)
52565 && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
52566 // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
52567 checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
52568 }
52569 }
52570 }
52571 function isAssignmentDeclaration(kind) {
52572 switch (kind) {
52573 case 2 /* ModuleExports */:
52574 return true;
52575 case 1 /* ExportsProperty */:
52576 case 5 /* Property */:
52577 case 6 /* Prototype */:
52578 case 3 /* PrototypeProperty */:
52579 case 4 /* ThisProperty */:
52580 var symbol = getSymbolOfNode(left);
52581 var init = ts.getAssignedExpandoInitializer(right);
52582 return init && ts.isObjectLiteralExpression(init) &&
52583 symbol && ts.hasEntries(symbol.exports);
52584 default:
52585 return false;
52586 }
52587 }
52588 function reportOperatorError() {
52589 var leftStr = typeToString(leftType);
52590 var rightStr = typeToString(rightType);
52591 var errNode = errorNode || operatorToken;
52592 if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) {
52593 error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
52594 }
52595 }
52596 function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) {
52597 switch (operatorToken.kind) {
52598 case 35 /* EqualsEqualsEqualsToken */:
52599 case 33 /* EqualsEqualsToken */:
52600 return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr);
52601 case 36 /* ExclamationEqualsEqualsToken */:
52602 case 34 /* ExclamationEqualsToken */:
52603 return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr);
52604 }
52605 return undefined;
52606 }
52607 }
52608 function isYieldExpressionInClass(node) {
52609 var current = node;
52610 var parent = node.parent;
52611 while (parent) {
52612 if (ts.isFunctionLike(parent) && current === parent.body) {
52613 return false;
52614 }
52615 else if (ts.isClassLike(current)) {
52616 return true;
52617 }
52618 current = parent;
52619 parent = parent.parent;
52620 }
52621 return false;
52622 }
52623 function checkYieldExpression(node) {
52624 // Grammar checking
52625 if (produceDiagnostics) {
52626 if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) {
52627 grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
52628 }
52629 if (isInParameterInitializerBeforeContainingFunction(node)) {
52630 error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
52631 }
52632 }
52633 var func = ts.getContainingFunction(node);
52634 if (!func)
52635 return anyType;
52636 var functionFlags = ts.getFunctionFlags(func);
52637 if (!(functionFlags & 1 /* Generator */)) {
52638 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
52639 return anyType;
52640 }
52641 if (node.asteriskToken) {
52642 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
52643 // and __asyncValues helpers
52644 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ &&
52645 languageVersion < 7 /* ESNext */) {
52646 checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
52647 }
52648 // Generator functions prior to ES2015 require the __values helper
52649 if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ &&
52650 languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
52651 checkExternalEmitHelpers(node, 256 /* Values */);
52652 }
52653 }
52654 var isAsync = (functionFlags & 2 /* Async */) !== 0;
52655 var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217
52656 // There is no point in doing an assignability check if the function
52657 // has no explicit return type because the return type is directly computed
52658 // from the yield expressions.
52659 var returnType = getReturnTypeFromAnnotation(func);
52660 if (returnType) {
52661 var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType;
52662 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression);
52663 }
52664 // Both yield and yield* expressions have type 'any'
52665 return anyType;
52666 }
52667 function checkConditionalExpression(node, checkMode) {
52668 checkTruthinessExpression(node.condition);
52669 var type1 = checkExpression(node.whenTrue, checkMode);
52670 var type2 = checkExpression(node.whenFalse, checkMode);
52671 return getUnionType([type1, type2], 2 /* Subtype */);
52672 }
52673 function checkTemplateExpression(node) {
52674 // We just want to check each expressions, but we are unconcerned with
52675 // the type of each expression, as any value may be coerced into a string.
52676 // It is worth asking whether this is what we really want though.
52677 // A place where we actually *are* concerned with the expressions' types are
52678 // in tagged templates.
52679 ts.forEach(node.templateSpans, function (templateSpan) {
52680 if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) {
52681 error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
52682 }
52683 });
52684 return stringType;
52685 }
52686 function getContextNode(node) {
52687 if (node.kind === 268 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
52688 return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes)
52689 }
52690 return node;
52691 }
52692 function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
52693 var context = getContextNode(node);
52694 var saveContextualType = context.contextualType;
52695 var saveInferenceContext = context.inferenceContext;
52696 context.contextualType = contextualType;
52697 context.inferenceContext = inferenceContext;
52698 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
52699 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
52700 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
52701 // here would be to not mark contextually typed literals as fresh in the first place.
52702 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
52703 getRegularTypeOfLiteralType(type) : type;
52704 context.contextualType = saveContextualType;
52705 context.inferenceContext = saveInferenceContext;
52706 return result;
52707 }
52708 function checkExpressionCached(node, checkMode) {
52709 var links = getNodeLinks(node);
52710 if (!links.resolvedType) {
52711 if (checkMode && checkMode !== 0 /* Normal */) {
52712 return checkExpression(node, checkMode);
52713 }
52714 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
52715 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
52716 // to the top of the stack ensures all transient types are computed from a known point.
52717 var saveFlowLoopStart = flowLoopStart;
52718 flowLoopStart = flowLoopCount;
52719 links.resolvedType = checkExpression(node, checkMode);
52720 flowLoopStart = saveFlowLoopStart;
52721 }
52722 return links.resolvedType;
52723 }
52724 function isTypeAssertion(node) {
52725 node = ts.skipParentheses(node);
52726 return node.kind === 194 /* TypeAssertionExpression */ || node.kind === 212 /* AsExpression */;
52727 }
52728 function checkDeclarationInitializer(declaration) {
52729 var initializer = ts.getEffectiveInitializer(declaration);
52730 var type = getTypeOfExpression(initializer, /*cache*/ true);
52731 var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ ||
52732 ts.isDeclarationReadonly(declaration) ||
52733 isTypeAssertion(initializer) ||
52734 isLiteralOfContextualType(type, getContextualType(initializer)) ? type : getWidenedLiteralType(type);
52735 if (ts.isInJSFile(declaration)) {
52736 if (widened.flags & 98304 /* Nullable */) {
52737 reportImplicitAny(declaration, anyType);
52738 return anyType;
52739 }
52740 else if (isEmptyArrayLiteralType(widened)) {
52741 reportImplicitAny(declaration, anyArrayType);
52742 return anyArrayType;
52743 }
52744 }
52745 return widened;
52746 }
52747 function isLiteralOfContextualType(candidateType, contextualType) {
52748 if (contextualType) {
52749 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
52750 var types = contextualType.types;
52751 return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
52752 }
52753 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
52754 // If the contextual type is a type variable constrained to a primitive type, consider
52755 // this a literal context for literals of that primitive type. For example, given a
52756 // type parameter 'T extends string', infer string literal types for T.
52757 var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType;
52758 return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
52759 maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
52760 maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
52761 maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
52762 isLiteralOfContextualType(candidateType, constraint);
52763 }
52764 // If the contextual type is a literal of a particular primitive type, we consider this a
52765 // literal context for all literals of that primitive type.
52766 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
52767 contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
52768 contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
52769 contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
52770 contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
52771 }
52772 return false;
52773 }
52774 function isConstContext(node) {
52775 var parent = node.parent;
52776 return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
52777 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
52778 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
52779 }
52780 function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
52781 var type = checkExpression(node, checkMode, forceTuple);
52782 return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
52783 isTypeAssertion(node) ? type :
52784 getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
52785 }
52786 function checkPropertyAssignment(node, checkMode) {
52787 // Do not use hasDynamicName here, because that returns false for well known symbols.
52788 // We want to perform checkComputedPropertyName for all computed properties, including
52789 // well known symbols.
52790 if (node.name.kind === 149 /* ComputedPropertyName */) {
52791 checkComputedPropertyName(node.name);
52792 }
52793 return checkExpressionForMutableLocation(node.initializer, checkMode);
52794 }
52795 function checkObjectLiteralMethod(node, checkMode) {
52796 // Grammar checking
52797 checkGrammarMethod(node);
52798 // Do not use hasDynamicName here, because that returns false for well known symbols.
52799 // We want to perform checkComputedPropertyName for all computed properties, including
52800 // well known symbols.
52801 if (node.name.kind === 149 /* ComputedPropertyName */) {
52802 checkComputedPropertyName(node.name);
52803 }
52804 var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
52805 return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
52806 }
52807 function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
52808 if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
52809 var signature = getSingleCallSignature(type);
52810 if (signature && signature.typeParameters) {
52811 if (checkMode & 8 /* SkipGenericFunctions */) {
52812 skippedGenericFunction(node, checkMode);
52813 return anyFunctionType;
52814 }
52815 var contextualType = getApparentTypeOfContextualType(node);
52816 if (contextualType) {
52817 var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
52818 if (contextualSignature && !contextualSignature.typeParameters) {
52819 var context = getInferenceContext(node);
52820 // We have an expression that is an argument of a generic function for which we are performing
52821 // type argument inference. The expression is of a function type with a single generic call
52822 // signature and a contextual function type with a single non-generic call signature. Now check
52823 // if the outer function returns a function type with a single non-generic call signature and
52824 // if some of the outer function type parameters have no inferences so far. If so, we can
52825 // potentially add inferred type parameters to the outer function return type.
52826 var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
52827 if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
52828 // Instantiate the signature with its own type parameters as type arguments, possibly
52829 // renaming the type parameters to ensure they have unique names.
52830 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
52831 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
52832 // Infer from the parameters of the instantiated signature to the parameters of the
52833 // contextual signature starting with an empty set of inference candidates.
52834 var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
52835 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
52836 inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true);
52837 });
52838 if (ts.some(inferences_2, hasInferenceCandidates)) {
52839 // We have inference candidates, indicating that one or more type parameters are referenced
52840 // in the parameter types of the contextual signature. Now also infer from the return type.
52841 applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
52842 inferTypes(inferences_2, source, target);
52843 });
52844 // If the type parameters for which we produced candidates do not have any inferences yet,
52845 // we adopt the new inference candidates and add the type parameters of the expression type
52846 // to the set of inferred type parameters for the outer function return type.
52847 if (!hasOverlappingInferences(context.inferences, inferences_2)) {
52848 mergeInferences(context.inferences, inferences_2);
52849 context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
52850 return getOrCreateTypeFromSignature(instantiatedSignature);
52851 }
52852 }
52853 }
52854 return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
52855 }
52856 }
52857 }
52858 }
52859 return type;
52860 }
52861 function skippedGenericFunction(node, checkMode) {
52862 if (checkMode & 2 /* Inferential */) {
52863 // We have skipped a generic function during inferential typing. Obtain the inference context and
52864 // indicate this has occurred such that we know a second pass of inference is be needed.
52865 var context = getInferenceContext(node);
52866 context.flags |= 4 /* SkippedGenericFunction */;
52867 }
52868 }
52869 function hasInferenceCandidates(info) {
52870 return !!(info.candidates || info.contraCandidates);
52871 }
52872 function hasOverlappingInferences(a, b) {
52873 for (var i = 0; i < a.length; i++) {
52874 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
52875 return true;
52876 }
52877 }
52878 return false;
52879 }
52880 function mergeInferences(target, source) {
52881 for (var i = 0; i < target.length; i++) {
52882 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
52883 target[i] = source[i];
52884 }
52885 }
52886 }
52887 function getUniqueTypeParameters(context, typeParameters) {
52888 var result = [];
52889 var oldTypeParameters;
52890 var newTypeParameters;
52891 for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
52892 var tp = typeParameters_2[_i];
52893 var name = tp.symbol.escapedName;
52894 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
52895 var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
52896 var symbol = createSymbol(262144 /* TypeParameter */, newName);
52897 var newTypeParameter = createTypeParameter(symbol);
52898 newTypeParameter.target = tp;
52899 oldTypeParameters = ts.append(oldTypeParameters, tp);
52900 newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
52901 result.push(newTypeParameter);
52902 }
52903 else {
52904 result.push(tp);
52905 }
52906 }
52907 if (newTypeParameters) {
52908 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
52909 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
52910 var tp = newTypeParameters_1[_a];
52911 tp.mapper = mapper;
52912 }
52913 }
52914 return result;
52915 }
52916 function hasTypeParameterByName(typeParameters, name) {
52917 return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
52918 }
52919 function getUniqueTypeParameterName(typeParameters, baseName) {
52920 var len = baseName.length;
52921 while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
52922 len--;
52923 var s = baseName.slice(0, len);
52924 for (var index = 1; true; index++) {
52925 var augmentedName = (s + index);
52926 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
52927 return augmentedName;
52928 }
52929 }
52930 }
52931 /**
52932 * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
52933 * with computing the type and may not fully check all contained sub-expressions for errors.
52934 * A cache argument of true indicates that if the function performs a full type check, it is ok
52935 * to cache the result.
52936 */
52937 function getTypeOfExpression(node, cache) {
52938 var expr = ts.skipParentheses(node);
52939 // Optimize for the common case of a call to a function with a single non-generic call
52940 // signature where we can just fetch the return type without checking the arguments.
52941 if (expr.kind === 191 /* CallExpression */ && expr.expression.kind !== 98 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
52942 var funcType = checkNonNullExpression(expr.expression);
52943 var signature = getSingleCallSignature(funcType);
52944 if (signature && !signature.typeParameters) {
52945 return getReturnTypeOfSignature(signature);
52946 }
52947 }
52948 else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
52949 return getTypeFromTypeNode(expr.type);
52950 }
52951 // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
52952 // should have a parameter that indicates whether full error checking is required such that
52953 // we can perform the optimizations locally.
52954 return cache ? checkExpressionCached(node) : checkExpression(node);
52955 }
52956 /**
52957 * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
52958 * with computing the type and may not fully check all contained sub-expressions for errors.
52959 * It is intended for uses where you know there is no contextual type,
52960 * and requesting the contextual type might cause a circularity or other bad behaviour.
52961 * It sets the contextual type of the node to any before calling getTypeOfExpression.
52962 */
52963 function getContextFreeTypeOfExpression(node) {
52964 var links = getNodeLinks(node);
52965 if (links.contextFreeType) {
52966 return links.contextFreeType;
52967 }
52968 var saveContextualType = node.contextualType;
52969 node.contextualType = anyType;
52970 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
52971 node.contextualType = saveContextualType;
52972 return type;
52973 }
52974 function checkExpression(node, checkMode, forceTuple) {
52975 var saveCurrentNode = currentNode;
52976 currentNode = node;
52977 var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
52978 var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
52979 if (isConstEnumObjectType(type)) {
52980 checkConstEnumAccess(node, type);
52981 }
52982 currentNode = saveCurrentNode;
52983 return type;
52984 }
52985 function checkConstEnumAccess(node, type) {
52986 // enum object type for const enums are only permitted in:
52987 // - 'left' in property access
52988 // - 'object' in indexed access
52989 // - target in rhs of import statement
52990 var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) ||
52991 (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) ||
52992 ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
52993 (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === node));
52994 if (!ok) {
52995 error(node, ts.Diagnostics.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);
52996 }
52997 if (compilerOptions.isolatedModules) {
52998 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
52999 var constEnumDeclaration = type.symbol.valueDeclaration;
53000 if (constEnumDeclaration.flags & 4194304 /* Ambient */) {
53001 error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
53002 }
53003 }
53004 }
53005 function checkParenthesizedExpression(node, checkMode) {
53006 var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
53007 if (tag) {
53008 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
53009 }
53010 return checkExpression(node.expression, checkMode);
53011 }
53012 function checkExpressionWorker(node, checkMode, forceTuple) {
53013 switch (node.kind) {
53014 case 72 /* Identifier */:
53015 return checkIdentifier(node);
53016 case 100 /* ThisKeyword */:
53017 return checkThisExpression(node);
53018 case 98 /* SuperKeyword */:
53019 return checkSuperExpression(node);
53020 case 96 /* NullKeyword */:
53021 return nullWideningType;
53022 case 14 /* NoSubstitutionTemplateLiteral */:
53023 case 10 /* StringLiteral */:
53024 return getFreshTypeOfLiteralType(getLiteralType(node.text));
53025 case 8 /* NumericLiteral */:
53026 checkGrammarNumericLiteral(node);
53027 return getFreshTypeOfLiteralType(getLiteralType(+node.text));
53028 case 9 /* BigIntLiteral */:
53029 checkGrammarBigIntLiteral(node);
53030 return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
53031 case 102 /* TrueKeyword */:
53032 return trueType;
53033 case 87 /* FalseKeyword */:
53034 return falseType;
53035 case 206 /* TemplateExpression */:
53036 return checkTemplateExpression(node);
53037 case 13 /* RegularExpressionLiteral */:
53038 return globalRegExpType;
53039 case 187 /* ArrayLiteralExpression */:
53040 return checkArrayLiteral(node, checkMode, forceTuple);
53041 case 188 /* ObjectLiteralExpression */:
53042 return checkObjectLiteral(node, checkMode);
53043 case 189 /* PropertyAccessExpression */:
53044 return checkPropertyAccessExpression(node);
53045 case 148 /* QualifiedName */:
53046 return checkQualifiedName(node);
53047 case 190 /* ElementAccessExpression */:
53048 return checkIndexedAccess(node);
53049 case 191 /* CallExpression */:
53050 if (node.expression.kind === 92 /* ImportKeyword */) {
53051 return checkImportCallExpression(node);
53052 }
53053 /* falls through */
53054 case 192 /* NewExpression */:
53055 return checkCallExpression(node, checkMode);
53056 case 193 /* TaggedTemplateExpression */:
53057 return checkTaggedTemplateExpression(node);
53058 case 195 /* ParenthesizedExpression */:
53059 return checkParenthesizedExpression(node, checkMode);
53060 case 209 /* ClassExpression */:
53061 return checkClassExpression(node);
53062 case 196 /* FunctionExpression */:
53063 case 197 /* ArrowFunction */:
53064 return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
53065 case 199 /* TypeOfExpression */:
53066 return checkTypeOfExpression(node);
53067 case 194 /* TypeAssertionExpression */:
53068 case 212 /* AsExpression */:
53069 return checkAssertion(node);
53070 case 213 /* NonNullExpression */:
53071 return checkNonNullAssertion(node);
53072 case 214 /* MetaProperty */:
53073 return checkMetaProperty(node);
53074 case 198 /* DeleteExpression */:
53075 return checkDeleteExpression(node);
53076 case 200 /* VoidExpression */:
53077 return checkVoidExpression(node);
53078 case 201 /* AwaitExpression */:
53079 return checkAwaitExpression(node);
53080 case 202 /* PrefixUnaryExpression */:
53081 return checkPrefixUnaryExpression(node);
53082 case 203 /* PostfixUnaryExpression */:
53083 return checkPostfixUnaryExpression(node);
53084 case 204 /* BinaryExpression */:
53085 return checkBinaryExpression(node, checkMode);
53086 case 205 /* ConditionalExpression */:
53087 return checkConditionalExpression(node, checkMode);
53088 case 208 /* SpreadElement */:
53089 return checkSpreadExpression(node, checkMode);
53090 case 210 /* OmittedExpression */:
53091 return undefinedWideningType;
53092 case 207 /* YieldExpression */:
53093 return checkYieldExpression(node);
53094 case 215 /* SyntheticExpression */:
53095 return node.type;
53096 case 270 /* JsxExpression */:
53097 return checkJsxExpression(node, checkMode);
53098 case 260 /* JsxElement */:
53099 return checkJsxElement(node, checkMode);
53100 case 261 /* JsxSelfClosingElement */:
53101 return checkJsxSelfClosingElement(node, checkMode);
53102 case 264 /* JsxFragment */:
53103 return checkJsxFragment(node);
53104 case 268 /* JsxAttributes */:
53105 return checkJsxAttributes(node, checkMode);
53106 case 262 /* JsxOpeningElement */:
53107 ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
53108 }
53109 return errorType;
53110 }
53111 // DECLARATION AND STATEMENT TYPE CHECKING
53112 function checkTypeParameter(node) {
53113 // Grammar Checking
53114 if (node.expression) {
53115 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
53116 }
53117 checkSourceElement(node.constraint);
53118 checkSourceElement(node.default);
53119 var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
53120 // Resolve base constraint to reveal circularity errors
53121 getBaseConstraintOfType(typeParameter);
53122 if (!hasNonCircularTypeParameterDefault(typeParameter)) {
53123 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
53124 }
53125 var constraintType = getConstraintOfTypeParameter(typeParameter);
53126 var defaultType = getDefaultFromTypeParameter(typeParameter);
53127 if (constraintType && defaultType) {
53128 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
53129 }
53130 if (produceDiagnostics) {
53131 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
53132 }
53133 }
53134 function checkParameter(node) {
53135 // Grammar checking
53136 // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
53137 // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
53138 // or if its FunctionBody is strict code(11.1.5).
53139 checkGrammarDecoratorsAndModifiers(node);
53140 checkVariableLikeDeclaration(node);
53141 var func = ts.getContainingFunction(node);
53142 if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
53143 if (!(func.kind === 157 /* Constructor */ && ts.nodeIsPresent(func.body))) {
53144 error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
53145 }
53146 }
53147 if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
53148 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
53149 }
53150 if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
53151 if (func.parameters.indexOf(node) !== 0) {
53152 error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
53153 }
53154 if (func.kind === 157 /* Constructor */ || func.kind === 161 /* ConstructSignature */ || func.kind === 166 /* ConstructorType */) {
53155 error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
53156 }
53157 if (func.kind === 197 /* ArrowFunction */) {
53158 error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
53159 }
53160 }
53161 // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
53162 // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
53163 if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) {
53164 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
53165 }
53166 }
53167 function checkTypePredicate(node) {
53168 var parent = getTypePredicateParent(node);
53169 if (!parent) {
53170 // The parent must not be valid.
53171 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
53172 return;
53173 }
53174 var signature = getSignatureFromDeclaration(parent);
53175 var typePredicate = getTypePredicateOfSignature(signature);
53176 if (!typePredicate) {
53177 return;
53178 }
53179 checkSourceElement(node.type);
53180 var parameterName = node.parameterName;
53181 if (ts.isThisTypePredicate(typePredicate)) {
53182 getTypeFromThisTypeNode(parameterName);
53183 }
53184 else {
53185 if (typePredicate.parameterIndex >= 0) {
53186 if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) {
53187 error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
53188 }
53189 else {
53190 var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
53191 checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type,
53192 /*headMessage*/ undefined, leadingError);
53193 }
53194 }
53195 else if (parameterName) {
53196 var hasReportedError = false;
53197 for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
53198 var name = _a[_i].name;
53199 if (ts.isBindingPattern(name) &&
53200 checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
53201 hasReportedError = true;
53202 break;
53203 }
53204 }
53205 if (!hasReportedError) {
53206 error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
53207 }
53208 }
53209 }
53210 }
53211 function getTypePredicateParent(node) {
53212 switch (node.parent.kind) {
53213 case 197 /* ArrowFunction */:
53214 case 160 /* CallSignature */:
53215 case 239 /* FunctionDeclaration */:
53216 case 196 /* FunctionExpression */:
53217 case 165 /* FunctionType */:
53218 case 156 /* MethodDeclaration */:
53219 case 155 /* MethodSignature */:
53220 var parent = node.parent;
53221 if (node === parent.type) {
53222 return parent;
53223 }
53224 }
53225 }
53226 function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
53227 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
53228 var element = _a[_i];
53229 if (ts.isOmittedExpression(element)) {
53230 continue;
53231 }
53232 var name = element.name;
53233 if (name.kind === 72 /* Identifier */ && name.escapedText === predicateVariableName) {
53234 error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
53235 return true;
53236 }
53237 else if (name.kind === 185 /* ArrayBindingPattern */ || name.kind === 184 /* ObjectBindingPattern */) {
53238 if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
53239 return true;
53240 }
53241 }
53242 }
53243 }
53244 function checkSignatureDeclaration(node) {
53245 // Grammar checking
53246 if (node.kind === 162 /* IndexSignature */) {
53247 checkGrammarIndexSignature(node);
53248 }
53249 // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
53250 else if (node.kind === 165 /* FunctionType */ || node.kind === 239 /* FunctionDeclaration */ || node.kind === 166 /* ConstructorType */ ||
53251 node.kind === 160 /* CallSignature */ || node.kind === 157 /* Constructor */ ||
53252 node.kind === 161 /* ConstructSignature */) {
53253 checkGrammarFunctionLikeDeclaration(node);
53254 }
53255 var functionFlags = ts.getFunctionFlags(node);
53256 if (!(functionFlags & 4 /* Invalid */)) {
53257 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
53258 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 7 /* ESNext */) {
53259 checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
53260 }
53261 // Async functions prior to ES2017 require the __awaiter helper
53262 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
53263 checkExternalEmitHelpers(node, 64 /* Awaiter */);
53264 }
53265 // Generator functions, Async functions, and Async Generator functions prior to
53266 // ES2015 require the __generator helper
53267 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
53268 checkExternalEmitHelpers(node, 128 /* Generator */);
53269 }
53270 }
53271 checkTypeParameters(node.typeParameters);
53272 ts.forEach(node.parameters, checkParameter);
53273 // TODO(rbuckton): Should we start checking JSDoc types?
53274 if (node.type) {
53275 checkSourceElement(node.type);
53276 }
53277 if (produceDiagnostics) {
53278 checkCollisionWithArgumentsInGeneratedCode(node);
53279 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
53280 if (noImplicitAny && !returnTypeNode) {
53281 switch (node.kind) {
53282 case 161 /* ConstructSignature */:
53283 error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
53284 break;
53285 case 160 /* CallSignature */:
53286 error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
53287 break;
53288 }
53289 }
53290 if (returnTypeNode) {
53291 var functionFlags_1 = ts.getFunctionFlags(node);
53292 if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
53293 var returnType = getTypeFromTypeNode(returnTypeNode);
53294 if (returnType === voidType) {
53295 error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
53296 }
53297 else {
53298 var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
53299 var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */
53300 ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function
53301 : createIterableIteratorType(generatorElementType); // Generator function
53302 // Naively, one could check that IterableIterator<any> is assignable to the return type annotation.
53303 // However, that would not catch the error in the following case.
53304 //
53305 // interface BadGenerator extends Iterable<number>, Iterator<string> { }
53306 // function* g(): BadGenerator { } // Iterable and Iterator have different types!
53307 //
53308 checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode);
53309 }
53310 }
53311 else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
53312 checkAsyncFunctionReturnType(node, returnTypeNode);
53313 }
53314 }
53315 if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
53316 registerForUnusedIdentifiersCheck(node);
53317 }
53318 }
53319 }
53320 function checkClassForDuplicateDeclarations(node) {
53321 var Declaration;
53322 (function (Declaration) {
53323 Declaration[Declaration["Getter"] = 1] = "Getter";
53324 Declaration[Declaration["Setter"] = 2] = "Setter";
53325 Declaration[Declaration["Method"] = 4] = "Method";
53326 Declaration[Declaration["Property"] = 3] = "Property";
53327 })(Declaration || (Declaration = {}));
53328 var instanceNames = ts.createUnderscoreEscapedMap();
53329 var staticNames = ts.createUnderscoreEscapedMap();
53330 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
53331 var member = _a[_i];
53332 if (member.kind === 157 /* Constructor */) {
53333 for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
53334 var param = _c[_b];
53335 if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) {
53336 addName(instanceNames, param.name, param.name.escapedText, 3 /* Property */);
53337 }
53338 }
53339 }
53340 else {
53341 var isStatic = ts.hasModifier(member, 32 /* Static */);
53342 var names = isStatic ? staticNames : instanceNames;
53343 var name = member.name;
53344 var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
53345 if (name && memberName) {
53346 switch (member.kind) {
53347 case 158 /* GetAccessor */:
53348 addName(names, name, memberName, 1 /* Getter */);
53349 break;
53350 case 159 /* SetAccessor */:
53351 addName(names, name, memberName, 2 /* Setter */);
53352 break;
53353 case 154 /* PropertyDeclaration */:
53354 addName(names, name, memberName, 3 /* Property */);
53355 break;
53356 case 156 /* MethodDeclaration */:
53357 addName(names, name, memberName, 4 /* Method */);
53358 break;
53359 }
53360 }
53361 }
53362 }
53363 function addName(names, location, name, meaning) {
53364 var prev = names.get(name);
53365 if (prev) {
53366 if (prev & 4 /* Method */) {
53367 if (meaning !== 4 /* Method */) {
53368 error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
53369 }
53370 }
53371 else if (prev & meaning) {
53372 error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
53373 }
53374 else {
53375 names.set(name, prev | meaning);
53376 }
53377 }
53378 else {
53379 names.set(name, meaning);
53380 }
53381 }
53382 }
53383 /**
53384 * Static members being set on a constructor function may conflict with built-in properties
53385 * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
53386 * built-in properties. This check issues a transpile error when a class has a static
53387 * member with the same name as a non-writable built-in property.
53388 *
53389 * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
53390 * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
53391 * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
53392 * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
53393 */
53394 function checkClassForStaticPropertyNameConflicts(node) {
53395 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
53396 var member = _a[_i];
53397 var memberNameNode = member.name;
53398 var isStatic = ts.hasModifier(member, 32 /* Static */);
53399 if (isStatic && memberNameNode) {
53400 var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
53401 switch (memberName) {
53402 case "name":
53403 case "length":
53404 case "caller":
53405 case "arguments":
53406 case "prototype":
53407 var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
53408 var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
53409 error(memberNameNode, message, memberName, className);
53410 break;
53411 }
53412 }
53413 }
53414 }
53415 function checkObjectTypeForDuplicateDeclarations(node) {
53416 var names = ts.createMap();
53417 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
53418 var member = _a[_i];
53419 if (member.kind === 153 /* PropertySignature */) {
53420 var memberName = void 0;
53421 var name = member.name;
53422 switch (name.kind) {
53423 case 10 /* StringLiteral */:
53424 case 8 /* NumericLiteral */:
53425 memberName = name.text;
53426 break;
53427 case 72 /* Identifier */:
53428 memberName = ts.idText(name);
53429 break;
53430 default:
53431 continue;
53432 }
53433 if (names.get(memberName)) {
53434 error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
53435 error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
53436 }
53437 else {
53438 names.set(memberName, true);
53439 }
53440 }
53441 }
53442 }
53443 function checkTypeForDuplicateIndexSignatures(node) {
53444 if (node.kind === 241 /* InterfaceDeclaration */) {
53445 var nodeSymbol = getSymbolOfNode(node);
53446 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
53447 // to prevent this run check only for the first declaration of a given kind
53448 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
53449 return;
53450 }
53451 }
53452 // TypeScript 1.0 spec (April 2014)
53453 // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
53454 // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
53455 var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
53456 if (indexSymbol) {
53457 var seenNumericIndexer = false;
53458 var seenStringIndexer = false;
53459 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
53460 var decl = _a[_i];
53461 var declaration = decl;
53462 if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
53463 switch (declaration.parameters[0].type.kind) {
53464 case 138 /* StringKeyword */:
53465 if (!seenStringIndexer) {
53466 seenStringIndexer = true;
53467 }
53468 else {
53469 error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
53470 }
53471 break;
53472 case 135 /* NumberKeyword */:
53473 if (!seenNumericIndexer) {
53474 seenNumericIndexer = true;
53475 }
53476 else {
53477 error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
53478 }
53479 break;
53480 }
53481 }
53482 }
53483 }
53484 }
53485 function checkPropertyDeclaration(node) {
53486 // Grammar checking
53487 if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
53488 checkGrammarComputedPropertyName(node.name);
53489 checkVariableLikeDeclaration(node);
53490 }
53491 function checkMethodDeclaration(node) {
53492 // Grammar checking
53493 if (!checkGrammarMethod(node))
53494 checkGrammarComputedPropertyName(node.name);
53495 // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
53496 checkFunctionOrMethodDeclaration(node);
53497 // Abstract methods cannot have an implementation.
53498 // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
53499 if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 156 /* MethodDeclaration */ && node.body) {
53500 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
53501 }
53502 }
53503 function checkConstructorDeclaration(node) {
53504 // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
53505 checkSignatureDeclaration(node);
53506 // Grammar check for checking only related to constructorDeclaration
53507 if (!checkGrammarConstructorTypeParameters(node))
53508 checkGrammarConstructorTypeAnnotation(node);
53509 checkSourceElement(node.body);
53510 var symbol = getSymbolOfNode(node);
53511 var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
53512 // Only type check the symbol once
53513 if (node === firstDeclaration) {
53514 checkFunctionOrConstructorSymbol(symbol);
53515 }
53516 // exit early in the case of signature - super checks are not relevant to them
53517 if (ts.nodeIsMissing(node.body)) {
53518 return;
53519 }
53520 if (!produceDiagnostics) {
53521 return;
53522 }
53523 function isInstancePropertyWithInitializer(n) {
53524 return n.kind === 154 /* PropertyDeclaration */ &&
53525 !ts.hasModifier(n, 32 /* Static */) &&
53526 !!n.initializer;
53527 }
53528 // TS 1.0 spec (April 2014): 8.3.2
53529 // Constructors of classes with no extends clause may not contain super calls, whereas
53530 // constructors of derived classes must contain at least one super call somewhere in their function body.
53531 var containingClassDecl = node.parent;
53532 if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
53533 captureLexicalThis(node.parent, containingClassDecl);
53534 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
53535 var superCall = getSuperCallInConstructor(node);
53536 if (superCall) {
53537 if (classExtendsNull) {
53538 error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
53539 }
53540 // The first statement in the body of a constructor (excluding prologue directives) must be a super call
53541 // if both of the following are true:
53542 // - The containing class is a derived class.
53543 // - The constructor declares parameter properties
53544 // or the containing class declares instance member variables with initializers.
53545 var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) ||
53546 ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); });
53547 // Skip past any prologue directives to find the first statement
53548 // to ensure that it was a super call.
53549 if (superCallShouldBeFirst) {
53550 var statements = node.body.statements;
53551 var superCallStatement = void 0;
53552 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
53553 var statement = statements_2[_i];
53554 if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
53555 superCallStatement = statement;
53556 break;
53557 }
53558 if (!ts.isPrologueDirective(statement)) {
53559 break;
53560 }
53561 }
53562 if (!superCallStatement) {
53563 error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties);
53564 }
53565 }
53566 }
53567 else if (!classExtendsNull) {
53568 error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
53569 }
53570 }
53571 }
53572 function checkAccessorDeclaration(node) {
53573 if (produceDiagnostics) {
53574 // Grammar checking accessors
53575 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
53576 checkGrammarComputedPropertyName(node.name);
53577 checkDecorators(node);
53578 checkSignatureDeclaration(node);
53579 if (node.kind === 158 /* GetAccessor */) {
53580 if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) {
53581 if (!(node.flags & 256 /* HasExplicitReturn */)) {
53582 error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
53583 }
53584 }
53585 }
53586 // Do not use hasDynamicName here, because that returns false for well known symbols.
53587 // We want to perform checkComputedPropertyName for all computed properties, including
53588 // well known symbols.
53589 if (node.name.kind === 149 /* ComputedPropertyName */) {
53590 checkComputedPropertyName(node.name);
53591 }
53592 if (!hasNonBindableDynamicName(node)) {
53593 // TypeScript 1.0 spec (April 2014): 8.4.3
53594 // Accessors for the same member name must specify the same accessibility.
53595 var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */;
53596 var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
53597 if (otherAccessor) {
53598 var nodeFlags = ts.getModifierFlags(node);
53599 var otherFlags = ts.getModifierFlags(otherAccessor);
53600 if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
53601 error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
53602 }
53603 if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
53604 error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
53605 }
53606 // TypeScript 1.0 spec (April 2014): 4.5
53607 // If both accessors include type annotations, the specified types must be identical.
53608 checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
53609 checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
53610 }
53611 }
53612 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
53613 if (node.kind === 158 /* GetAccessor */) {
53614 checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
53615 }
53616 }
53617 checkSourceElement(node.body);
53618 }
53619 function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
53620 var firstType = getAnnotatedType(first);
53621 var secondType = getAnnotatedType(second);
53622 if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
53623 error(first, message);
53624 }
53625 }
53626 function checkMissingDeclaration(node) {
53627 checkDecorators(node);
53628 }
53629 function getEffectiveTypeArguments(node, typeParameters) {
53630 return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
53631 }
53632 function checkTypeArgumentConstraints(node, typeParameters) {
53633 var typeArguments;
53634 var mapper;
53635 var result = true;
53636 for (var i = 0; i < typeParameters.length; i++) {
53637 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
53638 if (constraint) {
53639 if (!typeArguments) {
53640 typeArguments = getEffectiveTypeArguments(node, typeParameters);
53641 mapper = createTypeMapper(typeParameters, typeArguments);
53642 }
53643 result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
53644 }
53645 }
53646 return result;
53647 }
53648 function getTypeParametersForTypeReference(node) {
53649 var type = getTypeFromTypeReference(node);
53650 if (type !== errorType) {
53651 var symbol = getNodeLinks(node).resolvedSymbol;
53652 if (symbol) {
53653 return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
53654 (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
53655 }
53656 }
53657 return undefined;
53658 }
53659 function checkTypeReferenceNode(node) {
53660 checkGrammarTypeArguments(node, node.typeArguments);
53661 if (node.kind === 164 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
53662 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
53663 }
53664 var type = getTypeFromTypeReference(node);
53665 if (type !== errorType) {
53666 if (node.typeArguments) {
53667 // Do type argument local checks only if referenced type is successfully resolved
53668 ts.forEach(node.typeArguments, checkSourceElement);
53669 if (produceDiagnostics) {
53670 var typeParameters = getTypeParametersForTypeReference(node);
53671 if (typeParameters) {
53672 checkTypeArgumentConstraints(node, typeParameters);
53673 }
53674 }
53675 }
53676 if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) {
53677 error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
53678 }
53679 }
53680 }
53681 function getTypeArgumentConstraint(node) {
53682 var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
53683 if (!typeReferenceNode)
53684 return undefined;
53685 var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
53686 var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
53687 return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
53688 }
53689 function checkTypeQuery(node) {
53690 getTypeFromTypeQueryNode(node);
53691 }
53692 function checkTypeLiteral(node) {
53693 ts.forEach(node.members, checkSourceElement);
53694 if (produceDiagnostics) {
53695 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
53696 checkIndexConstraints(type);
53697 checkTypeForDuplicateIndexSignatures(node);
53698 checkObjectTypeForDuplicateDeclarations(node);
53699 }
53700 }
53701 function checkArrayType(node) {
53702 checkSourceElement(node.elementType);
53703 }
53704 function checkTupleType(node) {
53705 var elementTypes = node.elementTypes;
53706 var seenOptionalElement = false;
53707 for (var i = 0; i < elementTypes.length; i++) {
53708 var e = elementTypes[i];
53709 if (e.kind === 172 /* RestType */) {
53710 if (i !== elementTypes.length - 1) {
53711 grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
53712 break;
53713 }
53714 if (!isArrayType(getTypeFromTypeNode(e))) {
53715 error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
53716 }
53717 }
53718 else if (e.kind === 171 /* OptionalType */) {
53719 seenOptionalElement = true;
53720 }
53721 else if (seenOptionalElement) {
53722 grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
53723 break;
53724 }
53725 }
53726 ts.forEach(node.elementTypes, checkSourceElement);
53727 }
53728 function checkUnionOrIntersectionType(node) {
53729 ts.forEach(node.types, checkSourceElement);
53730 }
53731 function checkIndexedAccessIndexType(type, accessNode) {
53732 if (!(type.flags & 8388608 /* IndexedAccess */)) {
53733 return type;
53734 }
53735 // Check if the index type is assignable to 'keyof T' for the object type.
53736 var objectType = type.objectType;
53737 var indexType = type.indexType;
53738 if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
53739 if (accessNode.kind === 190 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
53740 ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
53741 error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
53742 }
53743 return type;
53744 }
53745 // Check if we're indexing with a numeric type and if either object or index types
53746 // is a generic type with a constraint that has a numeric index signature.
53747 if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
53748 return type;
53749 }
53750 error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
53751 return type;
53752 }
53753 function checkIndexedAccessType(node) {
53754 checkSourceElement(node.objectType);
53755 checkSourceElement(node.indexType);
53756 checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
53757 }
53758 function checkMappedType(node) {
53759 checkSourceElement(node.typeParameter);
53760 checkSourceElement(node.type);
53761 if (!node.type) {
53762 reportImplicitAny(node, anyType);
53763 }
53764 var type = getTypeFromMappedTypeNode(node);
53765 var constraintType = getConstraintTypeFromMappedType(type);
53766 checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
53767 }
53768 function checkThisType(node) {
53769 getTypeFromThisTypeNode(node);
53770 }
53771 function checkTypeOperator(node) {
53772 checkGrammarTypeOperatorNode(node);
53773 checkSourceElement(node.type);
53774 }
53775 function checkConditionalType(node) {
53776 ts.forEachChild(node, checkSourceElement);
53777 }
53778 function checkInferType(node) {
53779 if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 175 /* ConditionalType */ && n.parent.extendsType === n; })) {
53780 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
53781 }
53782 checkSourceElement(node.typeParameter);
53783 registerForUnusedIdentifiersCheck(node);
53784 }
53785 function checkImportType(node) {
53786 checkSourceElement(node.argument);
53787 getTypeFromTypeNode(node);
53788 }
53789 function isPrivateWithinAmbient(node) {
53790 return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 4194304 /* Ambient */);
53791 }
53792 function getEffectiveDeclarationFlags(n, flagsToCheck) {
53793 var flags = ts.getCombinedModifierFlags(n);
53794 // children of classes (even ambient classes) should not be marked as ambient or export
53795 // because those flags have no useful semantics there.
53796 if (n.parent.kind !== 241 /* InterfaceDeclaration */ &&
53797 n.parent.kind !== 240 /* ClassDeclaration */ &&
53798 n.parent.kind !== 209 /* ClassExpression */ &&
53799 n.flags & 4194304 /* Ambient */) {
53800 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
53801 // It is nested in an ambient context, which means it is automatically exported
53802 flags |= 1 /* Export */;
53803 }
53804 flags |= 2 /* Ambient */;
53805 }
53806 return flags & flagsToCheck;
53807 }
53808 function checkFunctionOrConstructorSymbol(symbol) {
53809 if (!produceDiagnostics) {
53810 return;
53811 }
53812 function getCanonicalOverload(overloads, implementation) {
53813 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
53814 // Error on all deviations from this canonical set of flags
53815 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
53816 // report the errors on those. To achieve this, we will say that the implementation is
53817 // the canonical signature only if it is in the same container as the first overload
53818 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
53819 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
53820 }
53821 function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
53822 // Error if some overloads have a flag that is not shared by all overloads. To find the
53823 // deviations, we XOR someOverloadFlags with allOverloadFlags
53824 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
53825 if (someButNotAllOverloadFlags !== 0) {
53826 var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
53827 ts.forEach(overloads, function (o) {
53828 var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
53829 if (deviation & 1 /* Export */) {
53830 error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
53831 }
53832 else if (deviation & 2 /* Ambient */) {
53833 error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
53834 }
53835 else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
53836 error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
53837 }
53838 else if (deviation & 128 /* Abstract */) {
53839 error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
53840 }
53841 });
53842 }
53843 }
53844 function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
53845 if (someHaveQuestionToken !== allHaveQuestionToken) {
53846 var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
53847 ts.forEach(overloads, function (o) {
53848 var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
53849 if (deviation) {
53850 error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
53851 }
53852 });
53853 }
53854 }
53855 var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
53856 var someNodeFlags = 0 /* None */;
53857 var allNodeFlags = flagsToCheck;
53858 var someHaveQuestionToken = false;
53859 var allHaveQuestionToken = true;
53860 var hasOverloads = false;
53861 var bodyDeclaration;
53862 var lastSeenNonAmbientDeclaration;
53863 var previousDeclaration;
53864 var declarations = symbol.declarations;
53865 var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
53866 function reportImplementationExpectedError(node) {
53867 if (node.name && ts.nodeIsMissing(node.name)) {
53868 return;
53869 }
53870 var seen = false;
53871 var subsequentNode = ts.forEachChild(node.parent, function (c) {
53872 if (seen) {
53873 return c;
53874 }
53875 else {
53876 seen = c === node;
53877 }
53878 });
53879 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
53880 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
53881 if (subsequentNode && subsequentNode.pos === node.end) {
53882 if (subsequentNode.kind === node.kind) {
53883 var errorNode_1 = subsequentNode.name || subsequentNode;
53884 // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
53885 var subsequentName = subsequentNode.name;
53886 if (node.name && subsequentName &&
53887 (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
53888 !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
53889 var reportError = (node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */) &&
53890 ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */);
53891 // we can get here in two cases
53892 // 1. mixed static and instance class members
53893 // 2. something with the same name was defined before the set of overloads that prevents them from merging
53894 // here we'll report error only for the first case since for second we should already report error in binder
53895 if (reportError) {
53896 var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
53897 error(errorNode_1, diagnostic);
53898 }
53899 return;
53900 }
53901 else if (ts.nodeIsPresent(subsequentNode.body)) {
53902 error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
53903 return;
53904 }
53905 }
53906 }
53907 var errorNode = node.name || node;
53908 if (isConstructor) {
53909 error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
53910 }
53911 else {
53912 // Report different errors regarding non-consecutive blocks of declarations depending on whether
53913 // the node in question is abstract.
53914 if (ts.hasModifier(node, 128 /* Abstract */)) {
53915 error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
53916 }
53917 else {
53918 error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
53919 }
53920 }
53921 }
53922 var duplicateFunctionDeclaration = false;
53923 var multipleConstructorImplementation = false;
53924 for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
53925 var current = declarations_4[_i];
53926 var node = current;
53927 var inAmbientContext = node.flags & 4194304 /* Ambient */;
53928 var inAmbientContextOrInterface = node.parent.kind === 241 /* InterfaceDeclaration */ || node.parent.kind === 168 /* TypeLiteral */ || inAmbientContext;
53929 if (inAmbientContextOrInterface) {
53930 // check if declarations are consecutive only if they are non-ambient
53931 // 1. ambient declarations can be interleaved
53932 // i.e. this is legal
53933 // declare function foo();
53934 // declare function bar();
53935 // declare function foo();
53936 // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
53937 previousDeclaration = undefined;
53938 }
53939 if (node.kind === 239 /* FunctionDeclaration */ || node.kind === 156 /* MethodDeclaration */ || node.kind === 155 /* MethodSignature */ || node.kind === 157 /* Constructor */) {
53940 var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
53941 someNodeFlags |= currentNodeFlags;
53942 allNodeFlags &= currentNodeFlags;
53943 someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
53944 allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
53945 if (ts.nodeIsPresent(node.body) && bodyDeclaration) {
53946 if (isConstructor) {
53947 multipleConstructorImplementation = true;
53948 }
53949 else {
53950 duplicateFunctionDeclaration = true;
53951 }
53952 }
53953 else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) {
53954 reportImplementationExpectedError(previousDeclaration);
53955 }
53956 if (ts.nodeIsPresent(node.body)) {
53957 if (!bodyDeclaration) {
53958 bodyDeclaration = node;
53959 }
53960 }
53961 else {
53962 hasOverloads = true;
53963 }
53964 previousDeclaration = node;
53965 if (!inAmbientContextOrInterface) {
53966 lastSeenNonAmbientDeclaration = node;
53967 }
53968 }
53969 }
53970 if (multipleConstructorImplementation) {
53971 ts.forEach(declarations, function (declaration) {
53972 error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
53973 });
53974 }
53975 if (duplicateFunctionDeclaration) {
53976 ts.forEach(declarations, function (declaration) {
53977 error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation);
53978 });
53979 }
53980 // Abstract methods can't have an implementation -- in particular, they don't need one.
53981 if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
53982 !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
53983 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
53984 }
53985 if (hasOverloads) {
53986 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
53987 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
53988 if (bodyDeclaration) {
53989 var signatures = getSignaturesOfSymbol(symbol);
53990 var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
53991 for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) {
53992 var signature = signatures_6[_a];
53993 if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
53994 ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
53995 break;
53996 }
53997 }
53998 }
53999 }
54000 }
54001 var DeclarationSpaces;
54002 (function (DeclarationSpaces) {
54003 DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
54004 DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
54005 DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
54006 DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
54007 })(DeclarationSpaces || (DeclarationSpaces = {}));
54008 function checkExportsOnMergedDeclarations(node) {
54009 if (!produceDiagnostics) {
54010 return;
54011 }
54012 // if localSymbol is defined on node then node itself is exported - check is required
54013 var symbol = node.localSymbol;
54014 if (!symbol) {
54015 // local symbol is undefined => this declaration is non-exported.
54016 // however symbol might contain other declarations that are exported
54017 symbol = getSymbolOfNode(node);
54018 if (!symbol.exportSymbol) {
54019 // this is a pure local symbol (all declarations are non-exported) - no need to check anything
54020 return;
54021 }
54022 }
54023 // run the check only for the first declaration in the list
54024 if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
54025 return;
54026 }
54027 var exportedDeclarationSpaces = 0 /* None */;
54028 var nonExportedDeclarationSpaces = 0 /* None */;
54029 var defaultExportedDeclarationSpaces = 0 /* None */;
54030 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
54031 var d = _a[_i];
54032 var declarationSpaces = getDeclarationSpaces(d);
54033 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
54034 if (effectiveDeclarationFlags & 1 /* Export */) {
54035 if (effectiveDeclarationFlags & 512 /* Default */) {
54036 defaultExportedDeclarationSpaces |= declarationSpaces;
54037 }
54038 else {
54039 exportedDeclarationSpaces |= declarationSpaces;
54040 }
54041 }
54042 else {
54043 nonExportedDeclarationSpaces |= declarationSpaces;
54044 }
54045 }
54046 // Spaces for anything not declared a 'default export'.
54047 var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
54048 var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
54049 var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
54050 if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
54051 // declaration spaces for exported and non-exported declarations intersect
54052 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
54053 var d = _c[_b];
54054 var declarationSpaces = getDeclarationSpaces(d);
54055 var name = ts.getNameOfDeclaration(d);
54056 // Only error on the declarations that contributed to the intersecting spaces.
54057 if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
54058 error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name));
54059 }
54060 else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
54061 error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
54062 }
54063 }
54064 }
54065 function getDeclarationSpaces(decl) {
54066 var d = decl;
54067 switch (d.kind) {
54068 case 241 /* InterfaceDeclaration */:
54069 case 242 /* TypeAliasDeclaration */:
54070 // A jsdoc typedef and callback are, by definition, type aliases
54071 case 309 /* JSDocTypedefTag */:
54072 case 302 /* JSDocCallbackTag */:
54073 return 2 /* ExportType */;
54074 case 244 /* ModuleDeclaration */:
54075 return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
54076 ? 4 /* ExportNamespace */ | 1 /* ExportValue */
54077 : 4 /* ExportNamespace */;
54078 case 240 /* ClassDeclaration */:
54079 case 243 /* EnumDeclaration */:
54080 return 2 /* ExportType */ | 1 /* ExportValue */;
54081 case 284 /* SourceFile */:
54082 return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
54083 case 254 /* ExportAssignment */:
54084 // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
54085 if (!ts.isEntityNameExpression(d.expression)) {
54086 return 1 /* ExportValue */;
54087 }
54088 d = d.expression;
54089 /* falls through */
54090 // The below options all declare an Alias, which is allowed to merge with other values within the importing module
54091 case 248 /* ImportEqualsDeclaration */:
54092 case 251 /* NamespaceImport */:
54093 case 250 /* ImportClause */:
54094 var result_5 = 0 /* None */;
54095 var target = resolveAlias(getSymbolOfNode(d));
54096 ts.forEach(target.declarations, function (d) { result_5 |= getDeclarationSpaces(d); });
54097 return result_5;
54098 case 237 /* VariableDeclaration */:
54099 case 186 /* BindingElement */:
54100 case 239 /* FunctionDeclaration */:
54101 case 253 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
54102 return 1 /* ExportValue */;
54103 default:
54104 return ts.Debug.fail(ts.Debug.showSyntaxKind(d));
54105 }
54106 }
54107 }
54108 function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) {
54109 var promisedType = getPromisedTypeOfPromise(type, errorNode);
54110 return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage);
54111 }
54112 /**
54113 * Gets the "promised type" of a promise.
54114 * @param type The type of the promise.
54115 * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
54116 */
54117 function getPromisedTypeOfPromise(promise, errorNode) {
54118 //
54119 // { // promise
54120 // then( // thenFunction
54121 // onfulfilled: ( // onfulfilledParameterType
54122 // value: T // valueParameterType
54123 // ) => any
54124 // ): any;
54125 // }
54126 //
54127 if (isTypeAny(promise)) {
54128 return undefined;
54129 }
54130 var typeAsPromise = promise;
54131 if (typeAsPromise.promisedTypeOfPromise) {
54132 return typeAsPromise.promisedTypeOfPromise;
54133 }
54134 if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) {
54135 return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0];
54136 }
54137 var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217
54138 if (isTypeAny(thenFunction)) {
54139 return undefined;
54140 }
54141 var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
54142 if (thenSignatures.length === 0) {
54143 if (errorNode) {
54144 error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
54145 }
54146 return undefined;
54147 }
54148 var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
54149 if (isTypeAny(onfulfilledParameterType)) {
54150 return undefined;
54151 }
54152 var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
54153 if (onfulfilledParameterSignatures.length === 0) {
54154 if (errorNode) {
54155 error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
54156 }
54157 return undefined;
54158 }
54159 return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
54160 }
54161 /**
54162 * Gets the "awaited type" of a type.
54163 * @param type The type to await.
54164 * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
54165 * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
54166 * The runtime behavior of the `await` keyword.
54167 */
54168 function checkAwaitedType(type, errorNode, diagnosticMessage) {
54169 return getAwaitedType(type, errorNode, diagnosticMessage) || errorType;
54170 }
54171 function getAwaitedType(type, errorNode, diagnosticMessage) {
54172 var typeAsAwaitable = type;
54173 if (typeAsAwaitable.awaitedTypeOfType) {
54174 return typeAsAwaitable.awaitedTypeOfType;
54175 }
54176 if (isTypeAny(type)) {
54177 return typeAsAwaitable.awaitedTypeOfType = type;
54178 }
54179 if (type.flags & 1048576 /* Union */) {
54180 var types = void 0;
54181 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
54182 var constituentType = _a[_i];
54183 types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage));
54184 }
54185 if (!types) {
54186 return undefined;
54187 }
54188 return typeAsAwaitable.awaitedTypeOfType = getUnionType(types);
54189 }
54190 var promisedType = getPromisedTypeOfPromise(type);
54191 if (promisedType) {
54192 if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) {
54193 // Verify that we don't have a bad actor in the form of a promise whose
54194 // promised type is the same as the promise type, or a mutually recursive
54195 // promise. If so, we return undefined as we cannot guess the shape. If this
54196 // were the actual case in the JavaScript, this Promise would never resolve.
54197 //
54198 // An example of a bad actor with a singly-recursive promise type might
54199 // be:
54200 //
54201 // interface BadPromise {
54202 // then(
54203 // onfulfilled: (value: BadPromise) => any,
54204 // onrejected: (error: any) => any): BadPromise;
54205 // }
54206 // The above interface will pass the PromiseLike check, and return a
54207 // promised type of `BadPromise`. Since this is a self reference, we
54208 // don't want to keep recursing ad infinitum.
54209 //
54210 // An example of a bad actor in the form of a mutually-recursive
54211 // promise type might be:
54212 //
54213 // interface BadPromiseA {
54214 // then(
54215 // onfulfilled: (value: BadPromiseB) => any,
54216 // onrejected: (error: any) => any): BadPromiseB;
54217 // }
54218 //
54219 // interface BadPromiseB {
54220 // then(
54221 // onfulfilled: (value: BadPromiseA) => any,
54222 // onrejected: (error: any) => any): BadPromiseA;
54223 // }
54224 //
54225 if (errorNode) {
54226 error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
54227 }
54228 return undefined;
54229 }
54230 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
54231 // See the comments above for more information.
54232 awaitedTypeStack.push(type.id);
54233 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage);
54234 awaitedTypeStack.pop();
54235 if (!awaitedType) {
54236 return undefined;
54237 }
54238 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
54239 }
54240 // The type was not a promise, so it could not be unwrapped any further.
54241 // As long as the type does not have a callable "then" property, it is
54242 // safe to return the type; otherwise, an error will be reported in
54243 // the call to getNonThenableType and we will return undefined.
54244 //
54245 // An example of a non-promise "thenable" might be:
54246 //
54247 // await { then(): void {} }
54248 //
54249 // The "thenable" does not match the minimal definition for a promise. When
54250 // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
54251 // will never settle. We treat this as an error to help flag an early indicator
54252 // of a runtime problem. If the user wants to return this value from an async
54253 // function, they would need to wrap it in some other value. If they want it to
54254 // be treated as a promise, they can cast to <any>.
54255 var thenFunction = getTypeOfPropertyOfType(type, "then");
54256 if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) {
54257 if (errorNode) {
54258 if (!diagnosticMessage)
54259 return ts.Debug.fail();
54260 error(errorNode, diagnosticMessage);
54261 }
54262 return undefined;
54263 }
54264 return typeAsAwaitable.awaitedTypeOfType = type;
54265 }
54266 /**
54267 * Checks the return type of an async function to ensure it is a compatible
54268 * Promise implementation.
54269 *
54270 * This checks that an async function has a valid Promise-compatible return type.
54271 * An async function has a valid Promise-compatible return type if the resolved value
54272 * of the return type has a construct signature that takes in an `initializer` function
54273 * that in turn supplies a `resolve` function as one of its arguments and results in an
54274 * object with a callable `then` signature.
54275 *
54276 * @param node The signature to check
54277 */
54278 function checkAsyncFunctionReturnType(node, returnTypeNode) {
54279 // As part of our emit for an async function, we will need to emit the entity name of
54280 // the return type annotation as an expression. To meet the necessary runtime semantics
54281 // for __awaiter, we must also check that the type of the declaration (e.g. the static
54282 // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
54283 //
54284 // An example might be (from lib.es6.d.ts):
54285 //
54286 // interface Promise<T> { ... }
54287 // interface PromiseConstructor {
54288 // new <T>(...): Promise<T>;
54289 // }
54290 // declare var Promise: PromiseConstructor;
54291 //
54292 // When an async function declares a return type annotation of `Promise<T>`, we
54293 // need to get the type of the `Promise` variable declaration above, which would
54294 // be `PromiseConstructor`.
54295 //
54296 // The same case applies to a class:
54297 //
54298 // declare class Promise<T> {
54299 // constructor(...);
54300 // then<U>(...): Promise<U>;
54301 // }
54302 //
54303 var returnType = getTypeFromTypeNode(returnTypeNode);
54304 if (languageVersion >= 2 /* ES2015 */) {
54305 if (returnType === errorType) {
54306 return;
54307 }
54308 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
54309 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
54310 // The promise type was not a valid type reference to the global promise type, so we
54311 // report an error and return the unknown type.
54312 error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
54313 return;
54314 }
54315 }
54316 else {
54317 // Always mark the type node as referenced if it points to a value
54318 markTypeNodeAsReferenced(returnTypeNode);
54319 if (returnType === errorType) {
54320 return;
54321 }
54322 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
54323 if (promiseConstructorName === undefined) {
54324 error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType));
54325 return;
54326 }
54327 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true);
54328 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
54329 if (promiseConstructorType === errorType) {
54330 if (promiseConstructorName.kind === 72 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
54331 error(returnTypeNode, ts.Diagnostics.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);
54332 }
54333 else {
54334 error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName));
54335 }
54336 return;
54337 }
54338 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
54339 if (globalPromiseConstructorLikeType === emptyObjectType) {
54340 // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
54341 // compatibility with __awaiter.
54342 error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName));
54343 return;
54344 }
54345 if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) {
54346 return;
54347 }
54348 // Verify there is no local declaration that could collide with the promise constructor.
54349 var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName);
54350 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */);
54351 if (collidingSymbol) {
54352 error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
54353 return;
54354 }
54355 }
54356 checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
54357 }
54358 /** Check a decorator */
54359 function checkDecorator(node) {
54360 var signature = getResolvedSignature(node);
54361 var returnType = getReturnTypeOfSignature(signature);
54362 if (returnType.flags & 1 /* Any */) {
54363 return;
54364 }
54365 var expectedReturnType;
54366 var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
54367 var errorInfo;
54368 switch (node.parent.kind) {
54369 case 240 /* ClassDeclaration */:
54370 var classSymbol = getSymbolOfNode(node.parent);
54371 var classConstructorType = getTypeOfSymbol(classSymbol);
54372 expectedReturnType = getUnionType([classConstructorType, voidType]);
54373 break;
54374 case 151 /* Parameter */:
54375 expectedReturnType = voidType;
54376 errorInfo = ts.chainDiagnosticMessages(
54377 /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
54378 break;
54379 case 154 /* PropertyDeclaration */:
54380 expectedReturnType = voidType;
54381 errorInfo = ts.chainDiagnosticMessages(
54382 /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
54383 break;
54384 case 156 /* MethodDeclaration */:
54385 case 158 /* GetAccessor */:
54386 case 159 /* SetAccessor */:
54387 var methodType = getTypeOfNode(node.parent);
54388 var descriptorType = createTypedPropertyDescriptorType(methodType);
54389 expectedReturnType = getUnionType([descriptorType, voidType]);
54390 break;
54391 default:
54392 return ts.Debug.fail();
54393 }
54394 checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
54395 }
54396 /**
54397 * If a TypeNode can be resolved to a value symbol imported from an external module, it is
54398 * marked as referenced to prevent import elision.
54399 */
54400 function markTypeNodeAsReferenced(node) {
54401 markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
54402 }
54403 function markEntityNameOrEntityExpressionAsReference(typeName) {
54404 if (!typeName)
54405 return;
54406 var rootName = getFirstIdentifier(typeName);
54407 var meaning = (typeName.kind === 72 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
54408 var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
54409 if (rootSymbol
54410 && rootSymbol.flags & 2097152 /* Alias */
54411 && symbolIsValue(rootSymbol)
54412 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) {
54413 markAliasSymbolAsReferenced(rootSymbol);
54414 }
54415 }
54416 /**
54417 * This function marks the type used for metadata decorator as referenced if it is import
54418 * from external module.
54419 * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
54420 * union and intersection type
54421 * @param node
54422 */
54423 function markDecoratorMedataDataTypeNodeAsReferenced(node) {
54424 var entityName = getEntityNameForDecoratorMetadata(node);
54425 if (entityName && ts.isEntityName(entityName)) {
54426 markEntityNameOrEntityExpressionAsReference(entityName);
54427 }
54428 }
54429 function getEntityNameForDecoratorMetadata(node) {
54430 if (node) {
54431 switch (node.kind) {
54432 case 174 /* IntersectionType */:
54433 case 173 /* UnionType */:
54434 return getEntityNameForDecoratorMetadataFromTypeList(node.types);
54435 case 175 /* ConditionalType */:
54436 return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
54437 case 177 /* ParenthesizedType */:
54438 return getEntityNameForDecoratorMetadata(node.type);
54439 case 164 /* TypeReference */:
54440 return node.typeName;
54441 }
54442 }
54443 }
54444 function getEntityNameForDecoratorMetadataFromTypeList(types) {
54445 var commonEntityName;
54446 for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
54447 var typeNode = types_17[_i];
54448 while (typeNode.kind === 177 /* ParenthesizedType */) {
54449 typeNode = typeNode.type; // Skip parens if need be
54450 }
54451 if (typeNode.kind === 132 /* NeverKeyword */) {
54452 continue; // Always elide `never` from the union/intersection if possible
54453 }
54454 if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) {
54455 continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
54456 }
54457 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
54458 if (!individualEntityName) {
54459 // Individual is something like string number
54460 // So it would be serialized to either that type or object
54461 // Safe to return here
54462 return undefined;
54463 }
54464 if (commonEntityName) {
54465 // Note this is in sync with the transformation that happens for type node.
54466 // Keep this in sync with serializeUnionOrIntersectionType
54467 // Verify if they refer to same entity and is identifier
54468 // return undefined if they dont match because we would emit object
54469 if (!ts.isIdentifier(commonEntityName) ||
54470 !ts.isIdentifier(individualEntityName) ||
54471 commonEntityName.escapedText !== individualEntityName.escapedText) {
54472 return undefined;
54473 }
54474 }
54475 else {
54476 commonEntityName = individualEntityName;
54477 }
54478 }
54479 return commonEntityName;
54480 }
54481 function getParameterTypeNodeForDecoratorCheck(node) {
54482 var typeNode = ts.getEffectiveTypeAnnotationNode(node);
54483 return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
54484 }
54485 /** Check the decorators of a node */
54486 function checkDecorators(node) {
54487 if (!node.decorators) {
54488 return;
54489 }
54490 // skip this check for nodes that cannot have decorators. These should have already had an error reported by
54491 // checkGrammarDecorators.
54492 if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
54493 return;
54494 }
54495 if (!compilerOptions.experimentalDecorators) {
54496 error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning);
54497 }
54498 var firstDecorator = node.decorators[0];
54499 checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
54500 if (node.kind === 151 /* Parameter */) {
54501 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
54502 }
54503 if (compilerOptions.emitDecoratorMetadata) {
54504 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
54505 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
54506 switch (node.kind) {
54507 case 240 /* ClassDeclaration */:
54508 var constructor = ts.getFirstConstructorWithBody(node);
54509 if (constructor) {
54510 for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
54511 var parameter = _a[_i];
54512 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
54513 }
54514 }
54515 break;
54516 case 158 /* GetAccessor */:
54517 case 159 /* SetAccessor */:
54518 var otherKind = node.kind === 158 /* GetAccessor */ ? 159 /* SetAccessor */ : 158 /* GetAccessor */;
54519 var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
54520 markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
54521 break;
54522 case 156 /* MethodDeclaration */:
54523 for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
54524 var parameter = _c[_b];
54525 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
54526 }
54527 markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
54528 break;
54529 case 154 /* PropertyDeclaration */:
54530 markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
54531 break;
54532 case 151 /* Parameter */:
54533 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
54534 var containingSignature = node.parent;
54535 for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
54536 var parameter = _e[_d];
54537 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
54538 }
54539 break;
54540 }
54541 }
54542 ts.forEach(node.decorators, checkDecorator);
54543 }
54544 function checkFunctionDeclaration(node) {
54545 if (produceDiagnostics) {
54546 checkFunctionOrMethodDeclaration(node);
54547 checkGrammarForGenerator(node);
54548 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
54549 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
54550 }
54551 }
54552 function checkJSDocTypeAliasTag(node) {
54553 if (!node.typeExpression) {
54554 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
54555 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
54556 }
54557 if (node.name) {
54558 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
54559 }
54560 checkSourceElement(node.typeExpression);
54561 }
54562 function checkJSDocTemplateTag(node) {
54563 checkSourceElement(node.constraint);
54564 for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
54565 var tp = _a[_i];
54566 checkSourceElement(tp);
54567 }
54568 }
54569 function checkJSDocTypeTag(node) {
54570 checkSourceElement(node.typeExpression);
54571 }
54572 function checkJSDocParameterTag(node) {
54573 checkSourceElement(node.typeExpression);
54574 if (!ts.getParameterSymbolFromJSDoc(node)) {
54575 var decl = ts.getHostSignatureFromJSDoc(node);
54576 // don't issue an error for invalid hosts -- just functions --
54577 // and give a better error message when the host function mentions `arguments`
54578 // but the tag doesn't have an array type
54579 if (decl) {
54580 var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
54581 if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
54582 return;
54583 }
54584 if (!containsArgumentsReference(decl)) {
54585 if (ts.isQualifiedName(node.name)) {
54586 error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left));
54587 }
54588 else {
54589 error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
54590 }
54591 }
54592 else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
54593 node.typeExpression && node.typeExpression.type &&
54594 !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
54595 error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name));
54596 }
54597 }
54598 }
54599 }
54600 function checkJSDocFunctionType(node) {
54601 if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
54602 reportImplicitAny(node, anyType);
54603 }
54604 checkSignatureDeclaration(node);
54605 }
54606 function checkJSDocAugmentsTag(node) {
54607 var classLike = ts.getJSDocHost(node);
54608 if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
54609 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
54610 return;
54611 }
54612 var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
54613 ts.Debug.assert(augmentsTags.length > 0);
54614 if (augmentsTags.length > 1) {
54615 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
54616 }
54617 var name = getIdentifierFromEntityNameExpression(node.class.expression);
54618 var extend = ts.getClassExtendsHeritageElement(classLike);
54619 if (extend) {
54620 var className = getIdentifierFromEntityNameExpression(extend.expression);
54621 if (className && name.escapedText !== className.escapedText) {
54622 error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
54623 }
54624 }
54625 }
54626 function getIdentifierFromEntityNameExpression(node) {
54627 switch (node.kind) {
54628 case 72 /* Identifier */:
54629 return node;
54630 case 189 /* PropertyAccessExpression */:
54631 return node.name;
54632 default:
54633 return undefined;
54634 }
54635 }
54636 function checkFunctionOrMethodDeclaration(node) {
54637 checkDecorators(node);
54638 checkSignatureDeclaration(node);
54639 var functionFlags = ts.getFunctionFlags(node);
54640 // Do not use hasDynamicName here, because that returns false for well known symbols.
54641 // We want to perform checkComputedPropertyName for all computed properties, including
54642 // well known symbols.
54643 if (node.name && node.name.kind === 149 /* ComputedPropertyName */) {
54644 // This check will account for methods in class/interface declarations,
54645 // as well as accessors in classes/object literals
54646 checkComputedPropertyName(node.name);
54647 }
54648 if (!hasNonBindableDynamicName(node)) {
54649 // first we want to check the local symbol that contain this declaration
54650 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
54651 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
54652 var symbol = getSymbolOfNode(node);
54653 var localSymbol = node.localSymbol || symbol;
54654 // Since the javascript won't do semantic analysis like typescript,
54655 // if the javascript file comes before the typescript file and both contain same name functions,
54656 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
54657 var firstDeclaration = ts.find(localSymbol.declarations,
54658 // Get first non javascript function declaration
54659 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536 /* JavaScriptFile */); });
54660 // Only type check the symbol once
54661 if (node === firstDeclaration) {
54662 checkFunctionOrConstructorSymbol(localSymbol);
54663 }
54664 if (symbol.parent) {
54665 // run check once for the first declaration
54666 if (ts.getDeclarationOfKind(symbol, node.kind) === node) {
54667 // run check on export symbol to check that modifiers agree across all exported declarations
54668 checkFunctionOrConstructorSymbol(symbol);
54669 }
54670 }
54671 }
54672 var body = node.kind === 155 /* MethodSignature */ ? undefined : node.body;
54673 checkSourceElement(body);
54674 if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function
54675 var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags);
54676 checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
54677 }
54678 if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
54679 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
54680 // in an ambient context
54681 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
54682 reportImplicitAny(node, anyType);
54683 }
54684 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
54685 // A generator with a body and no type annotation can still cause errors. It can error if the
54686 // yielded values have no common supertype, or it can give an implicit any error if it has no
54687 // yielded values. The only way to trigger these errors is to try checking its return type.
54688 getReturnTypeOfSignature(getSignatureFromDeclaration(node));
54689 }
54690 }
54691 // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
54692 if (ts.isInJSFile(node)) {
54693 var typeTag = ts.getJSDocTypeTag(node);
54694 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
54695 error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
54696 }
54697 }
54698 }
54699 function registerForUnusedIdentifiersCheck(node) {
54700 // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
54701 if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) {
54702 var sourceFile = ts.getSourceFileOfNode(node);
54703 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
54704 if (!potentiallyUnusedIdentifiers) {
54705 potentiallyUnusedIdentifiers = [];
54706 allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
54707 }
54708 // TODO: GH#22580
54709 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
54710 potentiallyUnusedIdentifiers.push(node);
54711 }
54712 }
54713 function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
54714 for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
54715 var node = potentiallyUnusedIdentifiers_1[_i];
54716 switch (node.kind) {
54717 case 240 /* ClassDeclaration */:
54718 case 209 /* ClassExpression */:
54719 checkUnusedClassMembers(node, addDiagnostic);
54720 checkUnusedTypeParameters(node, addDiagnostic);
54721 break;
54722 case 284 /* SourceFile */:
54723 case 244 /* ModuleDeclaration */:
54724 case 218 /* Block */:
54725 case 246 /* CaseBlock */:
54726 case 225 /* ForStatement */:
54727 case 226 /* ForInStatement */:
54728 case 227 /* ForOfStatement */:
54729 checkUnusedLocalsAndParameters(node, addDiagnostic);
54730 break;
54731 case 157 /* Constructor */:
54732 case 196 /* FunctionExpression */:
54733 case 239 /* FunctionDeclaration */:
54734 case 197 /* ArrowFunction */:
54735 case 156 /* MethodDeclaration */:
54736 case 158 /* GetAccessor */:
54737 case 159 /* SetAccessor */:
54738 if (node.body) { // Don't report unused parameters in overloads
54739 checkUnusedLocalsAndParameters(node, addDiagnostic);
54740 }
54741 checkUnusedTypeParameters(node, addDiagnostic);
54742 break;
54743 case 155 /* MethodSignature */:
54744 case 160 /* CallSignature */:
54745 case 161 /* ConstructSignature */:
54746 case 165 /* FunctionType */:
54747 case 166 /* ConstructorType */:
54748 case 242 /* TypeAliasDeclaration */:
54749 case 241 /* InterfaceDeclaration */:
54750 checkUnusedTypeParameters(node, addDiagnostic);
54751 break;
54752 case 176 /* InferType */:
54753 checkUnusedInferTypeParameter(node, addDiagnostic);
54754 break;
54755 default:
54756 ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
54757 }
54758 }
54759 }
54760 function errorUnusedLocal(declaration, name, addDiagnostic) {
54761 var node = ts.getNameOfDeclaration(declaration) || declaration;
54762 var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
54763 addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
54764 }
54765 function isIdentifierThatStartsWithUnderscore(node) {
54766 return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
54767 }
54768 function checkUnusedClassMembers(node, addDiagnostic) {
54769 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
54770 var member = _a[_i];
54771 switch (member.kind) {
54772 case 156 /* MethodDeclaration */:
54773 case 154 /* PropertyDeclaration */:
54774 case 158 /* GetAccessor */:
54775 case 159 /* SetAccessor */:
54776 if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
54777 // Already would have reported an error on the getter.
54778 break;
54779 }
54780 var symbol = getSymbolOfNode(member);
54781 if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
54782 addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
54783 }
54784 break;
54785 case 157 /* Constructor */:
54786 for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
54787 var parameter = _c[_b];
54788 if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
54789 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
54790 }
54791 }
54792 break;
54793 case 162 /* IndexSignature */:
54794 case 217 /* SemicolonClassElement */:
54795 // Can't be private
54796 break;
54797 default:
54798 ts.Debug.fail();
54799 }
54800 }
54801 }
54802 function checkUnusedInferTypeParameter(node, addDiagnostic) {
54803 var typeParameter = node.typeParameter;
54804 if (isTypeParameterUnused(typeParameter)) {
54805 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
54806 }
54807 }
54808 function checkUnusedTypeParameters(node, addDiagnostic) {
54809 // Only report errors on the last declaration for the type parameter container;
54810 // this ensures that all uses have been accounted for.
54811 if (ts.last(getSymbolOfNode(node).declarations) !== node)
54812 return;
54813 var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
54814 var seenParentsWithEveryUnused = new ts.NodeSet();
54815 for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
54816 var typeParameter = typeParameters_3[_i];
54817 if (!isTypeParameterUnused(typeParameter))
54818 continue;
54819 var name = ts.idText(typeParameter.name);
54820 var parent = typeParameter.parent;
54821 if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
54822 if (seenParentsWithEveryUnused.tryAdd(parent)) {
54823 var range = ts.isJSDocTemplateTag(parent)
54824 // Whole @template tag
54825 ? ts.rangeOfNode(parent)
54826 // Include the `<>` in the error message
54827 : ts.rangeOfTypeParameters(parent.typeParameters);
54828 var only = typeParameters.length === 1;
54829 var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
54830 var arg0 = only ? name : undefined;
54831 addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
54832 }
54833 }
54834 else {
54835 addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
54836 }
54837 }
54838 }
54839 function isTypeParameterUnused(typeParameter) {
54840 return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
54841 }
54842 function addToGroup(map, key, value, getKey) {
54843 var keyString = String(getKey(key));
54844 var group = map.get(keyString);
54845 if (group) {
54846 group[1].push(value);
54847 }
54848 else {
54849 map.set(keyString, [key, [value]]);
54850 }
54851 }
54852 function tryGetRootParameterDeclaration(node) {
54853 return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
54854 }
54855 function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
54856 if (nodeWithLocals.flags & 4194304 /* Ambient */)
54857 return;
54858 // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
54859 var unusedImports = ts.createMap();
54860 var unusedDestructures = ts.createMap();
54861 var unusedVariables = ts.createMap();
54862 nodeWithLocals.locals.forEach(function (local) {
54863 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
54864 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
54865 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
54866 return;
54867 }
54868 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
54869 var declaration = _a[_i];
54870 if (ts.isAmbientModule(declaration) ||
54871 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
54872 continue;
54873 }
54874 if (isImportedDeclaration(declaration)) {
54875 addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
54876 }
54877 else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
54878 // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
54879 var lastElement = ts.last(declaration.parent.elements);
54880 if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
54881 addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
54882 }
54883 }
54884 else if (ts.isVariableDeclaration(declaration)) {
54885 addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
54886 }
54887 else {
54888 var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
54889 var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
54890 if (parameter && name) {
54891 if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
54892 addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
54893 }
54894 }
54895 else {
54896 errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
54897 }
54898 }
54899 }
54900 });
54901 unusedImports.forEach(function (_a) {
54902 var importClause = _a[0], unuseds = _a[1];
54903 var importDecl = importClause.parent;
54904 var nDeclarations = (importClause.name ? 1 : 0) +
54905 (importClause.namedBindings ?
54906 (importClause.namedBindings.kind === 251 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
54907 : 0);
54908 if (nDeclarations === unuseds.length) {
54909 addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
54910 ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
54911 : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
54912 }
54913 else {
54914 for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
54915 var unused = unuseds_1[_i];
54916 errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
54917 }
54918 }
54919 });
54920 unusedDestructures.forEach(function (_a) {
54921 var bindingPattern = _a[0], bindingElements = _a[1];
54922 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
54923 if (bindingPattern.elements.length === bindingElements.length) {
54924 if (bindingElements.length === 1 && bindingPattern.parent.kind === 237 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 238 /* VariableDeclarationList */) {
54925 addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
54926 }
54927 else {
54928 addDiagnostic(bindingPattern, kind, bindingElements.length === 1
54929 ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
54930 : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
54931 }
54932 }
54933 else {
54934 for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
54935 var e = bindingElements_1[_i];
54936 addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
54937 }
54938 }
54939 });
54940 unusedVariables.forEach(function (_a) {
54941 var declarationList = _a[0], declarations = _a[1];
54942 if (declarationList.declarations.length === declarations.length) {
54943 addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
54944 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
54945 : ts.createDiagnosticForNode(declarationList.parent.kind === 219 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
54946 }
54947 else {
54948 for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
54949 var decl = declarations_5[_i];
54950 addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
54951 }
54952 }
54953 });
54954 }
54955 function bindingNameText(name) {
54956 switch (name.kind) {
54957 case 72 /* Identifier */:
54958 return ts.idText(name);
54959 case 185 /* ArrayBindingPattern */:
54960 case 184 /* ObjectBindingPattern */:
54961 return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
54962 default:
54963 return ts.Debug.assertNever(name);
54964 }
54965 }
54966 function isImportedDeclaration(node) {
54967 return node.kind === 250 /* ImportClause */ || node.kind === 253 /* ImportSpecifier */ || node.kind === 251 /* NamespaceImport */;
54968 }
54969 function importClauseFromImported(decl) {
54970 return decl.kind === 250 /* ImportClause */ ? decl : decl.kind === 251 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
54971 }
54972 function checkBlock(node) {
54973 // Grammar checking for SyntaxKind.Block
54974 if (node.kind === 218 /* Block */) {
54975 checkGrammarStatementInAmbientContext(node);
54976 }
54977 if (ts.isFunctionOrModuleBlock(node)) {
54978 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
54979 ts.forEach(node.statements, checkSourceElement);
54980 flowAnalysisDisabled = saveFlowAnalysisDisabled;
54981 }
54982 else {
54983 ts.forEach(node.statements, checkSourceElement);
54984 }
54985 if (node.locals) {
54986 registerForUnusedIdentifiersCheck(node);
54987 }
54988 }
54989 function checkCollisionWithArgumentsInGeneratedCode(node) {
54990 // no rest parameters \ declaration context \ overload - no codegen impact
54991 if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 4194304 /* Ambient */ || ts.nodeIsMissing(node.body)) {
54992 return;
54993 }
54994 ts.forEach(node.parameters, function (p) {
54995 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
54996 error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
54997 }
54998 });
54999 }
55000 function needCollisionCheckForIdentifier(node, identifier, name) {
55001 if (!(identifier && identifier.escapedText === name)) {
55002 return false;
55003 }
55004 if (node.kind === 154 /* PropertyDeclaration */ ||
55005 node.kind === 153 /* PropertySignature */ ||
55006 node.kind === 156 /* MethodDeclaration */ ||
55007 node.kind === 155 /* MethodSignature */ ||
55008 node.kind === 158 /* GetAccessor */ ||
55009 node.kind === 159 /* SetAccessor */) {
55010 // it is ok to have member named '_super' or '_this' - member access is always qualified
55011 return false;
55012 }
55013 if (node.flags & 4194304 /* Ambient */) {
55014 // ambient context - no codegen impact
55015 return false;
55016 }
55017 var root = ts.getRootDeclaration(node);
55018 if (root.kind === 151 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
55019 // just an overload - no codegen impact
55020 return false;
55021 }
55022 return true;
55023 }
55024 // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
55025 function checkIfThisIsCapturedInEnclosingScope(node) {
55026 ts.findAncestor(node, function (current) {
55027 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
55028 var isDeclaration_1 = node.kind !== 72 /* Identifier */;
55029 if (isDeclaration_1) {
55030 error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
55031 }
55032 else {
55033 error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
55034 }
55035 return true;
55036 }
55037 return false;
55038 });
55039 }
55040 function checkIfNewTargetIsCapturedInEnclosingScope(node) {
55041 ts.findAncestor(node, function (current) {
55042 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
55043 var isDeclaration_2 = node.kind !== 72 /* Identifier */;
55044 if (isDeclaration_2) {
55045 error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
55046 }
55047 else {
55048 error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
55049 }
55050 return true;
55051 }
55052 return false;
55053 });
55054 }
55055 function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
55056 // No need to check for require or exports for ES6 modules and later
55057 if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) {
55058 return;
55059 }
55060 if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
55061 return;
55062 }
55063 // Uninstantiated modules shouldnt do this check
55064 if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
55065 return;
55066 }
55067 // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
55068 var parent = getDeclarationContainer(node);
55069 if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
55070 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
55071 error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
55072 }
55073 }
55074 function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
55075 if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) {
55076 return;
55077 }
55078 // Uninstantiated modules shouldnt do this check
55079 if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
55080 return;
55081 }
55082 // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
55083 var parent = getDeclarationContainer(node);
55084 if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
55085 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
55086 error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
55087 }
55088 }
55089 function checkVarDeclaredNamesNotShadowed(node) {
55090 // - ScriptBody : StatementList
55091 // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
55092 // also occurs in the VarDeclaredNames of StatementList.
55093 // - Block : { StatementList }
55094 // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
55095 // also occurs in the VarDeclaredNames of StatementList.
55096 // Variable declarations are hoisted to the top of their function scope. They can shadow
55097 // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
55098 // by the binder as the declaration scope is different.
55099 // A non-initialized declaration is a no-op as the block declaration will resolve before the var
55100 // declaration. the problem is if the declaration has an initializer. this will act as a write to the
55101 // block declared value. this is fine for let, but not const.
55102 // Only consider declarations with initializers, uninitialized const declarations will not
55103 // step on a let/const variable.
55104 // Do not consider const and const declarations, as duplicate block-scoped declarations
55105 // are handled by the binder.
55106 // We are only looking for const declarations that step on let\const declarations from a
55107 // different scope. e.g.:
55108 // {
55109 // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
55110 // const x = 0; // symbol for this declaration will be 'symbol'
55111 // }
55112 // skip block-scoped variables and parameters
55113 if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
55114 return;
55115 }
55116 // skip variable declarations that don't have initializers
55117 // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
55118 // so we'll always treat binding elements as initialized
55119 if (node.kind === 237 /* VariableDeclaration */ && !node.initializer) {
55120 return;
55121 }
55122 var symbol = getSymbolOfNode(node);
55123 if (symbol.flags & 1 /* FunctionScopedVariable */) {
55124 if (!ts.isIdentifier(node.name))
55125 return ts.Debug.fail();
55126 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
55127 if (localDeclarationSymbol &&
55128 localDeclarationSymbol !== symbol &&
55129 localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
55130 if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
55131 var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 238 /* VariableDeclarationList */);
55132 var container = varDeclList.parent.kind === 219 /* VariableStatement */ && varDeclList.parent.parent
55133 ? varDeclList.parent.parent
55134 : undefined;
55135 // names of block-scoped and function scoped variables can collide only
55136 // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
55137 var namesShareScope = container &&
55138 (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
55139 container.kind === 245 /* ModuleBlock */ ||
55140 container.kind === 244 /* ModuleDeclaration */ ||
55141 container.kind === 284 /* SourceFile */);
55142 // here we know that function scoped variable is shadowed by block scoped one
55143 // if they are defined in the same scope - binder has already reported redeclaration error
55144 // otherwise if variable has an initializer - show error that initialization will fail
55145 // since LHS will be block scoped name instead of function scoped
55146 if (!namesShareScope) {
55147 var name = symbolToString(localDeclarationSymbol);
55148 error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
55149 }
55150 }
55151 }
55152 }
55153 }
55154 // Check that a parameter initializer contains no references to parameters declared to the right of itself
55155 function checkParameterInitializer(node) {
55156 if (ts.getRootDeclaration(node).kind !== 151 /* Parameter */) {
55157 return;
55158 }
55159 var func = ts.getContainingFunction(node);
55160 visit(node.initializer);
55161 function visit(n) {
55162 if (ts.isTypeNode(n) || ts.isDeclarationName(n)) {
55163 // do not dive in types
55164 // skip declaration names (i.e. in object literal expressions)
55165 return;
55166 }
55167 if (n.kind === 189 /* PropertyAccessExpression */) {
55168 // skip property names in property access expression
55169 return visit(n.expression);
55170 }
55171 else if (n.kind === 72 /* Identifier */) {
55172 // check FunctionLikeDeclaration.locals (stores parameters\function local variable)
55173 // if it contains entry with a specified name
55174 var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
55175 if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) {
55176 return;
55177 }
55178 if (symbol.valueDeclaration === node) {
55179 error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name));
55180 return;
55181 }
55182 // locals map for function contain both parameters and function locals
55183 // so we need to do a bit of extra work to check if reference is legal
55184 var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
55185 if (enclosingContainer === func) {
55186 if (symbol.valueDeclaration.kind === 151 /* Parameter */ ||
55187 symbol.valueDeclaration.kind === 186 /* BindingElement */) {
55188 // it is ok to reference parameter in initializer if either
55189 // - parameter is located strictly on the left of current parameter declaration
55190 if (symbol.valueDeclaration.pos < node.pos) {
55191 return;
55192 }
55193 // - parameter is wrapped in function-like entity
55194 if (ts.findAncestor(n, function (current) {
55195 if (current === node.initializer) {
55196 return "quit";
55197 }
55198 return ts.isFunctionLike(current.parent) ||
55199 // computed property names/initializers in instance property declaration of class like entities
55200 // are executed in constructor and thus deferred
55201 (current.parent.kind === 154 /* PropertyDeclaration */ &&
55202 !(ts.hasModifier(current.parent, 32 /* Static */)) &&
55203 ts.isClassLike(current.parent.parent));
55204 })) {
55205 return;
55206 }
55207 // fall through to report error
55208 }
55209 error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n));
55210 }
55211 }
55212 else {
55213 return ts.forEachChild(n, visit);
55214 }
55215 }
55216 }
55217 function convertAutoToAny(type) {
55218 return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
55219 }
55220 // Check variable, parameter, or property declaration
55221 function checkVariableLikeDeclaration(node) {
55222 checkDecorators(node);
55223 if (!ts.isBindingElement(node)) {
55224 checkSourceElement(node.type);
55225 }
55226 // JSDoc `function(string, string): string` syntax results in parameters with no name
55227 if (!node.name) {
55228 return;
55229 }
55230 // For a computed property, just check the initializer and exit
55231 // Do not use hasDynamicName here, because that returns false for well known symbols.
55232 // We want to perform checkComputedPropertyName for all computed properties, including
55233 // well known symbols.
55234 if (node.name.kind === 149 /* ComputedPropertyName */) {
55235 checkComputedPropertyName(node.name);
55236 if (node.initializer) {
55237 checkExpressionCached(node.initializer);
55238 }
55239 }
55240 if (node.kind === 186 /* BindingElement */) {
55241 if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 7 /* ESNext */) {
55242 checkExternalEmitHelpers(node, 4 /* Rest */);
55243 }
55244 // check computed properties inside property names of binding elements
55245 if (node.propertyName && node.propertyName.kind === 149 /* ComputedPropertyName */) {
55246 checkComputedPropertyName(node.propertyName);
55247 }
55248 // check private/protected variable access
55249 var parent = node.parent.parent;
55250 var parentType = getTypeForBindingElementParent(parent);
55251 var name = node.propertyName || node.name;
55252 if (parentType && !ts.isBindingPattern(name)) {
55253 var exprType = getLiteralTypeFromPropertyName(name);
55254 if (isTypeUsableAsPropertyName(exprType)) {
55255 var nameText = getPropertyNameFromType(exprType);
55256 var property = getPropertyOfType(parentType, nameText);
55257 if (property) {
55258 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
55259 checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
55260 }
55261 }
55262 }
55263 }
55264 // For a binding pattern, check contained binding elements
55265 if (ts.isBindingPattern(node.name)) {
55266 if (node.name.kind === 185 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
55267 checkExternalEmitHelpers(node, 512 /* Read */);
55268 }
55269 ts.forEach(node.name.elements, checkSourceElement);
55270 }
55271 // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
55272 if (node.initializer && ts.getRootDeclaration(node).kind === 151 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
55273 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
55274 return;
55275 }
55276 // For a binding pattern, validate the initializer and exit
55277 if (ts.isBindingPattern(node.name)) {
55278 // Don't validate for-in initializer as it is already an error
55279 if (node.initializer && node.parent.parent.kind !== 226 /* ForInStatement */) {
55280 var initializerType = checkExpressionCached(node.initializer);
55281 if (strictNullChecks && node.name.elements.length === 0) {
55282 checkNonNullType(initializerType, node);
55283 }
55284 else {
55285 checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
55286 }
55287 checkParameterInitializer(node);
55288 }
55289 return;
55290 }
55291 var symbol = getSymbolOfNode(node);
55292 var type = convertAutoToAny(getTypeOfSymbol(symbol));
55293 if (node === symbol.valueDeclaration) {
55294 // Node is the primary declaration of the symbol, just validate the initializer
55295 // Don't validate for-in initializer as it is already an error
55296 var initializer = ts.getEffectiveInitializer(node);
55297 if (initializer) {
55298 var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
55299 ts.isObjectLiteralExpression(initializer) &&
55300 (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
55301 ts.hasEntries(symbol.exports);
55302 if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 226 /* ForInStatement */) {
55303 checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
55304 checkParameterInitializer(node);
55305 }
55306 }
55307 if (symbol.declarations.length > 1) {
55308 if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
55309 error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
55310 }
55311 }
55312 }
55313 else {
55314 // Node is a secondary declaration, check that type is identical to primary declaration and check that
55315 // initializer is consistent with type associated with the node
55316 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
55317 if (type !== errorType && declarationType !== errorType &&
55318 !isTypeIdenticalTo(type, declarationType) &&
55319 !(symbol.flags & 67108864 /* Assignment */)) {
55320 errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType);
55321 }
55322 if (node.initializer) {
55323 checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
55324 }
55325 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
55326 error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
55327 }
55328 }
55329 if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */) {
55330 // We know we don't have a binding pattern or computed name here
55331 checkExportsOnMergedDeclarations(node);
55332 if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) {
55333 checkVarDeclaredNamesNotShadowed(node);
55334 }
55335 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
55336 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
55337 }
55338 }
55339 function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) {
55340 var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
55341 var message = nextDeclaration.kind === 154 /* PropertyDeclaration */ || nextDeclaration.kind === 153 /* PropertySignature */
55342 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
55343 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
55344 error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType));
55345 }
55346 function areDeclarationFlagsIdentical(left, right) {
55347 if ((left.kind === 151 /* Parameter */ && right.kind === 237 /* VariableDeclaration */) ||
55348 (left.kind === 237 /* VariableDeclaration */ && right.kind === 151 /* Parameter */)) {
55349 // Differences in optionality between parameters and variables are allowed.
55350 return true;
55351 }
55352 if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
55353 return false;
55354 }
55355 var interestingFlags = 8 /* Private */ |
55356 16 /* Protected */ |
55357 256 /* Async */ |
55358 128 /* Abstract */ |
55359 64 /* Readonly */ |
55360 32 /* Static */;
55361 return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags);
55362 }
55363 function checkVariableDeclaration(node) {
55364 checkGrammarVariableDeclaration(node);
55365 return checkVariableLikeDeclaration(node);
55366 }
55367 function checkBindingElement(node) {
55368 checkGrammarBindingElement(node);
55369 return checkVariableLikeDeclaration(node);
55370 }
55371 function checkVariableStatement(node) {
55372 // Grammar checking
55373 if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
55374 checkGrammarForDisallowedLetOrConstStatement(node);
55375 ts.forEach(node.declarationList.declarations, checkSourceElement);
55376 }
55377 function checkExpressionStatement(node) {
55378 // Grammar checking
55379 checkGrammarStatementInAmbientContext(node);
55380 checkExpression(node.expression);
55381 }
55382 function checkIfStatement(node) {
55383 // Grammar checking
55384 checkGrammarStatementInAmbientContext(node);
55385 checkTruthinessExpression(node.expression);
55386 checkSourceElement(node.thenStatement);
55387 if (node.thenStatement.kind === 220 /* EmptyStatement */) {
55388 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
55389 }
55390 checkSourceElement(node.elseStatement);
55391 }
55392 function checkDoStatement(node) {
55393 // Grammar checking
55394 checkGrammarStatementInAmbientContext(node);
55395 checkSourceElement(node.statement);
55396 checkTruthinessExpression(node.expression);
55397 }
55398 function checkWhileStatement(node) {
55399 // Grammar checking
55400 checkGrammarStatementInAmbientContext(node);
55401 checkTruthinessExpression(node.expression);
55402 checkSourceElement(node.statement);
55403 }
55404 function checkTruthinessExpression(node, checkMode) {
55405 var type = checkExpression(node, checkMode);
55406 if (type.flags & 16384 /* Void */) {
55407 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
55408 }
55409 return type;
55410 }
55411 function checkForStatement(node) {
55412 // Grammar checking
55413 if (!checkGrammarStatementInAmbientContext(node)) {
55414 if (node.initializer && node.initializer.kind === 238 /* VariableDeclarationList */) {
55415 checkGrammarVariableDeclarationList(node.initializer);
55416 }
55417 }
55418 if (node.initializer) {
55419 if (node.initializer.kind === 238 /* VariableDeclarationList */) {
55420 ts.forEach(node.initializer.declarations, checkVariableDeclaration);
55421 }
55422 else {
55423 checkExpression(node.initializer);
55424 }
55425 }
55426 if (node.condition)
55427 checkTruthinessExpression(node.condition);
55428 if (node.incrementor)
55429 checkExpression(node.incrementor);
55430 checkSourceElement(node.statement);
55431 if (node.locals) {
55432 registerForUnusedIdentifiersCheck(node);
55433 }
55434 }
55435 function checkForOfStatement(node) {
55436 checkGrammarForInOrForOfStatement(node);
55437 if (node.awaitModifier) {
55438 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
55439 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 7 /* ESNext */) {
55440 // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
55441 checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
55442 }
55443 }
55444 else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
55445 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
55446 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
55447 }
55448 // Check the LHS and RHS
55449 // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
55450 // via checkRightHandSideOfForOf.
55451 // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
55452 // Then check that the RHS is assignable to it.
55453 if (node.initializer.kind === 238 /* VariableDeclarationList */) {
55454 checkForInOrForOfVariableDeclaration(node);
55455 }
55456 else {
55457 var varExpr = node.initializer;
55458 var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier);
55459 // There may be a destructuring assignment on the left side
55460 if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) {
55461 // iteratedType may be undefined. In this case, we still want to check the structure of
55462 // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
55463 // to short circuit the type relation checking as much as possible, so we pass the unknownType.
55464 checkDestructuringAssignment(varExpr, iteratedType || errorType);
55465 }
55466 else {
55467 var leftType = checkExpression(varExpr);
55468 checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access);
55469 // iteratedType will be undefined if the rightType was missing properties/signatures
55470 // required to get its iteratedType (like [Symbol.iterator] or next). This may be
55471 // because we accessed properties from anyType, or it may have led to an error inside
55472 // getElementTypeOfIterable.
55473 if (iteratedType) {
55474 checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
55475 }
55476 }
55477 }
55478 checkSourceElement(node.statement);
55479 if (node.locals) {
55480 registerForUnusedIdentifiersCheck(node);
55481 }
55482 }
55483 function checkForInStatement(node) {
55484 // Grammar checking
55485 checkGrammarForInOrForOfStatement(node);
55486 var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
55487 // TypeScript 1.0 spec (April 2014): 5.4
55488 // In a 'for-in' statement of the form
55489 // for (let VarDecl in Expr) Statement
55490 // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
55491 // and Expr must be an expression of type Any, an object type, or a type parameter type.
55492 if (node.initializer.kind === 238 /* VariableDeclarationList */) {
55493 var variable = node.initializer.declarations[0];
55494 if (variable && ts.isBindingPattern(variable.name)) {
55495 error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
55496 }
55497 checkForInOrForOfVariableDeclaration(node);
55498 }
55499 else {
55500 // In a 'for-in' statement of the form
55501 // for (Var in Expr) Statement
55502 // Var must be an expression classified as a reference of type Any or the String primitive type,
55503 // and Expr must be an expression of type Any, an object type, or a type parameter type.
55504 var varExpr = node.initializer;
55505 var leftType = checkExpression(varExpr);
55506 if (varExpr.kind === 187 /* ArrayLiteralExpression */ || varExpr.kind === 188 /* ObjectLiteralExpression */) {
55507 error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
55508 }
55509 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
55510 error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
55511 }
55512 else {
55513 // run check only former check succeeded to avoid cascading errors
55514 checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access);
55515 }
55516 }
55517 // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
55518 // in this case error about missing name is already reported - do not report extra one
55519 if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
55520 error(node.expression, ts.Diagnostics.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, typeToString(rightType));
55521 }
55522 checkSourceElement(node.statement);
55523 if (node.locals) {
55524 registerForUnusedIdentifiersCheck(node);
55525 }
55526 }
55527 function checkForInOrForOfVariableDeclaration(iterationStatement) {
55528 var variableDeclarationList = iterationStatement.initializer;
55529 // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
55530 if (variableDeclarationList.declarations.length >= 1) {
55531 var decl = variableDeclarationList.declarations[0];
55532 checkVariableDeclaration(decl);
55533 }
55534 }
55535 function checkRightHandSideOfForOf(rhsExpression, awaitModifier) {
55536 var expressionType = checkNonNullExpression(rhsExpression);
55537 return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined);
55538 }
55539 function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) {
55540 if (isTypeAny(inputType)) {
55541 return inputType;
55542 }
55543 return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType;
55544 }
55545 /**
55546 * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
55547 * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
55548 * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
55549 */
55550 function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) {
55551 if (inputType === neverType) {
55552 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
55553 return undefined;
55554 }
55555 var uplevelIteration = languageVersion >= 2 /* ES2015 */;
55556 var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
55557 // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
55558 // or higher, when inside of an async generator or for-await-if, or when
55559 // downlevelIteration is requested.
55560 if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
55561 // We only report errors for an invalid iterable type in ES2015 or higher.
55562 var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability);
55563 if (iteratedType || uplevelIteration) {
55564 return iteratedType;
55565 }
55566 }
55567 var arrayType = inputType;
55568 var reportedError = false;
55569 var hasStringConstituent = false;
55570 // If strings are permitted, remove any string-like constituents from the array type.
55571 // This allows us to find other non-string element types from an array unioned with
55572 // a string.
55573 if (allowStringInput) {
55574 if (arrayType.flags & 1048576 /* Union */) {
55575 // After we remove all types that are StringLike, we will know if there was a string constituent
55576 // based on whether the result of filter is a new array.
55577 var arrayTypes = inputType.types;
55578 var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); });
55579 if (filteredTypes !== arrayTypes) {
55580 arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
55581 }
55582 }
55583 else if (arrayType.flags & 132 /* StringLike */) {
55584 arrayType = neverType;
55585 }
55586 hasStringConstituent = arrayType !== inputType;
55587 if (hasStringConstituent) {
55588 if (languageVersion < 1 /* ES5 */) {
55589 if (errorNode) {
55590 error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
55591 reportedError = true;
55592 }
55593 }
55594 // Now that we've removed all the StringLike types, if no constituents remain, then the entire
55595 // arrayOrStringType was a string.
55596 if (arrayType.flags & 131072 /* Never */) {
55597 return stringType;
55598 }
55599 }
55600 }
55601 if (!isArrayLikeType(arrayType)) {
55602 if (errorNode && !reportedError) {
55603 // Which error we report depends on whether we allow strings or if there was a
55604 // string constituent. For example, if the input type is number | string, we
55605 // want to say that number is not an array type. But if the input was just
55606 // number and string input is allowed, we want to say that number is not an
55607 // array type or a string type.
55608 var isIterable = !!getIteratedTypeOfIterable(inputType, /* errorNode */ undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability);
55609 var diagnostic = !allowStringInput || hasStringConstituent
55610 ? downlevelIteration
55611 ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator
55612 : isIterable
55613 ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators
55614 : ts.Diagnostics.Type_0_is_not_an_array_type
55615 : downlevelIteration
55616 ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator
55617 : isIterable
55618 ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators
55619 : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type;
55620 error(errorNode, diagnostic, typeToString(arrayType));
55621 }
55622 return hasStringConstituent ? stringType : undefined;
55623 }
55624 var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
55625 if (hasStringConstituent && arrayElementType) {
55626 // This is just an optimization for the case where arrayOrStringType is string | string[]
55627 if (arrayElementType.flags & 132 /* StringLike */) {
55628 return stringType;
55629 }
55630 return getUnionType([arrayElementType, stringType], 2 /* Subtype */);
55631 }
55632 return arrayElementType;
55633 }
55634 /**
55635 * We want to treat type as an iterable, and get the type it is an iterable of. The iterable
55636 * must have the following structure (annotated with the names of the variables below):
55637 *
55638 * { // iterable
55639 * [Symbol.iterator]: { // iteratorMethod
55640 * (): Iterator<T>
55641 * }
55642 * }
55643 *
55644 * For an async iterable, we expect the following structure:
55645 *
55646 * { // iterable
55647 * [Symbol.asyncIterator]: { // iteratorMethod
55648 * (): AsyncIterator<T>
55649 * }
55650 * }
55651 *
55652 * T is the type we are after. At every level that involves analyzing return types
55653 * of signatures, we union the return types of all the signatures.
55654 *
55655 * Another thing to note is that at any step of this process, we could run into a dead end,
55656 * meaning either the property is missing, or we run into the anyType. If either of these things
55657 * happens, we return undefined to signal that we could not find the iterated type. If a property
55658 * is missing, and the previous step did not result in 'any', then we also give an error if the
55659 * caller requested it. Then the caller can decide what to do in the case where there is no iterated
55660 * type. This is different from returning anyType, because that would signify that we have matched the
55661 * whole pattern and that T (above) is 'any'.
55662 *
55663 * For a **for-of** statement, `yield*` (in a normal generator), spread, array
55664 * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
55665 * method.
55666 *
55667 * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
55668 *
55669 * For a **for-await-of** statement or a `yield*` in an async generator we will look for
55670 * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
55671 */
55672 function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) {
55673 if (isTypeAny(type)) {
55674 return undefined;
55675 }
55676 return mapType(type, getIteratedType);
55677 function getIteratedType(type) {
55678 var typeAsIterable = type;
55679 if (allowAsyncIterables) {
55680 if (typeAsIterable.iteratedTypeOfAsyncIterable) {
55681 return typeAsIterable.iteratedTypeOfAsyncIterable;
55682 }
55683 // As an optimization, if the type is an instantiation of the global `AsyncIterable<T>`
55684 // or the global `AsyncIterableIterator<T>` then just grab its type argument.
55685 if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) ||
55686 isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) {
55687 return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0];
55688 }
55689 }
55690 if (allowSyncIterables) {
55691 if (typeAsIterable.iteratedTypeOfIterable) {
55692 return allowAsyncIterables
55693 ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable)
55694 : typeAsIterable.iteratedTypeOfIterable;
55695 }
55696 // As an optimization, if the type is an instantiation of the global `Iterable<T>` or
55697 // `IterableIterator<T>` then just grab its type argument.
55698 if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) ||
55699 isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) {
55700 return allowAsyncIterables
55701 ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0])
55702 : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0];
55703 }
55704 }
55705 var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator"));
55706 var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined);
55707 if (isTypeAny(methodType)) {
55708 return undefined;
55709 }
55710 var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
55711 if (!ts.some(signatures)) {
55712 if (errorNode) {
55713 // only report on the first error
55714 reportTypeNotIterableError(errorNode, type, allowAsyncIterables);
55715 errorNode = undefined;
55716 }
55717 return undefined;
55718 }
55719 var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */);
55720 var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType);
55721 if (checkAssignability && errorNode && iteratedType) {
55722 // If `checkAssignability` was specified, we were called from
55723 // `checkIteratedTypeOrElementType`. As such, we need to validate that
55724 // the type passed in is actually an Iterable.
55725 checkTypeAssignableTo(type, asyncMethodType
55726 ? createAsyncIterableType(iteratedType)
55727 : createIterableType(iteratedType), errorNode);
55728 }
55729 if (iteratedType) {
55730 return allowAsyncIterables
55731 ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType)
55732 : typeAsIterable.iteratedTypeOfIterable = iteratedType;
55733 }
55734 }
55735 }
55736 function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
55737 error(errorNode, allowAsyncIterables
55738 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
55739 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type));
55740 }
55741 /**
55742 * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on
55743 * Iterators instead of Iterables. Here is the structure:
55744 *
55745 * { // iterator
55746 * next: { // nextMethod
55747 * (): { // nextResult
55748 * value: T // nextValue
55749 * }
55750 * }
55751 * }
55752 *
55753 * For an async iterator, we expect the following structure:
55754 *
55755 * { // iterator
55756 * next: { // nextMethod
55757 * (): PromiseLike<{ // nextResult
55758 * value: T // nextValue
55759 * }>
55760 * }
55761 * }
55762 */
55763 function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) {
55764 if (isTypeAny(type)) {
55765 return undefined;
55766 }
55767 var typeAsIterator = type;
55768 if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) {
55769 return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator;
55770 }
55771 // As an optimization, if the type is an instantiation of the global `Iterator<T>` (for
55772 // a non-async iterator) or the global `AsyncIterator<T>` (for an async-iterator) then
55773 // just grab its type argument.
55774 var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType;
55775 if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) {
55776 return isAsyncIterator
55777 ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0]
55778 : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0];
55779 }
55780 // Both async and non-async iterators must have a `next` method.
55781 var nextMethod = getTypeOfPropertyOfType(type, "next");
55782 if (isTypeAny(nextMethod)) {
55783 return undefined;
55784 }
55785 var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : ts.emptyArray;
55786 if (nextMethodSignatures.length === 0) {
55787 if (errorNode) {
55788 error(errorNode, isAsyncIterator
55789 ? ts.Diagnostics.An_async_iterator_must_have_a_next_method
55790 : ts.Diagnostics.An_iterator_must_have_a_next_method);
55791 }
55792 return undefined;
55793 }
55794 var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2 /* Subtype */);
55795 if (isTypeAny(nextResult)) {
55796 return undefined;
55797 }
55798 // For an async iterator, we must get the awaited type of the return type.
55799 if (isAsyncIterator) {
55800 nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property);
55801 if (isTypeAny(nextResult)) {
55802 return undefined;
55803 }
55804 }
55805 var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value");
55806 if (!nextValue) {
55807 if (errorNode) {
55808 error(errorNode, isAsyncIterator
55809 ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property
55810 : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property);
55811 }
55812 return undefined;
55813 }
55814 return isAsyncIterator
55815 ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue
55816 : typeAsIterator.iteratedTypeOfIterator = nextValue;
55817 }
55818 /**
55819 * A generator may have a return type of `Iterator<T>`, `Iterable<T>`, or
55820 * `IterableIterator<T>`. An async generator may have a return type of `AsyncIterator<T>`,
55821 * `AsyncIterable<T>`, or `AsyncIterableIterator<T>`. This function can be used to extract
55822 * the iterated type from this return type for contextual typing and verifying signatures.
55823 */
55824 function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) {
55825 if (isTypeAny(returnType)) {
55826 return undefined;
55827 }
55828 return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false)
55829 || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator);
55830 }
55831 function checkBreakOrContinueStatement(node) {
55832 // Grammar checking
55833 if (!checkGrammarStatementInAmbientContext(node))
55834 checkGrammarBreakOrContinueStatement(node);
55835 // TODO: Check that target label is valid
55836 }
55837 function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
55838 var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */
55839 ? getPromisedTypeOfPromise(returnType) // Async function
55840 : returnType; // AsyncGenerator function, Generator function, or normal function
55841 return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
55842 }
55843 function checkReturnStatement(node) {
55844 // Grammar checking
55845 if (checkGrammarStatementInAmbientContext(node)) {
55846 return;
55847 }
55848 var func = ts.getContainingFunction(node);
55849 if (!func) {
55850 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
55851 return;
55852 }
55853 var signature = getSignatureFromDeclaration(func);
55854 var returnType = getReturnTypeOfSignature(signature);
55855 var functionFlags = ts.getFunctionFlags(func);
55856 var isGenerator = functionFlags & 1 /* Generator */;
55857 if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
55858 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
55859 if (isGenerator) { // AsyncGenerator function or Generator function
55860 // A generator does not need its return expressions checked against its return type.
55861 // Instead, the yield expressions are checked against the element type.
55862 // TODO: Check return types of generators when return type tracking is added
55863 // for generators.
55864 return;
55865 }
55866 else if (func.kind === 159 /* SetAccessor */) {
55867 if (node.expression) {
55868 error(node, ts.Diagnostics.Setters_cannot_return_a_value);
55869 }
55870 }
55871 else if (func.kind === 157 /* Constructor */) {
55872 if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
55873 error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
55874 }
55875 }
55876 else if (getReturnTypeFromAnnotation(func)) {
55877 if (functionFlags & 2 /* Async */) { // Async function
55878 var promisedType = getPromisedTypeOfPromise(returnType);
55879 var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
55880 if (promisedType) {
55881 // If the function has a return type, but promisedType is
55882 // undefined, an error will be reported in checkAsyncFunctionReturnType
55883 // so we don't need to report one here.
55884 checkTypeAssignableToAndOptionallyElaborate(awaitedType, promisedType, node, node.expression);
55885 }
55886 }
55887 else {
55888 checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression);
55889 }
55890 }
55891 }
55892 else if (func.kind !== 157 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) {
55893 // The function has a return type, but the return statement doesn't have an expression.
55894 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
55895 }
55896 }
55897 function checkWithStatement(node) {
55898 // Grammar checking for withStatement
55899 if (!checkGrammarStatementInAmbientContext(node)) {
55900 if (node.flags & 16384 /* AwaitContext */) {
55901 grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
55902 }
55903 }
55904 checkExpression(node.expression);
55905 var sourceFile = ts.getSourceFileOfNode(node);
55906 if (!hasParseDiagnostics(sourceFile)) {
55907 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
55908 var end = node.statement.pos;
55909 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
55910 }
55911 }
55912 function checkSwitchStatement(node) {
55913 // Grammar checking
55914 checkGrammarStatementInAmbientContext(node);
55915 var firstDefaultClause;
55916 var hasDuplicateDefaultClause = false;
55917 var expressionType = checkExpression(node.expression);
55918 var expressionIsLiteral = isLiteralType(expressionType);
55919 ts.forEach(node.caseBlock.clauses, function (clause) {
55920 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
55921 if (clause.kind === 272 /* DefaultClause */ && !hasDuplicateDefaultClause) {
55922 if (firstDefaultClause === undefined) {
55923 firstDefaultClause = clause;
55924 }
55925 else {
55926 var sourceFile = ts.getSourceFileOfNode(node);
55927 var start = ts.skipTrivia(sourceFile.text, clause.pos);
55928 var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end;
55929 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
55930 hasDuplicateDefaultClause = true;
55931 }
55932 }
55933 if (produceDiagnostics && clause.kind === 271 /* CaseClause */) {
55934 // TypeScript 1.0 spec (April 2014): 5.9
55935 // In a 'switch' statement, each 'case' expression must be of a type that is comparable
55936 // to or from the type of the 'switch' expression.
55937 var caseType = checkExpression(clause.expression);
55938 var caseIsLiteral = isLiteralType(caseType);
55939 var comparedExpressionType = expressionType;
55940 if (!caseIsLiteral || !expressionIsLiteral) {
55941 caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
55942 comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
55943 }
55944 if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
55945 // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
55946 checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
55947 }
55948 }
55949 ts.forEach(clause.statements, checkSourceElement);
55950 });
55951 if (node.caseBlock.locals) {
55952 registerForUnusedIdentifiersCheck(node.caseBlock);
55953 }
55954 }
55955 function checkLabeledStatement(node) {
55956 // Grammar checking
55957 if (!checkGrammarStatementInAmbientContext(node)) {
55958 ts.findAncestor(node.parent, function (current) {
55959 if (ts.isFunctionLike(current)) {
55960 return "quit";
55961 }
55962 if (current.kind === 233 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
55963 grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
55964 return true;
55965 }
55966 return false;
55967 });
55968 }
55969 // ensure that label is unique
55970 checkSourceElement(node.statement);
55971 }
55972 function checkThrowStatement(node) {
55973 // Grammar checking
55974 if (!checkGrammarStatementInAmbientContext(node)) {
55975 if (node.expression === undefined) {
55976 grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
55977 }
55978 }
55979 if (node.expression) {
55980 checkExpression(node.expression);
55981 }
55982 }
55983 function checkTryStatement(node) {
55984 // Grammar checking
55985 checkGrammarStatementInAmbientContext(node);
55986 checkBlock(node.tryBlock);
55987 var catchClause = node.catchClause;
55988 if (catchClause) {
55989 // Grammar checking
55990 if (catchClause.variableDeclaration) {
55991 if (catchClause.variableDeclaration.type) {
55992 grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation);
55993 }
55994 else if (catchClause.variableDeclaration.initializer) {
55995 grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
55996 }
55997 else {
55998 var blockLocals_1 = catchClause.block.locals;
55999 if (blockLocals_1) {
56000 ts.forEachKey(catchClause.locals, function (caughtName) {
56001 var blockLocal = blockLocals_1.get(caughtName);
56002 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
56003 grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
56004 }
56005 });
56006 }
56007 }
56008 }
56009 checkBlock(catchClause.block);
56010 }
56011 if (node.finallyBlock) {
56012 checkBlock(node.finallyBlock);
56013 }
56014 }
56015 function checkIndexConstraints(type) {
56016 var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
56017 var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
56018 var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
56019 var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
56020 if (stringIndexType || numberIndexType) {
56021 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
56022 var propType = getTypeOfSymbol(prop);
56023 checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
56024 checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
56025 });
56026 var classDeclaration = type.symbol.valueDeclaration;
56027 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
56028 for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
56029 var member = _a[_i];
56030 // Only process instance properties with computed names here.
56031 // Static properties cannot be in conflict with indexers,
56032 // and properties with literal names were already checked.
56033 if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
56034 var symbol = getSymbolOfNode(member);
56035 var propType = getTypeOfSymbol(symbol);
56036 checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
56037 checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
56038 }
56039 }
56040 }
56041 }
56042 var errorNode;
56043 if (stringIndexType && numberIndexType) {
56044 errorNode = declaredNumberIndexer || declaredStringIndexer;
56045 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
56046 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
56047 var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
56048 errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
56049 }
56050 }
56051 if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
56052 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
56053 }
56054 function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
56055 // ESSymbol properties apply to neither string nor numeric indexers.
56056 if (!indexType || ts.isKnownSymbol(prop)) {
56057 return;
56058 }
56059 var propDeclaration = prop.valueDeclaration;
56060 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
56061 // index is numeric and property name is not valid numeric literal
56062 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
56063 return;
56064 }
56065 // perform property check if property or indexer is declared in 'type'
56066 // this allows us to rule out cases when both property and indexer are inherited from the base class
56067 var errorNode;
56068 if (propDeclaration && name &&
56069 (propDeclaration.kind === 204 /* BinaryExpression */ ||
56070 name.kind === 149 /* ComputedPropertyName */ ||
56071 prop.parent === containingType.symbol)) {
56072 errorNode = propDeclaration;
56073 }
56074 else if (indexDeclaration) {
56075 errorNode = indexDeclaration;
56076 }
56077 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
56078 // for interfaces property and indexer might be inherited from different bases
56079 // check if any base class already has both property and indexer.
56080 // check should be performed only if 'type' is the first type that brings property\indexer together
56081 var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
56082 errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
56083 }
56084 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
56085 var errorMessage = indexKind === 0 /* String */
56086 ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
56087 : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
56088 error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
56089 }
56090 }
56091 }
56092 function checkTypeNameIsReserved(name, message) {
56093 // TS 1.0 spec (April 2014): 3.6.1
56094 // The predefined type keywords are reserved and cannot be used as names of user defined types.
56095 switch (name.escapedText) {
56096 case "any":
56097 case "unknown":
56098 case "number":
56099 case "bigint":
56100 case "boolean":
56101 case "string":
56102 case "symbol":
56103 case "void":
56104 case "object":
56105 error(name, message, name.escapedText);
56106 }
56107 }
56108 /**
56109 * The name cannot be used as 'Object' of user defined types with special target.
56110 */
56111 function checkClassNameCollisionWithObject(name) {
56112 if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
56113 && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) {
56114 error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494
56115 }
56116 }
56117 /**
56118 * Check each type parameter and check that type parameters have no duplicate type parameter declarations
56119 */
56120 function checkTypeParameters(typeParameterDeclarations) {
56121 if (typeParameterDeclarations) {
56122 var seenDefault = false;
56123 for (var i = 0; i < typeParameterDeclarations.length; i++) {
56124 var node = typeParameterDeclarations[i];
56125 checkTypeParameter(node);
56126 if (produceDiagnostics) {
56127 if (node.default) {
56128 seenDefault = true;
56129 checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
56130 }
56131 else if (seenDefault) {
56132 error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
56133 }
56134 for (var j = 0; j < i; j++) {
56135 if (typeParameterDeclarations[j].symbol === node.symbol) {
56136 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
56137 }
56138 }
56139 }
56140 }
56141 }
56142 }
56143 /** Check that type parameter defaults only reference previously declared type parameters */
56144 function checkTypeParametersNotReferenced(root, typeParameters, index) {
56145 visit(root);
56146 function visit(node) {
56147 if (node.kind === 164 /* TypeReference */) {
56148 var type = getTypeFromTypeReference(node);
56149 if (type.flags & 262144 /* TypeParameter */) {
56150 for (var i = index; i < typeParameters.length; i++) {
56151 if (type.symbol === getSymbolOfNode(typeParameters[i])) {
56152 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
56153 }
56154 }
56155 }
56156 }
56157 ts.forEachChild(node, visit);
56158 }
56159 }
56160 /** Check that type parameter lists are identical across multiple declarations */
56161 function checkTypeParameterListsIdentical(symbol) {
56162 if (symbol.declarations.length === 1) {
56163 return;
56164 }
56165 var links = getSymbolLinks(symbol);
56166 if (!links.typeParametersChecked) {
56167 links.typeParametersChecked = true;
56168 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
56169 if (declarations.length <= 1) {
56170 return;
56171 }
56172 var type = getDeclaredTypeOfSymbol(symbol);
56173 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
56174 // Report an error on every conflicting declaration.
56175 var name = symbolToString(symbol);
56176 for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
56177 var declaration = declarations_6[_i];
56178 error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
56179 }
56180 }
56181 }
56182 }
56183 function areTypeParametersIdentical(declarations, targetParameters) {
56184 var maxTypeArgumentCount = ts.length(targetParameters);
56185 var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
56186 for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
56187 var declaration = declarations_7[_i];
56188 // If this declaration has too few or too many type parameters, we report an error
56189 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
56190 var numTypeParameters = sourceParameters.length;
56191 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
56192 return false;
56193 }
56194 for (var i = 0; i < numTypeParameters; i++) {
56195 var source = sourceParameters[i];
56196 var target = targetParameters[i];
56197 // If the type parameter node does not have the same as the resolved type
56198 // parameter at this position, we report an error.
56199 if (source.name.escapedText !== target.symbol.escapedName) {
56200 return false;
56201 }
56202 // If the type parameter node does not have an identical constraint as the resolved
56203 // type parameter at this position, we report an error.
56204 var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
56205 var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
56206 var targetConstraint = getConstraintOfTypeParameter(target);
56207 if (sourceConstraint) {
56208 // relax check if later interface augmentation has no constraint
56209 if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
56210 return false;
56211 }
56212 }
56213 // If the type parameter node has a default and it is not identical to the default
56214 // for the type parameter at this position, we report an error.
56215 var sourceDefault = source.default && getTypeFromTypeNode(source.default);
56216 var targetDefault = getDefaultFromTypeParameter(target);
56217 if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
56218 return false;
56219 }
56220 }
56221 }
56222 return true;
56223 }
56224 function checkClassExpression(node) {
56225 checkClassLikeDeclaration(node);
56226 checkNodeDeferred(node);
56227 return getTypeOfSymbol(getSymbolOfNode(node));
56228 }
56229 function checkClassExpressionDeferred(node) {
56230 ts.forEach(node.members, checkSourceElement);
56231 registerForUnusedIdentifiersCheck(node);
56232 }
56233 function checkClassDeclaration(node) {
56234 if (!node.name && !ts.hasModifier(node, 512 /* Default */)) {
56235 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
56236 }
56237 checkClassLikeDeclaration(node);
56238 ts.forEach(node.members, checkSourceElement);
56239 registerForUnusedIdentifiersCheck(node);
56240 }
56241 function checkClassLikeDeclaration(node) {
56242 checkGrammarClassLikeDeclaration(node);
56243 checkDecorators(node);
56244 if (node.name) {
56245 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
56246 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
56247 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
56248 if (!(node.flags & 4194304 /* Ambient */)) {
56249 checkClassNameCollisionWithObject(node.name);
56250 }
56251 }
56252 checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
56253 checkExportsOnMergedDeclarations(node);
56254 var symbol = getSymbolOfNode(node);
56255 var type = getDeclaredTypeOfSymbol(symbol);
56256 var typeWithThis = getTypeWithThisArgument(type);
56257 var staticType = getTypeOfSymbol(symbol);
56258 checkTypeParameterListsIdentical(symbol);
56259 checkClassForDuplicateDeclarations(node);
56260 // Only check for reserved static identifiers on non-ambient context.
56261 if (!(node.flags & 4194304 /* Ambient */)) {
56262 checkClassForStaticPropertyNameConflicts(node);
56263 }
56264 var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
56265 if (baseTypeNode) {
56266 if (languageVersion < 2 /* ES2015 */) {
56267 checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
56268 }
56269 var baseTypes = getBaseTypes(type);
56270 if (baseTypes.length && produceDiagnostics) {
56271 var baseType_1 = baseTypes[0];
56272 var baseConstructorType = getBaseConstructorTypeOfClass(type);
56273 var staticBaseType = getApparentType(baseConstructorType);
56274 checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
56275 checkSourceElement(baseTypeNode.expression);
56276 var extendsNode = ts.getClassExtendsHeritageElement(node);
56277 if (extendsNode && extendsNode !== baseTypeNode) {
56278 checkExpression(extendsNode.expression);
56279 }
56280 if (ts.some(baseTypeNode.typeArguments)) {
56281 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
56282 for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
56283 var constructor = _a[_i];
56284 if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
56285 break;
56286 }
56287 }
56288 }
56289 var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
56290 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
56291 issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
56292 }
56293 else {
56294 // Report static side error only when instance type is assignable
56295 checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
56296 }
56297 if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
56298 error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
56299 }
56300 if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
56301 // When the static base type is a "class-like" constructor function (but not actually a class), we verify
56302 // that all instantiated base constructor signatures return the same type. We can simply compare the type
56303 // references (as opposed to checking the structure of the types) because elsewhere we have already checked
56304 // that the base type is a class or interface type (and not, for example, an anonymous object type).
56305 // (Javascript constructor functions have this property trivially true since their return type is ignored.)
56306 var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
56307 if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) {
56308 error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
56309 }
56310 }
56311 checkKindsOfPropertyMemberOverrides(type, baseType_1);
56312 }
56313 }
56314 var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node);
56315 if (implementedTypeNodes) {
56316 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
56317 var typeRefNode = implementedTypeNodes_1[_b];
56318 if (!ts.isEntityNameExpression(typeRefNode.expression)) {
56319 error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
56320 }
56321 checkTypeReferenceNode(typeRefNode);
56322 if (produceDiagnostics) {
56323 var t = getTypeFromTypeNode(typeRefNode);
56324 if (t !== errorType) {
56325 if (isValidBaseType(t)) {
56326 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
56327 ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
56328 ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
56329 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
56330 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
56331 issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
56332 }
56333 }
56334 else {
56335 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
56336 }
56337 }
56338 }
56339 }
56340 }
56341 if (produceDiagnostics) {
56342 checkIndexConstraints(type);
56343 checkTypeForDuplicateIndexSignatures(node);
56344 checkPropertyInitialization(node);
56345 }
56346 }
56347 function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
56348 // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
56349 var issuedMemberError = false;
56350 var _loop_9 = function (member) {
56351 if (ts.hasStaticModifier(member)) {
56352 return "continue";
56353 }
56354 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
56355 if (declaredProp) {
56356 var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
56357 var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
56358 if (prop && baseProp) {
56359 var rootChain = function () { return ts.chainDiagnosticMessages(
56360 /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); };
56361 if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
56362 issuedMemberError = true;
56363 }
56364 }
56365 }
56366 };
56367 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
56368 var member = _a[_i];
56369 _loop_9(member);
56370 }
56371 if (!issuedMemberError) {
56372 // check again with diagnostics to generate a less-specific error
56373 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
56374 }
56375 }
56376 function checkBaseTypeAccessibility(type, node) {
56377 var signatures = getSignaturesOfType(type, 1 /* Construct */);
56378 if (signatures.length) {
56379 var declaration = signatures[0].declaration;
56380 if (declaration && ts.hasModifier(declaration, 8 /* Private */)) {
56381 var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
56382 if (!isNodeWithinClass(node, typeClassDeclaration)) {
56383 error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
56384 }
56385 }
56386 }
56387 }
56388 function getTargetSymbol(s) {
56389 // if symbol is instantiated its flags are not copied from the 'target'
56390 // so we'll need to get back original 'target' symbol to work with correct set of flags
56391 return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
56392 }
56393 function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
56394 return ts.filter(symbol.declarations, function (d) {
56395 return d.kind === 240 /* ClassDeclaration */ || d.kind === 241 /* InterfaceDeclaration */;
56396 });
56397 }
56398 function checkKindsOfPropertyMemberOverrides(type, baseType) {
56399 // TypeScript 1.0 spec (April 2014): 8.2.3
56400 // A derived class inherits all members from its base class it doesn't override.
56401 // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
56402 // Both public and private property members are inherited, but only public property members can be overridden.
56403 // A property member in a derived class is said to override a property member in a base class
56404 // when the derived class property member has the same name and kind(instance or static)
56405 // as the base class property member.
56406 // The type of an overriding property member must be assignable(section 3.8.4)
56407 // to the type of the overridden property member, or otherwise a compile - time error occurs.
56408 // Base class instance member functions can be overridden by derived class instance member functions,
56409 // but not by other kinds of members.
56410 // Base class instance member variables and accessors can be overridden by
56411 // derived class instance member variables and accessors, but not by other kinds of members.
56412 // NOTE: assignability is checked in checkClassDeclaration
56413 var baseProperties = getPropertiesOfType(baseType);
56414 for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
56415 var baseProperty = baseProperties_1[_i];
56416 var base = getTargetSymbol(baseProperty);
56417 if (base.flags & 4194304 /* Prototype */) {
56418 continue;
56419 }
56420 var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217
56421 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
56422 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
56423 if (derived) {
56424 // In order to resolve whether the inherited method was overridden in the base class or not,
56425 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
56426 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
56427 if (derived === base) {
56428 // derived class inherits base without override/redeclaration
56429 var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
56430 // It is an error to inherit an abstract member without implementing it or being declared abstract.
56431 // If there is no declaration for the derived class (as in the case of class expressions),
56432 // then the class cannot be declared abstract.
56433 if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) {
56434 if (derivedClassDecl.kind === 209 /* ClassExpression */) {
56435 error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
56436 }
56437 else {
56438 error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
56439 }
56440 }
56441 }
56442 else {
56443 // derived overrides base.
56444 var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
56445 if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
56446 // either base or derived property is private - not override, skip it
56447 continue;
56448 }
56449 if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) {
56450 // method is overridden with method or property/accessor is overridden with property/accessor - correct case
56451 continue;
56452 }
56453 var errorMessage = void 0;
56454 if (isPrototypeProperty(base)) {
56455 if (derived.flags & 98304 /* Accessor */) {
56456 errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
56457 }
56458 else {
56459 errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property;
56460 }
56461 }
56462 else if (base.flags & 98304 /* Accessor */) {
56463 errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
56464 }
56465 else {
56466 errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
56467 }
56468 error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
56469 }
56470 }
56471 }
56472 }
56473 function checkInheritedPropertiesAreIdentical(type, typeNode) {
56474 var baseTypes = getBaseTypes(type);
56475 if (baseTypes.length < 2) {
56476 return true;
56477 }
56478 var seen = ts.createUnderscoreEscapedMap();
56479 ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
56480 var ok = true;
56481 for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
56482 var base = baseTypes_2[_i];
56483 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
56484 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
56485 var prop = properties_6[_a];
56486 var existing = seen.get(prop.escapedName);
56487 if (!existing) {
56488 seen.set(prop.escapedName, { prop: prop, containingType: base });
56489 }
56490 else {
56491 var isInheritedProperty = existing.containingType !== type;
56492 if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
56493 ok = false;
56494 var typeName1 = typeToString(existing.containingType);
56495 var typeName2 = typeToString(base);
56496 var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
56497 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
56498 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
56499 }
56500 }
56501 }
56502 }
56503 return ok;
56504 }
56505 function checkPropertyInitialization(node) {
56506 if (!strictNullChecks || !strictPropertyInitialization || node.flags & 4194304 /* Ambient */) {
56507 return;
56508 }
56509 var constructor = findConstructorDeclaration(node);
56510 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
56511 var member = _a[_i];
56512 if (isInstancePropertyWithoutInitializer(member)) {
56513 var propName = member.name;
56514 if (ts.isIdentifier(propName)) {
56515 var type = getTypeOfSymbol(getSymbolOfNode(member));
56516 if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
56517 if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
56518 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
56519 }
56520 }
56521 }
56522 }
56523 }
56524 }
56525 function isInstancePropertyWithoutInitializer(node) {
56526 return node.kind === 154 /* PropertyDeclaration */ &&
56527 !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
56528 !node.exclamationToken &&
56529 !node.initializer;
56530 }
56531 function isPropertyInitializedInConstructor(propName, propType, constructor) {
56532 var reference = ts.createPropertyAccess(ts.createThis(), propName);
56533 reference.expression.parent = reference;
56534 reference.parent = constructor;
56535 reference.flowNode = constructor.returnFlowNode;
56536 var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
56537 return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
56538 }
56539 function checkInterfaceDeclaration(node) {
56540 // Grammar checking
56541 if (!checkGrammarDecoratorsAndModifiers(node))
56542 checkGrammarInterfaceDeclaration(node);
56543 checkTypeParameters(node.typeParameters);
56544 if (produceDiagnostics) {
56545 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
56546 checkExportsOnMergedDeclarations(node);
56547 var symbol = getSymbolOfNode(node);
56548 checkTypeParameterListsIdentical(symbol);
56549 // Only check this symbol once
56550 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 241 /* InterfaceDeclaration */);
56551 if (node === firstInterfaceDecl) {
56552 var type = getDeclaredTypeOfSymbol(symbol);
56553 var typeWithThis = getTypeWithThisArgument(type);
56554 // run subsequent checks only if first set succeeded
56555 if (checkInheritedPropertiesAreIdentical(type, node.name)) {
56556 for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
56557 var baseType = _a[_i];
56558 checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
56559 }
56560 checkIndexConstraints(type);
56561 }
56562 }
56563 checkObjectTypeForDuplicateDeclarations(node);
56564 }
56565 ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
56566 if (!ts.isEntityNameExpression(heritageElement.expression)) {
56567 error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
56568 }
56569 checkTypeReferenceNode(heritageElement);
56570 });
56571 ts.forEach(node.members, checkSourceElement);
56572 if (produceDiagnostics) {
56573 checkTypeForDuplicateIndexSignatures(node);
56574 registerForUnusedIdentifiersCheck(node);
56575 }
56576 }
56577 function checkTypeAliasDeclaration(node) {
56578 // Grammar checking
56579 checkGrammarDecoratorsAndModifiers(node);
56580 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
56581 checkTypeParameters(node.typeParameters);
56582 checkSourceElement(node.type);
56583 registerForUnusedIdentifiersCheck(node);
56584 }
56585 function computeEnumMemberValues(node) {
56586 var nodeLinks = getNodeLinks(node);
56587 if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
56588 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
56589 var autoValue = 0;
56590 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
56591 var member = _a[_i];
56592 var value = computeMemberValue(member, autoValue);
56593 getNodeLinks(member).enumMemberValue = value;
56594 autoValue = typeof value === "number" ? value + 1 : undefined;
56595 }
56596 }
56597 }
56598 function computeMemberValue(member, autoValue) {
56599 if (isComputedNonLiteralName(member.name)) {
56600 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
56601 }
56602 else {
56603 var text = ts.getTextOfPropertyName(member.name);
56604 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
56605 error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
56606 }
56607 }
56608 if (member.initializer) {
56609 return computeConstantValue(member);
56610 }
56611 // In ambient enum declarations that specify no const modifier, enum member declarations that omit
56612 // a value are considered computed members (as opposed to having auto-incremented values).
56613 if (member.parent.flags & 4194304 /* Ambient */ && !ts.isEnumConst(member.parent)) {
56614 return undefined;
56615 }
56616 // If the member declaration specifies no value, the member is considered a constant enum member.
56617 // If the member is the first member in the enum declaration, it is assigned the value zero.
56618 // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
56619 // occurs if the immediately preceding member is not a constant enum member.
56620 if (autoValue !== undefined) {
56621 return autoValue;
56622 }
56623 error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
56624 return undefined;
56625 }
56626 function computeConstantValue(member) {
56627 var enumKind = getEnumKind(getSymbolOfNode(member.parent));
56628 var isConstEnum = ts.isEnumConst(member.parent);
56629 var initializer = member.initializer;
56630 var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
56631 if (value !== undefined) {
56632 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
56633 error(initializer, isNaN(value) ?
56634 ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
56635 ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
56636 }
56637 }
56638 else if (enumKind === 1 /* Literal */) {
56639 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
56640 return 0;
56641 }
56642 else if (isConstEnum) {
56643 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
56644 }
56645 else if (member.parent.flags & 4194304 /* Ambient */) {
56646 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
56647 }
56648 else {
56649 // Only here do we need to check that the initializer is assignable to the enum type.
56650 checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
56651 }
56652 return value;
56653 function evaluate(expr) {
56654 switch (expr.kind) {
56655 case 202 /* PrefixUnaryExpression */:
56656 var value_2 = evaluate(expr.operand);
56657 if (typeof value_2 === "number") {
56658 switch (expr.operator) {
56659 case 38 /* PlusToken */: return value_2;
56660 case 39 /* MinusToken */: return -value_2;
56661 case 53 /* TildeToken */: return ~value_2;
56662 }
56663 }
56664 break;
56665 case 204 /* BinaryExpression */:
56666 var left = evaluate(expr.left);
56667 var right = evaluate(expr.right);
56668 if (typeof left === "number" && typeof right === "number") {
56669 switch (expr.operatorToken.kind) {
56670 case 50 /* BarToken */: return left | right;
56671 case 49 /* AmpersandToken */: return left & right;
56672 case 47 /* GreaterThanGreaterThanToken */: return left >> right;
56673 case 48 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
56674 case 46 /* LessThanLessThanToken */: return left << right;
56675 case 51 /* CaretToken */: return left ^ right;
56676 case 40 /* AsteriskToken */: return left * right;
56677 case 42 /* SlashToken */: return left / right;
56678 case 38 /* PlusToken */: return left + right;
56679 case 39 /* MinusToken */: return left - right;
56680 case 43 /* PercentToken */: return left % right;
56681 case 41 /* AsteriskAsteriskToken */: return Math.pow(left, right);
56682 }
56683 }
56684 else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 38 /* PlusToken */) {
56685 return left + right;
56686 }
56687 break;
56688 case 10 /* StringLiteral */:
56689 return expr.text;
56690 case 8 /* NumericLiteral */:
56691 checkGrammarNumericLiteral(expr);
56692 return +expr.text;
56693 case 195 /* ParenthesizedExpression */:
56694 return evaluate(expr.expression);
56695 case 72 /* Identifier */:
56696 var identifier = expr;
56697 if (isInfinityOrNaNString(identifier.escapedText)) {
56698 return +(identifier.escapedText);
56699 }
56700 return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
56701 case 190 /* ElementAccessExpression */:
56702 case 189 /* PropertyAccessExpression */:
56703 var ex = expr;
56704 if (isConstantMemberAccess(ex)) {
56705 var type = getTypeOfExpression(ex.expression);
56706 if (type.symbol && type.symbol.flags & 384 /* Enum */) {
56707 var name = void 0;
56708 if (ex.kind === 189 /* PropertyAccessExpression */) {
56709 name = ex.name.escapedText;
56710 }
56711 else {
56712 var argument = ex.argumentExpression;
56713 ts.Debug.assert(ts.isLiteralExpression(argument));
56714 name = ts.escapeLeadingUnderscores(argument.text);
56715 }
56716 return evaluateEnumMember(expr, type.symbol, name);
56717 }
56718 }
56719 break;
56720 }
56721 return undefined;
56722 }
56723 function evaluateEnumMember(expr, enumSymbol, name) {
56724 var memberSymbol = enumSymbol.exports.get(name);
56725 if (memberSymbol) {
56726 var declaration = memberSymbol.valueDeclaration;
56727 if (declaration !== member) {
56728 if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
56729 return getEnumMemberValue(declaration);
56730 }
56731 error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
56732 return 0;
56733 }
56734 }
56735 return undefined;
56736 }
56737 }
56738 function isConstantMemberAccess(node) {
56739 return node.kind === 72 /* Identifier */ ||
56740 node.kind === 189 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
56741 node.kind === 190 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
56742 node.argumentExpression.kind === 10 /* StringLiteral */;
56743 }
56744 function checkEnumDeclaration(node) {
56745 if (!produceDiagnostics) {
56746 return;
56747 }
56748 // Grammar checking
56749 checkGrammarDecoratorsAndModifiers(node);
56750 checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
56751 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
56752 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
56753 checkExportsOnMergedDeclarations(node);
56754 computeEnumMemberValues(node);
56755 // Spec 2014 - Section 9.3:
56756 // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
56757 // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
56758 // for the first member.
56759 //
56760 // Only perform this check once per symbol
56761 var enumSymbol = getSymbolOfNode(node);
56762 var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
56763 if (node === firstDeclaration) {
56764 if (enumSymbol.declarations.length > 1) {
56765 var enumIsConst_1 = ts.isEnumConst(node);
56766 // check that const is placed\omitted on all enum declarations
56767 ts.forEach(enumSymbol.declarations, function (decl) {
56768 if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
56769 error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
56770 }
56771 });
56772 }
56773 var seenEnumMissingInitialInitializer_1 = false;
56774 ts.forEach(enumSymbol.declarations, function (declaration) {
56775 // return true if we hit a violation of the rule, false otherwise
56776 if (declaration.kind !== 243 /* EnumDeclaration */) {
56777 return false;
56778 }
56779 var enumDeclaration = declaration;
56780 if (!enumDeclaration.members.length) {
56781 return false;
56782 }
56783 var firstEnumMember = enumDeclaration.members[0];
56784 if (!firstEnumMember.initializer) {
56785 if (seenEnumMissingInitialInitializer_1) {
56786 error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
56787 }
56788 else {
56789 seenEnumMissingInitialInitializer_1 = true;
56790 }
56791 }
56792 });
56793 }
56794 }
56795 function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
56796 var declarations = symbol.declarations;
56797 for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
56798 var declaration = declarations_8[_i];
56799 if ((declaration.kind === 240 /* ClassDeclaration */ ||
56800 (declaration.kind === 239 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
56801 !(declaration.flags & 4194304 /* Ambient */)) {
56802 return declaration;
56803 }
56804 }
56805 return undefined;
56806 }
56807 function inSameLexicalScope(node1, node2) {
56808 var container1 = ts.getEnclosingBlockScopeContainer(node1);
56809 var container2 = ts.getEnclosingBlockScopeContainer(node2);
56810 if (isGlobalSourceFile(container1)) {
56811 return isGlobalSourceFile(container2);
56812 }
56813 else if (isGlobalSourceFile(container2)) {
56814 return false;
56815 }
56816 else {
56817 return container1 === container2;
56818 }
56819 }
56820 function checkModuleDeclaration(node) {
56821 if (produceDiagnostics) {
56822 // Grammar checking
56823 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
56824 var inAmbientContext = node.flags & 4194304 /* Ambient */;
56825 if (isGlobalAugmentation && !inAmbientContext) {
56826 error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
56827 }
56828 var isAmbientExternalModule = ts.isAmbientModule(node);
56829 var contextErrorMessage = isAmbientExternalModule
56830 ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
56831 : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
56832 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
56833 // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
56834 return;
56835 }
56836 if (!checkGrammarDecoratorsAndModifiers(node)) {
56837 if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
56838 grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
56839 }
56840 }
56841 if (ts.isIdentifier(node.name)) {
56842 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
56843 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
56844 }
56845 checkExportsOnMergedDeclarations(node);
56846 var symbol = getSymbolOfNode(node);
56847 // The following checks only apply on a non-ambient instantiated module declaration.
56848 if (symbol.flags & 512 /* ValueModule */
56849 && !inAmbientContext
56850 && symbol.declarations.length > 1
56851 && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
56852 var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
56853 if (firstNonAmbientClassOrFunc) {
56854 if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
56855 error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
56856 }
56857 else if (node.pos < firstNonAmbientClassOrFunc.pos) {
56858 error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
56859 }
56860 }
56861 // if the module merges with a class declaration in the same lexical scope,
56862 // we need to track this to ensure the correct emit.
56863 var mergedClass = ts.getDeclarationOfKind(symbol, 240 /* ClassDeclaration */);
56864 if (mergedClass &&
56865 inSameLexicalScope(node, mergedClass)) {
56866 getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
56867 }
56868 }
56869 if (isAmbientExternalModule) {
56870 if (ts.isExternalModuleAugmentation(node)) {
56871 // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
56872 // otherwise we'll be swamped in cascading errors.
56873 // We can detect if augmentation was applied using following rules:
56874 // - augmentation for a global scope is always applied
56875 // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
56876 var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
56877 if (checkBody && node.body) {
56878 for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
56879 var statement = _a[_i];
56880 checkModuleAugmentationElement(statement, isGlobalAugmentation);
56881 }
56882 }
56883 }
56884 else if (isGlobalSourceFile(node.parent)) {
56885 if (isGlobalAugmentation) {
56886 error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
56887 }
56888 else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
56889 error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
56890 }
56891 }
56892 else {
56893 if (isGlobalAugmentation) {
56894 error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
56895 }
56896 else {
56897 // Node is not an augmentation and is not located on the script level.
56898 // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
56899 error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
56900 }
56901 }
56902 }
56903 }
56904 if (node.body) {
56905 checkSourceElement(node.body);
56906 if (!ts.isGlobalScopeAugmentation(node)) {
56907 registerForUnusedIdentifiersCheck(node);
56908 }
56909 }
56910 }
56911 function checkModuleAugmentationElement(node, isGlobalAugmentation) {
56912 switch (node.kind) {
56913 case 219 /* VariableStatement */:
56914 // error each individual name in variable statement instead of marking the entire variable statement
56915 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
56916 var decl = _a[_i];
56917 checkModuleAugmentationElement(decl, isGlobalAugmentation);
56918 }
56919 break;
56920 case 254 /* ExportAssignment */:
56921 case 255 /* ExportDeclaration */:
56922 grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
56923 break;
56924 case 248 /* ImportEqualsDeclaration */:
56925 case 249 /* ImportDeclaration */:
56926 grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
56927 break;
56928 case 186 /* BindingElement */:
56929 case 237 /* VariableDeclaration */:
56930 var name = node.name;
56931 if (ts.isBindingPattern(name)) {
56932 for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
56933 var el = _c[_b];
56934 // mark individual names in binding pattern
56935 checkModuleAugmentationElement(el, isGlobalAugmentation);
56936 }
56937 break;
56938 }
56939 // falls through
56940 case 240 /* ClassDeclaration */:
56941 case 243 /* EnumDeclaration */:
56942 case 239 /* FunctionDeclaration */:
56943 case 241 /* InterfaceDeclaration */:
56944 case 244 /* ModuleDeclaration */:
56945 case 242 /* TypeAliasDeclaration */:
56946 if (isGlobalAugmentation) {
56947 return;
56948 }
56949 var symbol = getSymbolOfNode(node);
56950 if (symbol) {
56951 // module augmentations cannot introduce new names on the top level scope of the module
56952 // this is done it two steps
56953 // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
56954 // 2. main check - report error if value declaration of the parent symbol is module augmentation)
56955 var reportError = !(symbol.flags & 33554432 /* Transient */);
56956 if (!reportError) {
56957 // symbol should not originate in augmentation
56958 reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
56959 }
56960 }
56961 break;
56962 }
56963 }
56964 function getFirstIdentifier(node) {
56965 switch (node.kind) {
56966 case 72 /* Identifier */:
56967 return node;
56968 case 148 /* QualifiedName */:
56969 do {
56970 node = node.left;
56971 } while (node.kind !== 72 /* Identifier */);
56972 return node;
56973 case 189 /* PropertyAccessExpression */:
56974 do {
56975 node = node.expression;
56976 } while (node.kind !== 72 /* Identifier */);
56977 return node;
56978 }
56979 }
56980 function checkExternalImportOrExportDeclaration(node) {
56981 var moduleName = ts.getExternalModuleName(node);
56982 if (!moduleName || ts.nodeIsMissing(moduleName)) {
56983 // Should be a parse error.
56984 return false;
56985 }
56986 if (!ts.isStringLiteral(moduleName)) {
56987 error(moduleName, ts.Diagnostics.String_literal_expected);
56988 return false;
56989 }
56990 var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
56991 if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
56992 error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
56993 ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
56994 ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
56995 return false;
56996 }
56997 if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
56998 // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration
56999 // no need to do this again.
57000 if (!isTopLevelInExternalModuleAugmentation(node)) {
57001 // TypeScript 1.0 spec (April 2013): 12.1.6
57002 // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
57003 // other external modules only through top - level external module names.
57004 // Relative external module names are not permitted.
57005 error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
57006 return false;
57007 }
57008 }
57009 return true;
57010 }
57011 function checkAliasSymbol(node) {
57012 var symbol = getSymbolOfNode(node);
57013 var target = resolveAlias(symbol);
57014 if (target !== unknownSymbol) {
57015 // For external modules symbol represent local symbol for an alias.
57016 // This local symbol will merge any other local declarations (excluding other aliases)
57017 // and symbol.flags will contains combined representation for all merged declaration.
57018 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
57019 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
57020 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
57021 var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) |
57022 (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) |
57023 (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
57024 if (target.flags & excludedMeanings) {
57025 var message = node.kind === 257 /* ExportSpecifier */ ?
57026 ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
57027 ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
57028 error(node, message, symbolToString(symbol));
57029 }
57030 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
57031 if (compilerOptions.isolatedModules
57032 && node.kind === 257 /* ExportSpecifier */
57033 && !(target.flags & 67220415 /* Value */)
57034 && !(node.flags & 4194304 /* Ambient */)) {
57035 error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided);
57036 }
57037 }
57038 }
57039 function checkImportBinding(node) {
57040 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
57041 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
57042 checkAliasSymbol(node);
57043 }
57044 function checkImportDeclaration(node) {
57045 if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
57046 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
57047 return;
57048 }
57049 if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
57050 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
57051 }
57052 if (checkExternalImportOrExportDeclaration(node)) {
57053 var importClause = node.importClause;
57054 if (importClause) {
57055 if (importClause.name) {
57056 checkImportBinding(importClause);
57057 }
57058 if (importClause.namedBindings) {
57059 if (importClause.namedBindings.kind === 251 /* NamespaceImport */) {
57060 checkImportBinding(importClause.namedBindings);
57061 }
57062 else {
57063 var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
57064 if (moduleExisted) {
57065 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
57066 }
57067 }
57068 }
57069 }
57070 }
57071 }
57072 function checkImportEqualsDeclaration(node) {
57073 if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
57074 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
57075 return;
57076 }
57077 checkGrammarDecoratorsAndModifiers(node);
57078 if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
57079 checkImportBinding(node);
57080 if (ts.hasModifier(node, 1 /* Export */)) {
57081 markExportAsReferenced(node);
57082 }
57083 if (node.moduleReference.kind !== 259 /* ExternalModuleReference */) {
57084 var target = resolveAlias(getSymbolOfNode(node));
57085 if (target !== unknownSymbol) {
57086 if (target.flags & 67220415 /* Value */) {
57087 // Target is a value symbol, check that it is not hidden by a local declaration with the same name
57088 var moduleName = getFirstIdentifier(node.moduleReference);
57089 if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
57090 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
57091 }
57092 }
57093 if (target.flags & 67897832 /* Type */) {
57094 checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
57095 }
57096 }
57097 }
57098 else {
57099 if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 4194304 /* Ambient */)) {
57100 // Import equals declaration is deprecated in es6 or above
57101 grammarErrorOnNode(node, ts.Diagnostics.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);
57102 }
57103 }
57104 }
57105 }
57106 function checkExportDeclaration(node) {
57107 if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
57108 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
57109 return;
57110 }
57111 if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
57112 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
57113 }
57114 if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
57115 if (node.exportClause) {
57116 // export { x, y }
57117 // export { x, y } from "foo"
57118 ts.forEach(node.exportClause.elements, checkExportSpecifier);
57119 var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
57120 var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
57121 !node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
57122 if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
57123 error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
57124 }
57125 }
57126 else {
57127 // export * from "foo"
57128 var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
57129 if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
57130 error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
57131 }
57132 if (moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) {
57133 checkExternalEmitHelpers(node, 32768 /* ExportStar */);
57134 }
57135 }
57136 }
57137 }
57138 function checkGrammarModuleElementContext(node, errorMessage) {
57139 var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
57140 if (!isInAppropriateContext) {
57141 grammarErrorOnFirstToken(node, errorMessage);
57142 }
57143 return !isInAppropriateContext;
57144 }
57145 function checkExportSpecifier(node) {
57146 checkAliasSymbol(node);
57147 if (ts.getEmitDeclarations(compilerOptions)) {
57148 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
57149 }
57150 if (!node.parent.parent.moduleSpecifier) {
57151 var exportedName = node.propertyName || node.name;
57152 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
57153 var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
57154 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
57155 if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
57156 error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
57157 }
57158 else {
57159 markExportAsReferenced(node);
57160 }
57161 }
57162 }
57163 function checkExportAssignment(node) {
57164 if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
57165 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
57166 return;
57167 }
57168 var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
57169 if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
57170 if (node.isExportEquals) {
57171 error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
57172 }
57173 else {
57174 error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
57175 }
57176 return;
57177 }
57178 // Grammar checking
57179 if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
57180 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
57181 }
57182 if (node.expression.kind === 72 /* Identifier */) {
57183 markExportAsReferenced(node);
57184 if (ts.getEmitDeclarations(compilerOptions)) {
57185 collectLinkedAliases(node.expression, /*setVisibility*/ true);
57186 }
57187 }
57188 else {
57189 checkExpressionCached(node.expression);
57190 }
57191 checkExternalModuleExports(container);
57192 if ((node.flags & 4194304 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
57193 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
57194 }
57195 if (node.isExportEquals && !(node.flags & 4194304 /* Ambient */)) {
57196 if (moduleKind >= ts.ModuleKind.ES2015) {
57197 // export assignment is not supported in es6 modules
57198 grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
57199 }
57200 else if (moduleKind === ts.ModuleKind.System) {
57201 // system modules does not support export assignment
57202 grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
57203 }
57204 }
57205 }
57206 function hasExportedMembers(moduleSymbol) {
57207 return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
57208 }
57209 function checkExternalModuleExports(node) {
57210 var moduleSymbol = getSymbolOfNode(node);
57211 var links = getSymbolLinks(moduleSymbol);
57212 if (!links.exportsChecked) {
57213 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
57214 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
57215 var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
57216 if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
57217 error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
57218 }
57219 }
57220 // Checks for export * conflicts
57221 var exports_1 = getExportsOfModule(moduleSymbol);
57222 if (exports_1) {
57223 exports_1.forEach(function (_a, id) {
57224 var declarations = _a.declarations, flags = _a.flags;
57225 if (id === "__export") {
57226 return;
57227 }
57228 // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
57229 // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
57230 if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
57231 return;
57232 }
57233 var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
57234 if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
57235 // it is legal to merge type alias with other values
57236 // so count should be either 1 (just type alias) or 2 (type alias + merged value)
57237 return;
57238 }
57239 if (exportedDeclarationsCount > 1) {
57240 for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
57241 var declaration = declarations_9[_i];
57242 if (isNotOverload(declaration)) {
57243 diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
57244 }
57245 }
57246 }
57247 });
57248 }
57249 links.exportsChecked = true;
57250 }
57251 }
57252 function isNotAccessor(declaration) {
57253 // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
57254 return !ts.isAccessor(declaration);
57255 }
57256 function isNotOverload(declaration) {
57257 return (declaration.kind !== 239 /* FunctionDeclaration */ && declaration.kind !== 156 /* MethodDeclaration */) ||
57258 !!declaration.body;
57259 }
57260 function checkSourceElement(node) {
57261 if (node) {
57262 var saveCurrentNode = currentNode;
57263 currentNode = node;
57264 checkSourceElementWorker(node);
57265 currentNode = saveCurrentNode;
57266 }
57267 }
57268 function checkSourceElementWorker(node) {
57269 if (ts.isInJSFile(node)) {
57270 ts.forEach(node.jsDoc, function (_a) {
57271 var tags = _a.tags;
57272 return ts.forEach(tags, checkSourceElement);
57273 });
57274 }
57275 var kind = node.kind;
57276 if (cancellationToken) {
57277 // Only bother checking on a few construct kinds. We don't want to be excessively
57278 // hitting the cancellation token on every node we check.
57279 switch (kind) {
57280 case 244 /* ModuleDeclaration */:
57281 case 240 /* ClassDeclaration */:
57282 case 241 /* InterfaceDeclaration */:
57283 case 239 /* FunctionDeclaration */:
57284 cancellationToken.throwIfCancellationRequested();
57285 }
57286 }
57287 switch (kind) {
57288 case 150 /* TypeParameter */:
57289 return checkTypeParameter(node);
57290 case 151 /* Parameter */:
57291 return checkParameter(node);
57292 case 154 /* PropertyDeclaration */:
57293 case 153 /* PropertySignature */:
57294 return checkPropertyDeclaration(node);
57295 case 165 /* FunctionType */:
57296 case 166 /* ConstructorType */:
57297 case 160 /* CallSignature */:
57298 case 161 /* ConstructSignature */:
57299 case 162 /* IndexSignature */:
57300 return checkSignatureDeclaration(node);
57301 case 156 /* MethodDeclaration */:
57302 case 155 /* MethodSignature */:
57303 return checkMethodDeclaration(node);
57304 case 157 /* Constructor */:
57305 return checkConstructorDeclaration(node);
57306 case 158 /* GetAccessor */:
57307 case 159 /* SetAccessor */:
57308 return checkAccessorDeclaration(node);
57309 case 164 /* TypeReference */:
57310 return checkTypeReferenceNode(node);
57311 case 163 /* TypePredicate */:
57312 return checkTypePredicate(node);
57313 case 167 /* TypeQuery */:
57314 return checkTypeQuery(node);
57315 case 168 /* TypeLiteral */:
57316 return checkTypeLiteral(node);
57317 case 169 /* ArrayType */:
57318 return checkArrayType(node);
57319 case 170 /* TupleType */:
57320 return checkTupleType(node);
57321 case 173 /* UnionType */:
57322 case 174 /* IntersectionType */:
57323 return checkUnionOrIntersectionType(node);
57324 case 177 /* ParenthesizedType */:
57325 case 171 /* OptionalType */:
57326 case 172 /* RestType */:
57327 return checkSourceElement(node.type);
57328 case 178 /* ThisType */:
57329 return checkThisType(node);
57330 case 179 /* TypeOperator */:
57331 return checkTypeOperator(node);
57332 case 175 /* ConditionalType */:
57333 return checkConditionalType(node);
57334 case 176 /* InferType */:
57335 return checkInferType(node);
57336 case 183 /* ImportType */:
57337 return checkImportType(node);
57338 case 300 /* JSDocAugmentsTag */:
57339 return checkJSDocAugmentsTag(node);
57340 case 309 /* JSDocTypedefTag */:
57341 case 302 /* JSDocCallbackTag */:
57342 return checkJSDocTypeAliasTag(node);
57343 case 308 /* JSDocTemplateTag */:
57344 return checkJSDocTemplateTag(node);
57345 case 307 /* JSDocTypeTag */:
57346 return checkJSDocTypeTag(node);
57347 case 304 /* JSDocParameterTag */:
57348 return checkJSDocParameterTag(node);
57349 case 294 /* JSDocFunctionType */:
57350 checkJSDocFunctionType(node);
57351 // falls through
57352 case 292 /* JSDocNonNullableType */:
57353 case 291 /* JSDocNullableType */:
57354 case 289 /* JSDocAllType */:
57355 case 290 /* JSDocUnknownType */:
57356 case 297 /* JSDocTypeLiteral */:
57357 checkJSDocTypeIsInJsFile(node);
57358 ts.forEachChild(node, checkSourceElement);
57359 return;
57360 case 295 /* JSDocVariadicType */:
57361 checkJSDocVariadicType(node);
57362 return;
57363 case 288 /* JSDocTypeExpression */:
57364 return checkSourceElement(node.type);
57365 case 180 /* IndexedAccessType */:
57366 return checkIndexedAccessType(node);
57367 case 181 /* MappedType */:
57368 return checkMappedType(node);
57369 case 239 /* FunctionDeclaration */:
57370 return checkFunctionDeclaration(node);
57371 case 218 /* Block */:
57372 case 245 /* ModuleBlock */:
57373 return checkBlock(node);
57374 case 219 /* VariableStatement */:
57375 return checkVariableStatement(node);
57376 case 221 /* ExpressionStatement */:
57377 return checkExpressionStatement(node);
57378 case 222 /* IfStatement */:
57379 return checkIfStatement(node);
57380 case 223 /* DoStatement */:
57381 return checkDoStatement(node);
57382 case 224 /* WhileStatement */:
57383 return checkWhileStatement(node);
57384 case 225 /* ForStatement */:
57385 return checkForStatement(node);
57386 case 226 /* ForInStatement */:
57387 return checkForInStatement(node);
57388 case 227 /* ForOfStatement */:
57389 return checkForOfStatement(node);
57390 case 228 /* ContinueStatement */:
57391 case 229 /* BreakStatement */:
57392 return checkBreakOrContinueStatement(node);
57393 case 230 /* ReturnStatement */:
57394 return checkReturnStatement(node);
57395 case 231 /* WithStatement */:
57396 return checkWithStatement(node);
57397 case 232 /* SwitchStatement */:
57398 return checkSwitchStatement(node);
57399 case 233 /* LabeledStatement */:
57400 return checkLabeledStatement(node);
57401 case 234 /* ThrowStatement */:
57402 return checkThrowStatement(node);
57403 case 235 /* TryStatement */:
57404 return checkTryStatement(node);
57405 case 237 /* VariableDeclaration */:
57406 return checkVariableDeclaration(node);
57407 case 186 /* BindingElement */:
57408 return checkBindingElement(node);
57409 case 240 /* ClassDeclaration */:
57410 return checkClassDeclaration(node);
57411 case 241 /* InterfaceDeclaration */:
57412 return checkInterfaceDeclaration(node);
57413 case 242 /* TypeAliasDeclaration */:
57414 return checkTypeAliasDeclaration(node);
57415 case 243 /* EnumDeclaration */:
57416 return checkEnumDeclaration(node);
57417 case 244 /* ModuleDeclaration */:
57418 return checkModuleDeclaration(node);
57419 case 249 /* ImportDeclaration */:
57420 return checkImportDeclaration(node);
57421 case 248 /* ImportEqualsDeclaration */:
57422 return checkImportEqualsDeclaration(node);
57423 case 255 /* ExportDeclaration */:
57424 return checkExportDeclaration(node);
57425 case 254 /* ExportAssignment */:
57426 return checkExportAssignment(node);
57427 case 220 /* EmptyStatement */:
57428 case 236 /* DebuggerStatement */:
57429 checkGrammarStatementInAmbientContext(node);
57430 return;
57431 case 258 /* MissingDeclaration */:
57432 return checkMissingDeclaration(node);
57433 }
57434 }
57435 function checkJSDocTypeIsInJsFile(node) {
57436 if (!ts.isInJSFile(node)) {
57437 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
57438 }
57439 }
57440 function checkJSDocVariadicType(node) {
57441 checkJSDocTypeIsInJsFile(node);
57442 checkSourceElement(node.type);
57443 // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
57444 var parent = node.parent;
57445 if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
57446 if (ts.last(parent.parent.parameters) !== parent) {
57447 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
57448 }
57449 return;
57450 }
57451 if (!ts.isJSDocTypeExpression(parent)) {
57452 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
57453 }
57454 var paramTag = node.parent.parent;
57455 if (!ts.isJSDocParameterTag(paramTag)) {
57456 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
57457 return;
57458 }
57459 var param = ts.getParameterSymbolFromJSDoc(paramTag);
57460 if (!param) {
57461 // We will error in `checkJSDocParameterTag`.
57462 return;
57463 }
57464 var host = ts.getHostSignatureFromJSDoc(paramTag);
57465 if (!host || ts.last(host.parameters).symbol !== param) {
57466 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
57467 }
57468 }
57469 function getTypeFromJSDocVariadicType(node) {
57470 var type = getTypeFromTypeNode(node.type);
57471 var parent = node.parent;
57472 var paramTag = node.parent.parent;
57473 if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
57474 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
57475 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
57476 if (host_1) {
57477 /*
57478 Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
57479 So in the following situation we will not create an array type:
57480 /** @param {...number} a * /
57481 function f(a) {}
57482 Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
57483 */
57484 var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
57485 var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
57486 if (!lastParamDeclaration ||
57487 symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
57488 return createArrayType(type);
57489 }
57490 }
57491 }
57492 if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
57493 return createArrayType(type);
57494 }
57495 return addOptionality(type);
57496 }
57497 // Function and class expression bodies are checked after all statements in the enclosing body. This is
57498 // to ensure constructs like the following are permitted:
57499 // const foo = function () {
57500 // const s = foo();
57501 // return "hello";
57502 // }
57503 // Here, performing a full type check of the body of the function expression whilst in the process of
57504 // determining the type of foo would cause foo to be given type any because of the recursive reference.
57505 // Delaying the type check of the body ensures foo has been assigned a type.
57506 function checkNodeDeferred(node) {
57507 var enclosingFile = ts.getSourceFileOfNode(node);
57508 var links = getNodeLinks(enclosingFile);
57509 if (!(links.flags & 1 /* TypeChecked */)) {
57510 links.deferredNodes = links.deferredNodes || ts.createMap();
57511 var id = "" + getNodeId(node);
57512 links.deferredNodes.set(id, node);
57513 }
57514 }
57515 function checkDeferredNodes(context) {
57516 var links = getNodeLinks(context);
57517 if (links.deferredNodes) {
57518 links.deferredNodes.forEach(checkDeferredNode);
57519 }
57520 }
57521 function checkDeferredNode(node) {
57522 var saveCurrentNode = currentNode;
57523 currentNode = node;
57524 switch (node.kind) {
57525 case 196 /* FunctionExpression */:
57526 case 197 /* ArrowFunction */:
57527 case 156 /* MethodDeclaration */:
57528 case 155 /* MethodSignature */:
57529 checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
57530 break;
57531 case 158 /* GetAccessor */:
57532 case 159 /* SetAccessor */:
57533 checkAccessorDeclaration(node);
57534 break;
57535 case 209 /* ClassExpression */:
57536 checkClassExpressionDeferred(node);
57537 break;
57538 case 261 /* JsxSelfClosingElement */:
57539 checkJsxSelfClosingElementDeferred(node);
57540 break;
57541 case 260 /* JsxElement */:
57542 checkJsxElementDeferred(node);
57543 break;
57544 }
57545 currentNode = saveCurrentNode;
57546 }
57547 function checkSourceFile(node) {
57548 ts.performance.mark("beforeCheck");
57549 checkSourceFileWorker(node);
57550 ts.performance.mark("afterCheck");
57551 ts.performance.measure("Check", "beforeCheck", "afterCheck");
57552 }
57553 function unusedIsError(kind) {
57554 switch (kind) {
57555 case 0 /* Local */:
57556 return !!compilerOptions.noUnusedLocals;
57557 case 1 /* Parameter */:
57558 return !!compilerOptions.noUnusedParameters;
57559 default:
57560 return ts.Debug.assertNever(kind);
57561 }
57562 }
57563 function getPotentiallyUnusedIdentifiers(sourceFile) {
57564 return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
57565 }
57566 // Fully type check a source file and collect the relevant diagnostics.
57567 function checkSourceFileWorker(node) {
57568 var links = getNodeLinks(node);
57569 if (!(links.flags & 1 /* TypeChecked */)) {
57570 if (ts.skipTypeChecking(node, compilerOptions)) {
57571 return;
57572 }
57573 // Grammar checking
57574 checkGrammarSourceFile(node);
57575 ts.clear(potentialThisCollisions);
57576 ts.clear(potentialNewTargetCollisions);
57577 ts.forEach(node.statements, checkSourceElement);
57578 checkSourceElement(node.endOfFileToken);
57579 checkDeferredNodes(node);
57580 if (ts.isExternalOrCommonJsModule(node)) {
57581 registerForUnusedIdentifiersCheck(node);
57582 }
57583 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
57584 checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
57585 if (!ts.containsParseError(containingNode) && unusedIsError(kind)) {
57586 diagnostics.add(diag);
57587 }
57588 });
57589 }
57590 if (ts.isExternalOrCommonJsModule(node)) {
57591 checkExternalModuleExports(node);
57592 }
57593 if (potentialThisCollisions.length) {
57594 ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
57595 ts.clear(potentialThisCollisions);
57596 }
57597 if (potentialNewTargetCollisions.length) {
57598 ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
57599 ts.clear(potentialNewTargetCollisions);
57600 }
57601 links.flags |= 1 /* TypeChecked */;
57602 }
57603 }
57604 function getDiagnostics(sourceFile, ct) {
57605 try {
57606 // Record the cancellation token so it can be checked later on during checkSourceElement.
57607 // Do this in a finally block so we can ensure that it gets reset back to nothing after
57608 // this call is done.
57609 cancellationToken = ct;
57610 return getDiagnosticsWorker(sourceFile);
57611 }
57612 finally {
57613 cancellationToken = undefined;
57614 }
57615 }
57616 function getDiagnosticsWorker(sourceFile) {
57617 throwIfNonDiagnosticsProducing();
57618 if (sourceFile) {
57619 // Some global diagnostics are deferred until they are needed and
57620 // may not be reported in the first call to getGlobalDiagnostics.
57621 // We should catch these changes and report them.
57622 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
57623 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
57624 checkSourceFile(sourceFile);
57625 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
57626 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
57627 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
57628 // If the arrays are not the same reference, new diagnostics were added.
57629 var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
57630 return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
57631 }
57632 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
57633 // If the arrays are the same reference, but the length has changed, a single
57634 // new diagnostic was added as DiagnosticCollection attempts to reuse the
57635 // same array.
57636 return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
57637 }
57638 return semanticDiagnostics;
57639 }
57640 // Global diagnostics are always added when a file is not provided to
57641 // getDiagnostics
57642 ts.forEach(host.getSourceFiles(), checkSourceFile);
57643 return diagnostics.getDiagnostics();
57644 }
57645 function getGlobalDiagnostics() {
57646 throwIfNonDiagnosticsProducing();
57647 return diagnostics.getGlobalDiagnostics();
57648 }
57649 function throwIfNonDiagnosticsProducing() {
57650 if (!produceDiagnostics) {
57651 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
57652 }
57653 }
57654 // Language service support
57655 function getSymbolsInScope(location, meaning) {
57656 if (location.flags & 8388608 /* InWithStatement */) {
57657 // We cannot answer semantic questions within a with block, do not proceed any further
57658 return [];
57659 }
57660 var symbols = ts.createSymbolTable();
57661 var isStatic = false;
57662 populateSymbols();
57663 symbols.delete("this" /* This */); // Not a symbol, a keyword
57664 return symbolsToArray(symbols);
57665 function populateSymbols() {
57666 while (location) {
57667 if (location.locals && !isGlobalSourceFile(location)) {
57668 copySymbols(location.locals, meaning);
57669 }
57670 switch (location.kind) {
57671 case 284 /* SourceFile */:
57672 if (!ts.isExternalOrCommonJsModule(location))
57673 break;
57674 // falls through
57675 case 244 /* ModuleDeclaration */:
57676 copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
57677 break;
57678 case 243 /* EnumDeclaration */:
57679 copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
57680 break;
57681 case 209 /* ClassExpression */:
57682 var className = location.name;
57683 if (className) {
57684 copySymbol(location.symbol, meaning);
57685 }
57686 // falls through
57687 // this fall-through is necessary because we would like to handle
57688 // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration
57689 case 240 /* ClassDeclaration */:
57690 case 241 /* InterfaceDeclaration */:
57691 // If we didn't come from static member of class or interface,
57692 // add the type parameters into the symbol table
57693 // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
57694 // Note: that the memberFlags come from previous iteration.
57695 if (!isStatic) {
57696 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */);
57697 }
57698 break;
57699 case 196 /* FunctionExpression */:
57700 var funcName = location.name;
57701 if (funcName) {
57702 copySymbol(location.symbol, meaning);
57703 }
57704 break;
57705 }
57706 if (ts.introducesArgumentsExoticObject(location)) {
57707 copySymbol(argumentsSymbol, meaning);
57708 }
57709 isStatic = ts.hasModifier(location, 32 /* Static */);
57710 location = location.parent;
57711 }
57712 copySymbols(globals, meaning);
57713 }
57714 /**
57715 * Copy the given symbol into symbol tables if the symbol has the given meaning
57716 * and it doesn't already existed in the symbol table
57717 * @param key a key for storing in symbol table; if undefined, use symbol.name
57718 * @param symbol the symbol to be added into symbol table
57719 * @param meaning meaning of symbol to filter by before adding to symbol table
57720 */
57721 function copySymbol(symbol, meaning) {
57722 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
57723 var id = symbol.escapedName;
57724 // We will copy all symbol regardless of its reserved name because
57725 // symbolsToArray will check whether the key is a reserved name and
57726 // it will not copy symbol with reserved name to the array
57727 if (!symbols.has(id)) {
57728 symbols.set(id, symbol);
57729 }
57730 }
57731 }
57732 function copySymbols(source, meaning) {
57733 if (meaning) {
57734 source.forEach(function (symbol) {
57735 copySymbol(symbol, meaning);
57736 });
57737 }
57738 }
57739 }
57740 function isTypeDeclarationName(name) {
57741 return name.kind === 72 /* Identifier */ &&
57742 isTypeDeclaration(name.parent) &&
57743 name.parent.name === name;
57744 }
57745 function isTypeDeclaration(node) {
57746 switch (node.kind) {
57747 case 150 /* TypeParameter */:
57748 case 240 /* ClassDeclaration */:
57749 case 241 /* InterfaceDeclaration */:
57750 case 242 /* TypeAliasDeclaration */:
57751 case 243 /* EnumDeclaration */:
57752 return true;
57753 default:
57754 return false;
57755 }
57756 }
57757 // True if the given identifier is part of a type reference
57758 function isTypeReferenceIdentifier(node) {
57759 while (node.parent.kind === 148 /* QualifiedName */) {
57760 node = node.parent;
57761 }
57762 return node.parent.kind === 164 /* TypeReference */;
57763 }
57764 function isHeritageClauseElementIdentifier(node) {
57765 while (node.parent.kind === 189 /* PropertyAccessExpression */) {
57766 node = node.parent;
57767 }
57768 return node.parent.kind === 211 /* ExpressionWithTypeArguments */;
57769 }
57770 function forEachEnclosingClass(node, callback) {
57771 var result;
57772 while (true) {
57773 node = ts.getContainingClass(node);
57774 if (!node)
57775 break;
57776 if (result = callback(node))
57777 break;
57778 }
57779 return result;
57780 }
57781 function isNodeUsedDuringClassInitialization(node) {
57782 return !!ts.findAncestor(node, function (element) {
57783 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
57784 return true;
57785 }
57786 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
57787 return "quit";
57788 }
57789 return false;
57790 });
57791 }
57792 function isNodeWithinClass(node, classDeclaration) {
57793 return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
57794 }
57795 function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
57796 while (nodeOnRightSide.parent.kind === 148 /* QualifiedName */) {
57797 nodeOnRightSide = nodeOnRightSide.parent;
57798 }
57799 if (nodeOnRightSide.parent.kind === 248 /* ImportEqualsDeclaration */) {
57800 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
57801 }
57802 if (nodeOnRightSide.parent.kind === 254 /* ExportAssignment */) {
57803 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
57804 }
57805 return undefined;
57806 }
57807 function isInRightSideOfImportOrExportAssignment(node) {
57808 return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
57809 }
57810 function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
57811 var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
57812 switch (specialPropertyAssignmentKind) {
57813 case 1 /* ExportsProperty */:
57814 case 3 /* PrototypeProperty */:
57815 return getSymbolOfNode(entityName.parent);
57816 case 4 /* ThisProperty */:
57817 case 2 /* ModuleExports */:
57818 case 5 /* Property */:
57819 return getSymbolOfNode(entityName.parent.parent);
57820 }
57821 }
57822 function isImportTypeQualifierPart(node) {
57823 var parent = node.parent;
57824 while (ts.isQualifiedName(parent)) {
57825 node = parent;
57826 parent = parent.parent;
57827 }
57828 if (parent && parent.kind === 183 /* ImportType */ && parent.qualifier === node) {
57829 return parent;
57830 }
57831 return undefined;
57832 }
57833 function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) {
57834 if (ts.isDeclarationName(entityName)) {
57835 return getSymbolOfNode(entityName.parent);
57836 }
57837 if (ts.isInJSFile(entityName) &&
57838 entityName.parent.kind === 189 /* PropertyAccessExpression */ &&
57839 entityName.parent === entityName.parent.parent.left) {
57840 // Check if this is a special property assignment
57841 var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName);
57842 if (specialPropertyAssignmentSymbol) {
57843 return specialPropertyAssignmentSymbol;
57844 }
57845 }
57846 if (entityName.parent.kind === 254 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) {
57847 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
57848 var success = resolveEntityName(entityName,
57849 /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
57850 if (success && success !== unknownSymbol) {
57851 return success;
57852 }
57853 }
57854 else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) {
57855 // Since we already checked for ExportAssignment, this really could only be an Import
57856 var importEqualsDeclaration = ts.getAncestor(entityName, 248 /* ImportEqualsDeclaration */);
57857 ts.Debug.assert(importEqualsDeclaration !== undefined);
57858 return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true);
57859 }
57860 if (!ts.isPropertyAccessExpression(entityName)) {
57861 var possibleImportNode = isImportTypeQualifierPart(entityName);
57862 if (possibleImportNode) {
57863 getTypeFromTypeNode(possibleImportNode);
57864 var sym = getNodeLinks(entityName).resolvedSymbol;
57865 return sym === unknownSymbol ? undefined : sym;
57866 }
57867 }
57868 while (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
57869 entityName = entityName.parent;
57870 }
57871 if (isHeritageClauseElementIdentifier(entityName)) {
57872 var meaning = 0 /* None */;
57873 // In an interface or class, we're definitely interested in a type.
57874 if (entityName.parent.kind === 211 /* ExpressionWithTypeArguments */) {
57875 meaning = 67897832 /* Type */;
57876 // In a class 'extends' clause we are also looking for a value.
57877 if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) {
57878 meaning |= 67220415 /* Value */;
57879 }
57880 }
57881 else {
57882 meaning = 1920 /* Namespace */;
57883 }
57884 meaning |= 2097152 /* Alias */;
57885 var entityNameSymbol = ts.isEntityNameExpression(entityName) ? resolveEntityName(entityName, meaning) : undefined;
57886 if (entityNameSymbol) {
57887 return entityNameSymbol;
57888 }
57889 }
57890 if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
57891 return ts.getParameterSymbolFromJSDoc(entityName.parent);
57892 }
57893 if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
57894 ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
57895 var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
57896 return typeParameter && typeParameter.symbol;
57897 }
57898 if (ts.isExpressionNode(entityName)) {
57899 if (ts.nodeIsMissing(entityName)) {
57900 // Missing entity name.
57901 return undefined;
57902 }
57903 if (entityName.kind === 72 /* Identifier */) {
57904 if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) {
57905 var symbol = getIntrinsicTagSymbol(entityName.parent);
57906 return symbol === unknownSymbol ? undefined : symbol;
57907 }
57908 return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
57909 }
57910 else if (entityName.kind === 189 /* PropertyAccessExpression */ || entityName.kind === 148 /* QualifiedName */) {
57911 var links = getNodeLinks(entityName);
57912 if (links.resolvedSymbol) {
57913 return links.resolvedSymbol;
57914 }
57915 if (entityName.kind === 189 /* PropertyAccessExpression */) {
57916 checkPropertyAccessExpression(entityName);
57917 }
57918 else {
57919 checkQualifiedName(entityName);
57920 }
57921 return links.resolvedSymbol;
57922 }
57923 }
57924 else if (isTypeReferenceIdentifier(entityName)) {
57925 var meaning = entityName.parent.kind === 164 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */;
57926 return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
57927 }
57928 if (entityName.parent.kind === 163 /* TypePredicate */) {
57929 return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */);
57930 }
57931 // Do we want to return undefined here?
57932 return undefined;
57933 }
57934 function getSymbolAtLocation(node) {
57935 if (node.kind === 284 /* SourceFile */) {
57936 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
57937 }
57938 var parent = node.parent;
57939 var grandParent = parent.parent;
57940 if (node.flags & 8388608 /* InWithStatement */) {
57941 // We cannot answer semantic questions within a with block, do not proceed any further
57942 return undefined;
57943 }
57944 if (isDeclarationNameOrImportPropertyName(node)) {
57945 // This is a declaration, call getSymbolOfNode
57946 var parentSymbol = getSymbolOfNode(parent);
57947 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
57948 ? getImmediateAliasedSymbol(parentSymbol)
57949 : parentSymbol;
57950 }
57951 else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
57952 return getSymbolOfNode(parent.parent);
57953 }
57954 if (node.kind === 72 /* Identifier */) {
57955 if (isInRightSideOfImportOrExportAssignment(node)) {
57956 return getSymbolOfEntityNameOrPropertyAccessExpression(node);
57957 }
57958 else if (parent.kind === 186 /* BindingElement */ &&
57959 grandParent.kind === 184 /* ObjectBindingPattern */ &&
57960 node === parent.propertyName) {
57961 var typeOfPattern = getTypeOfNode(grandParent);
57962 var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
57963 if (propertyDeclaration) {
57964 return propertyDeclaration;
57965 }
57966 }
57967 }
57968 switch (node.kind) {
57969 case 72 /* Identifier */:
57970 case 189 /* PropertyAccessExpression */:
57971 case 148 /* QualifiedName */:
57972 return getSymbolOfEntityNameOrPropertyAccessExpression(node);
57973 case 100 /* ThisKeyword */:
57974 var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
57975 if (ts.isFunctionLike(container)) {
57976 var sig = getSignatureFromDeclaration(container);
57977 if (sig.thisParameter) {
57978 return sig.thisParameter;
57979 }
57980 }
57981 if (ts.isInExpressionContext(node)) {
57982 return checkExpression(node).symbol;
57983 }
57984 // falls through
57985 case 178 /* ThisType */:
57986 return getTypeFromThisTypeNode(node).symbol;
57987 case 98 /* SuperKeyword */:
57988 return checkExpression(node).symbol;
57989 case 124 /* ConstructorKeyword */:
57990 // constructor keyword for an overload, should take us to the definition if it exist
57991 var constructorDeclaration = node.parent;
57992 if (constructorDeclaration && constructorDeclaration.kind === 157 /* Constructor */) {
57993 return constructorDeclaration.parent.symbol;
57994 }
57995 return undefined;
57996 case 10 /* StringLiteral */:
57997 case 14 /* NoSubstitutionTemplateLiteral */:
57998 // 1). import x = require("./mo/*gotToDefinitionHere*/d")
57999 // 2). External module name in an import declaration
58000 // 3). Dynamic import call or require in javascript
58001 // 4). type A = import("./f/*gotToDefinitionHere*/oo")
58002 if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
58003 ((node.parent.kind === 249 /* ImportDeclaration */ || node.parent.kind === 255 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
58004 ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
58005 (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
58006 return resolveExternalModuleName(node, node);
58007 }
58008 if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
58009 return getSymbolOfNode(parent);
58010 }
58011 // falls through
58012 case 8 /* NumericLiteral */:
58013 // index access
58014 var objectType = ts.isElementAccessExpression(parent)
58015 ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
58016 : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
58017 ? getTypeFromTypeNode(grandParent.objectType)
58018 : undefined;
58019 return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
58020 case 80 /* DefaultKeyword */:
58021 case 90 /* FunctionKeyword */:
58022 case 37 /* EqualsGreaterThanToken */:
58023 case 76 /* ClassKeyword */:
58024 return getSymbolOfNode(node.parent);
58025 case 183 /* ImportType */:
58026 return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined;
58027 case 85 /* ExportKeyword */:
58028 return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined;
58029 default:
58030 return undefined;
58031 }
58032 }
58033 function getShorthandAssignmentValueSymbol(location) {
58034 if (location && location.kind === 276 /* ShorthandPropertyAssignment */) {
58035 return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */);
58036 }
58037 return undefined;
58038 }
58039 /** Returns the target of an export specifier without following aliases */
58040 function getExportSpecifierLocalTargetSymbol(node) {
58041 return node.parent.parent.moduleSpecifier ?
58042 getExternalModuleMember(node.parent.parent, node) :
58043 resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
58044 }
58045 function getTypeOfNode(node) {
58046 if (node.flags & 8388608 /* InWithStatement */) {
58047 // We cannot answer semantic questions within a with block, do not proceed any further
58048 return errorType;
58049 }
58050 var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
58051 var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
58052 if (ts.isPartOfTypeNode(node)) {
58053 var typeFromTypeNode = getTypeFromTypeNode(node);
58054 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
58055 }
58056 if (ts.isExpressionNode(node)) {
58057 return getRegularTypeOfExpression(node);
58058 }
58059 if (classType && !classDecl.isImplements) {
58060 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
58061 // extends clause of a class. We handle that case here.
58062 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
58063 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
58064 }
58065 if (isTypeDeclaration(node)) {
58066 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
58067 var symbol = getSymbolOfNode(node);
58068 return getDeclaredTypeOfSymbol(symbol);
58069 }
58070 if (isTypeDeclarationName(node)) {
58071 var symbol = getSymbolAtLocation(node);
58072 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
58073 }
58074 if (ts.isDeclaration(node)) {
58075 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
58076 var symbol = getSymbolOfNode(node);
58077 return getTypeOfSymbol(symbol);
58078 }
58079 if (isDeclarationNameOrImportPropertyName(node)) {
58080 var symbol = getSymbolAtLocation(node);
58081 return symbol ? getTypeOfSymbol(symbol) : errorType;
58082 }
58083 if (ts.isBindingPattern(node)) {
58084 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
58085 }
58086 if (isInRightSideOfImportOrExportAssignment(node)) {
58087 var symbol = getSymbolAtLocation(node);
58088 if (symbol) {
58089 var declaredType = getDeclaredTypeOfSymbol(symbol);
58090 return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
58091 }
58092 }
58093 return errorType;
58094 }
58095 // Gets the type of object literal or array literal of destructuring assignment.
58096 // { a } from
58097 // for ( { a } of elems) {
58098 // }
58099 // [ a ] from
58100 // [a] = [ some array ...]
58101 function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) {
58102 ts.Debug.assert(expr.kind === 188 /* ObjectLiteralExpression */ || expr.kind === 187 /* ArrayLiteralExpression */);
58103 // If this is from "for of"
58104 // for ( { a } of elems) {
58105 // }
58106 if (expr.parent.kind === 227 /* ForOfStatement */) {
58107 var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier);
58108 return checkDestructuringAssignment(expr, iteratedType || errorType);
58109 }
58110 // If this is from "for" initializer
58111 // for ({a } = elems[0];.....) { }
58112 if (expr.parent.kind === 204 /* BinaryExpression */) {
58113 var iteratedType = getTypeOfExpression(expr.parent.right);
58114 return checkDestructuringAssignment(expr, iteratedType || errorType);
58115 }
58116 // If this is from nested object binding pattern
58117 // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
58118 if (expr.parent.kind === 275 /* PropertyAssignment */) {
58119 var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent);
58120 return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217
58121 }
58122 // Array literal assignment - array destructuring pattern
58123 ts.Debug.assert(expr.parent.kind === 187 /* ArrayLiteralExpression */);
58124 // [{ property1: p1, property2 }] = elems;
58125 var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent);
58126 var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType;
58127 return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); // TODO: GH#18217
58128 }
58129 // Gets the property symbol corresponding to the property in destructuring assignment
58130 // 'property1' from
58131 // for ( { property1: a } of elems) {
58132 // }
58133 // 'property1' at location 'a' from:
58134 // [a] = [ property1, property2 ]
58135 function getPropertySymbolOfDestructuringAssignment(location) {
58136 // Get the type of the object or array literal and then look for property of given name in the type
58137 var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent);
58138 return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
58139 }
58140 function getRegularTypeOfExpression(expr) {
58141 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
58142 expr = expr.parent;
58143 }
58144 return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
58145 }
58146 /**
58147 * Gets either the static or instance type of a class element, based on
58148 * whether the element is declared as "static".
58149 */
58150 function getParentTypeOfClassElement(node) {
58151 var classSymbol = getSymbolOfNode(node.parent);
58152 return ts.hasModifier(node, 32 /* Static */)
58153 ? getTypeOfSymbol(classSymbol)
58154 : getDeclaredTypeOfSymbol(classSymbol);
58155 }
58156 function getClassElementPropertyKeyType(element) {
58157 var name = element.name;
58158 switch (name.kind) {
58159 case 72 /* Identifier */:
58160 return getLiteralType(ts.idText(name));
58161 case 8 /* NumericLiteral */:
58162 case 10 /* StringLiteral */:
58163 return getLiteralType(name.text);
58164 case 149 /* ComputedPropertyName */:
58165 var nameType = checkComputedPropertyName(name);
58166 return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
58167 default:
58168 ts.Debug.fail("Unsupported property name.");
58169 return errorType;
58170 }
58171 }
58172 // Return the list of properties of the given type, augmented with properties from Function
58173 // if the type has call or construct signatures
58174 function getAugmentedPropertiesOfType(type) {
58175 type = getApparentType(type);
58176 var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
58177 var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
58178 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
58179 undefined;
58180 if (functionType) {
58181 ts.forEach(getPropertiesOfType(functionType), function (p) {
58182 if (!propsByName.has(p.escapedName)) {
58183 propsByName.set(p.escapedName, p);
58184 }
58185 });
58186 }
58187 return getNamedMembers(propsByName);
58188 }
58189 function typeHasCallOrConstructSignatures(type) {
58190 return ts.typeHasCallOrConstructSignatures(type, checker);
58191 }
58192 function getRootSymbols(symbol) {
58193 var roots = getImmediateRootSymbols(symbol);
58194 return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
58195 }
58196 function getImmediateRootSymbols(symbol) {
58197 if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
58198 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
58199 }
58200 else if (symbol.flags & 33554432 /* Transient */) {
58201 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
58202 return leftSpread ? [leftSpread, rightSpread]
58203 : syntheticOrigin ? [syntheticOrigin]
58204 : ts.singleElementArray(tryGetAliasTarget(symbol));
58205 }
58206 return undefined;
58207 }
58208 function tryGetAliasTarget(symbol) {
58209 var target;
58210 var next = symbol;
58211 while (next = getSymbolLinks(next).target) {
58212 target = next;
58213 }
58214 return target;
58215 }
58216 // Emitter support
58217 function isArgumentsLocalBinding(nodeIn) {
58218 if (!ts.isGeneratedIdentifier(nodeIn)) {
58219 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
58220 if (node) {
58221 var isPropertyName_1 = node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.name === node;
58222 return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol;
58223 }
58224 }
58225 return false;
58226 }
58227 function moduleExportsSomeValue(moduleReferenceExpression) {
58228 var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
58229 if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
58230 // If the module is not found or is shorthand, assume that it may export a value.
58231 return true;
58232 }
58233 var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
58234 // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
58235 // otherwise it will return moduleSymbol itself
58236 moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
58237 var symbolLinks = getSymbolLinks(moduleSymbol);
58238 if (symbolLinks.exportsSomeValue === undefined) {
58239 // for export assignments - check if resolved symbol for RHS is itself a value
58240 // otherwise - check if at least one export is value
58241 symbolLinks.exportsSomeValue = hasExportAssignment
58242 ? !!(moduleSymbol.flags & 67220415 /* Value */)
58243 : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
58244 }
58245 return symbolLinks.exportsSomeValue;
58246 function isValue(s) {
58247 s = resolveSymbol(s);
58248 return s && !!(s.flags & 67220415 /* Value */);
58249 }
58250 }
58251 function isNameOfModuleOrEnumDeclaration(node) {
58252 return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
58253 }
58254 // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
58255 // node of the exported entity's container. Otherwise, return undefined.
58256 function getReferencedExportContainer(nodeIn, prefixLocals) {
58257 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
58258 if (node) {
58259 // When resolving the export container for the name of a module or enum
58260 // declaration, we need to start resolution at the declaration's container.
58261 // Otherwise, we could incorrectly resolve the export container as the
58262 // declaration if it contains an exported member with the same name.
58263 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
58264 if (symbol) {
58265 if (symbol.flags & 1048576 /* ExportValue */) {
58266 // If we reference an exported entity within the same module declaration, then whether
58267 // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
58268 // kinds that we do NOT prefix.
58269 var exportSymbol = getMergedSymbol(symbol.exportSymbol);
58270 if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
58271 return undefined;
58272 }
58273 symbol = exportSymbol;
58274 }
58275 var parentSymbol_1 = getParentOfSymbol(symbol);
58276 if (parentSymbol_1) {
58277 if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* SourceFile */) {
58278 var symbolFile = parentSymbol_1.valueDeclaration;
58279 var referenceFile = ts.getSourceFileOfNode(node);
58280 // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
58281 var symbolIsUmdExport = symbolFile !== referenceFile;
58282 return symbolIsUmdExport ? undefined : symbolFile;
58283 }
58284 return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
58285 }
58286 }
58287 }
58288 }
58289 // When resolved as an expression identifier, if the given node references an import, return the declaration of
58290 // that import. Otherwise, return undefined.
58291 function getReferencedImportDeclaration(nodeIn) {
58292 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
58293 if (node) {
58294 var symbol = getReferencedValueSymbol(node);
58295 // We should only get the declaration of an alias if there isn't a local value
58296 // declaration for the symbol
58297 if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) {
58298 return getDeclarationOfAliasSymbol(symbol);
58299 }
58300 }
58301 return undefined;
58302 }
58303 function isSymbolOfDeclarationWithCollidingName(symbol) {
58304 if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
58305 var links = getSymbolLinks(symbol);
58306 if (links.isDeclarationWithCollidingName === undefined) {
58307 var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
58308 if (ts.isStatementWithLocals(container)) {
58309 var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
58310 if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
58311 // redeclaration - always should be renamed
58312 links.isDeclarationWithCollidingName = true;
58313 }
58314 else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
58315 // binding is captured in the function
58316 // should be renamed if:
58317 // - binding is not top level - top level bindings never collide with anything
58318 // AND
58319 // - binding is not declared in loop, should be renamed to avoid name reuse across siblings
58320 // let a, b
58321 // { let x = 1; a = () => x; }
58322 // { let x = 100; b = () => x; }
58323 // console.log(a()); // should print '1'
58324 // console.log(b()); // should print '100'
58325 // OR
58326 // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
58327 // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
58328 // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
58329 // they will not collide with anything
58330 var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
58331 var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
58332 var inLoopBodyBlock = container.kind === 218 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
58333 links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
58334 }
58335 else {
58336 links.isDeclarationWithCollidingName = false;
58337 }
58338 }
58339 }
58340 return links.isDeclarationWithCollidingName;
58341 }
58342 return false;
58343 }
58344 // When resolved as an expression identifier, if the given node references a nested block scoped entity with
58345 // a name that either hides an existing name or might hide it when compiled downlevel,
58346 // return the declaration of that entity. Otherwise, return undefined.
58347 function getReferencedDeclarationWithCollidingName(nodeIn) {
58348 if (!ts.isGeneratedIdentifier(nodeIn)) {
58349 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
58350 if (node) {
58351 var symbol = getReferencedValueSymbol(node);
58352 if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
58353 return symbol.valueDeclaration;
58354 }
58355 }
58356 }
58357 return undefined;
58358 }
58359 // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
58360 // existing name or might hide a name when compiled downlevel
58361 function isDeclarationWithCollidingName(nodeIn) {
58362 var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
58363 if (node) {
58364 var symbol = getSymbolOfNode(node);
58365 if (symbol) {
58366 return isSymbolOfDeclarationWithCollidingName(symbol);
58367 }
58368 }
58369 return false;
58370 }
58371 function isValueAliasDeclaration(node) {
58372 switch (node.kind) {
58373 case 248 /* ImportEqualsDeclaration */:
58374 case 250 /* ImportClause */:
58375 case 251 /* NamespaceImport */:
58376 case 253 /* ImportSpecifier */:
58377 case 257 /* ExportSpecifier */:
58378 return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
58379 case 255 /* ExportDeclaration */:
58380 var exportClause = node.exportClause;
58381 return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration);
58382 case 254 /* ExportAssignment */:
58383 return node.expression
58384 && node.expression.kind === 72 /* Identifier */
58385 ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol)
58386 : true;
58387 }
58388 return false;
58389 }
58390 function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
58391 var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
58392 if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
58393 // parent is not source file or it is not reference to internal module
58394 return false;
58395 }
58396 var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
58397 return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
58398 }
58399 function isAliasResolvedToValue(symbol) {
58400 var target = resolveAlias(symbol);
58401 if (target === unknownSymbol) {
58402 return true;
58403 }
58404 // const enums and modules that contain only const enums are not considered values from the emit perspective
58405 // unless 'preserveConstEnums' option is set to true
58406 return !!(target.flags & 67220415 /* Value */) &&
58407 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
58408 }
58409 function isConstEnumOrConstEnumOnlyModule(s) {
58410 return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
58411 }
58412 function isReferencedAliasDeclaration(node, checkChildren) {
58413 if (ts.isAliasSymbolDeclaration(node)) {
58414 var symbol = getSymbolOfNode(node);
58415 if (symbol && getSymbolLinks(symbol).referenced) {
58416 return true;
58417 }
58418 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
58419 if (target && ts.getModifierFlags(node) & 1 /* Export */ &&
58420 target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
58421 // An `export import ... =` of a value symbol is always considered referenced
58422 return true;
58423 }
58424 }
58425 if (checkChildren) {
58426 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
58427 }
58428 return false;
58429 }
58430 function isImplementationOfOverload(node) {
58431 if (ts.nodeIsPresent(node.body)) {
58432 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
58433 return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
58434 var symbol = getSymbolOfNode(node);
58435 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
58436 // If this function body corresponds to function with multiple signature, it is implementation of overload
58437 // e.g.: function foo(a: string): string;
58438 // function foo(a: number): number;
58439 // function foo(a: any) { // This is implementation of the overloads
58440 // return a;
58441 // }
58442 return signaturesOfSymbol.length > 1 ||
58443 // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
58444 // e.g.: function foo(a: string): string;
58445 // function foo(a: any) { // This is implementation of the overloads
58446 // return a;
58447 // }
58448 (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
58449 }
58450 return false;
58451 }
58452 function isRequiredInitializedParameter(parameter) {
58453 return !!strictNullChecks &&
58454 !isOptionalParameter(parameter) &&
58455 !ts.isJSDocParameterTag(parameter) &&
58456 !!parameter.initializer &&
58457 !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
58458 }
58459 function isOptionalUninitializedParameterProperty(parameter) {
58460 return strictNullChecks &&
58461 isOptionalParameter(parameter) &&
58462 !parameter.initializer &&
58463 ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
58464 }
58465 function isExpandoFunctionDeclaration(node) {
58466 var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
58467 if (!declaration) {
58468 return false;
58469 }
58470 var symbol = getSymbolOfNode(declaration);
58471 if (!symbol || !(symbol.flags & 16 /* Function */)) {
58472 return false;
58473 }
58474 return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); });
58475 }
58476 function getPropertiesOfContainerFunction(node) {
58477 var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
58478 if (!declaration) {
58479 return ts.emptyArray;
58480 }
58481 var symbol = getSymbolOfNode(declaration);
58482 return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
58483 }
58484 function getNodeCheckFlags(node) {
58485 return getNodeLinks(node).flags || 0;
58486 }
58487 function getEnumMemberValue(node) {
58488 computeEnumMemberValues(node.parent);
58489 return getNodeLinks(node).enumMemberValue;
58490 }
58491 function canHaveConstantValue(node) {
58492 switch (node.kind) {
58493 case 278 /* EnumMember */:
58494 case 189 /* PropertyAccessExpression */:
58495 case 190 /* ElementAccessExpression */:
58496 return true;
58497 }
58498 return false;
58499 }
58500 function getConstantValue(node) {
58501 if (node.kind === 278 /* EnumMember */) {
58502 return getEnumMemberValue(node);
58503 }
58504 var symbol = getNodeLinks(node).resolvedSymbol;
58505 if (symbol && (symbol.flags & 8 /* EnumMember */)) {
58506 // inline property\index accesses only for const enums
58507 var member = symbol.valueDeclaration;
58508 if (ts.isEnumConst(member.parent)) {
58509 return getEnumMemberValue(member);
58510 }
58511 }
58512 return undefined;
58513 }
58514 function isFunctionType(type) {
58515 return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
58516 }
58517 function getTypeReferenceSerializationKind(typeNameIn, location) {
58518 // ensure both `typeName` and `location` are parse tree nodes.
58519 var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
58520 if (!typeName)
58521 return ts.TypeReferenceSerializationKind.Unknown;
58522 if (location) {
58523 location = ts.getParseTreeNode(location);
58524 if (!location)
58525 return ts.TypeReferenceSerializationKind.Unknown;
58526 }
58527 // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
58528 var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
58529 // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
58530 var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
58531 if (valueSymbol && valueSymbol === typeSymbol) {
58532 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
58533 if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
58534 return ts.TypeReferenceSerializationKind.Promise;
58535 }
58536 var constructorType = getTypeOfSymbol(valueSymbol);
58537 if (constructorType && isConstructorType(constructorType)) {
58538 return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
58539 }
58540 }
58541 // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
58542 if (!typeSymbol) {
58543 return ts.TypeReferenceSerializationKind.Unknown;
58544 }
58545 var type = getDeclaredTypeOfSymbol(typeSymbol);
58546 if (type === errorType) {
58547 return ts.TypeReferenceSerializationKind.Unknown;
58548 }
58549 else if (type.flags & 3 /* AnyOrUnknown */) {
58550 return ts.TypeReferenceSerializationKind.ObjectType;
58551 }
58552 else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
58553 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
58554 }
58555 else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
58556 return ts.TypeReferenceSerializationKind.BooleanType;
58557 }
58558 else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
58559 return ts.TypeReferenceSerializationKind.NumberLikeType;
58560 }
58561 else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
58562 return ts.TypeReferenceSerializationKind.BigIntLikeType;
58563 }
58564 else if (isTypeAssignableToKind(type, 132 /* StringLike */)) {
58565 return ts.TypeReferenceSerializationKind.StringLikeType;
58566 }
58567 else if (isTupleType(type)) {
58568 return ts.TypeReferenceSerializationKind.ArrayLikeType;
58569 }
58570 else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
58571 return ts.TypeReferenceSerializationKind.ESSymbolType;
58572 }
58573 else if (isFunctionType(type)) {
58574 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
58575 }
58576 else if (isArrayType(type)) {
58577 return ts.TypeReferenceSerializationKind.ArrayLikeType;
58578 }
58579 else {
58580 return ts.TypeReferenceSerializationKind.ObjectType;
58581 }
58582 }
58583 function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
58584 var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
58585 if (!declaration) {
58586 return ts.createToken(120 /* AnyKeyword */);
58587 }
58588 // Get type of the symbol if this is the valid symbol otherwise get type at location
58589 var symbol = getSymbolOfNode(declaration);
58590 var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
58591 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
58592 : errorType;
58593 if (type.flags & 8192 /* UniqueESSymbol */ &&
58594 type.symbol === symbol) {
58595 flags |= 1048576 /* AllowUniqueESSymbolType */;
58596 }
58597 if (addUndefined) {
58598 type = getOptionalType(type);
58599 }
58600 return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
58601 }
58602 function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
58603 var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
58604 if (!signatureDeclaration) {
58605 return ts.createToken(120 /* AnyKeyword */);
58606 }
58607 var signature = getSignatureFromDeclaration(signatureDeclaration);
58608 return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
58609 }
58610 function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
58611 var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
58612 if (!expr) {
58613 return ts.createToken(120 /* AnyKeyword */);
58614 }
58615 var type = getWidenedType(getRegularTypeOfExpression(expr));
58616 return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
58617 }
58618 function hasGlobalName(name) {
58619 return globals.has(ts.escapeLeadingUnderscores(name));
58620 }
58621 function getReferencedValueSymbol(reference, startInDeclarationContainer) {
58622 var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
58623 if (resolvedSymbol) {
58624 return resolvedSymbol;
58625 }
58626 var location = reference;
58627 if (startInDeclarationContainer) {
58628 // When resolving the name of a declaration as a value, we need to start resolution
58629 // at a point outside of the declaration.
58630 var parent = reference.parent;
58631 if (ts.isDeclaration(parent) && reference === parent.name) {
58632 location = getDeclarationContainer(parent);
58633 }
58634 }
58635 return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
58636 }
58637 function getReferencedValueDeclaration(referenceIn) {
58638 if (!ts.isGeneratedIdentifier(referenceIn)) {
58639 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
58640 if (reference) {
58641 var symbol = getReferencedValueSymbol(reference);
58642 if (symbol) {
58643 return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
58644 }
58645 }
58646 }
58647 return undefined;
58648 }
58649 function isLiteralConstDeclaration(node) {
58650 if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
58651 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
58652 }
58653 return false;
58654 }
58655 function literalTypeToNode(type, enclosing, tracker) {
58656 var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing, /*flags*/ undefined, tracker)
58657 : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse();
58658 return enumResult || ts.createLiteral(type.value);
58659 }
58660 function createLiteralConstValue(node, tracker) {
58661 var type = getTypeOfSymbol(getSymbolOfNode(node));
58662 return literalTypeToNode(type, node, tracker);
58663 }
58664 function createResolver() {
58665 // this variable and functions that use it are deliberately moved here from the outer scope
58666 // to avoid scope pollution
58667 var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
58668 var fileToDirective;
58669 if (resolvedTypeReferenceDirectives) {
58670 // populate reverse mapping: file path -> type reference directive that was resolved to this file
58671 fileToDirective = ts.createMap();
58672 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
58673 if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
58674 return;
58675 }
58676 var file = host.getSourceFile(resolvedDirective.resolvedFileName);
58677 // Add the transitive closure of path references loaded by this file (as long as they are not)
58678 // part of an existing type reference.
58679 addReferencedFilesToTypeDirective(file, key);
58680 });
58681 }
58682 return {
58683 getReferencedExportContainer: getReferencedExportContainer,
58684 getReferencedImportDeclaration: getReferencedImportDeclaration,
58685 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
58686 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
58687 isValueAliasDeclaration: function (node) {
58688 node = ts.getParseTreeNode(node);
58689 // Synthesized nodes are always treated like values.
58690 return node ? isValueAliasDeclaration(node) : true;
58691 },
58692 hasGlobalName: hasGlobalName,
58693 isReferencedAliasDeclaration: function (node, checkChildren) {
58694 node = ts.getParseTreeNode(node);
58695 // Synthesized nodes are always treated as referenced.
58696 return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
58697 },
58698 getNodeCheckFlags: function (node) {
58699 node = ts.getParseTreeNode(node);
58700 return node ? getNodeCheckFlags(node) : 0;
58701 },
58702 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
58703 isDeclarationVisible: isDeclarationVisible,
58704 isImplementationOfOverload: isImplementationOfOverload,
58705 isRequiredInitializedParameter: isRequiredInitializedParameter,
58706 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
58707 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
58708 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
58709 createTypeOfDeclaration: createTypeOfDeclaration,
58710 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
58711 createTypeOfExpression: createTypeOfExpression,
58712 createLiteralConstValue: createLiteralConstValue,
58713 isSymbolAccessible: isSymbolAccessible,
58714 isEntityNameVisible: isEntityNameVisible,
58715 getConstantValue: function (nodeIn) {
58716 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
58717 return node ? getConstantValue(node) : undefined;
58718 },
58719 collectLinkedAliases: collectLinkedAliases,
58720 getReferencedValueDeclaration: getReferencedValueDeclaration,
58721 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
58722 isOptionalParameter: isOptionalParameter,
58723 moduleExportsSomeValue: moduleExportsSomeValue,
58724 isArgumentsLocalBinding: isArgumentsLocalBinding,
58725 getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
58726 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
58727 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
58728 isLiteralConstDeclaration: isLiteralConstDeclaration,
58729 isLateBound: function (nodeIn) {
58730 var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
58731 var symbol = node && getSymbolOfNode(node);
58732 return !!(symbol && ts.getCheckFlags(symbol) & 2048 /* Late */);
58733 },
58734 getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; },
58735 getAllAccessorDeclarations: function (accessor) {
58736 accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
58737 var otherKind = accessor.kind === 159 /* SetAccessor */ ? 158 /* GetAccessor */ : 159 /* SetAccessor */;
58738 var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
58739 var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
58740 var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
58741 var setAccessor = accessor.kind === 159 /* SetAccessor */ ? accessor : otherAccessor;
58742 var getAccessor = accessor.kind === 158 /* GetAccessor */ ? accessor : otherAccessor;
58743 return {
58744 firstAccessor: firstAccessor,
58745 secondAccessor: secondAccessor,
58746 setAccessor: setAccessor,
58747 getAccessor: getAccessor
58748 };
58749 },
58750 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
58751 isBindingCapturedByNode: function (node, decl) {
58752 var parseNode = ts.getParseTreeNode(node);
58753 var parseDecl = ts.getParseTreeNode(decl);
58754 return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
58755 }
58756 };
58757 function isInHeritageClause(node) {
58758 return node.parent && node.parent.kind === 211 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 273 /* HeritageClause */;
58759 }
58760 // defined here to avoid outer scope pollution
58761 function getTypeReferenceDirectivesForEntityName(node) {
58762 // program does not have any files with type reference directives - bail out
58763 if (!fileToDirective) {
58764 return undefined;
58765 }
58766 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
58767 // qualified names can only be used as types\namespaces
58768 // identifiers are treated as values only if they appear in type queries
58769 var meaning = 67897832 /* Type */ | 1920 /* Namespace */;
58770 if ((node.kind === 72 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 189 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
58771 meaning = 67220415 /* Value */ | 1048576 /* ExportValue */;
58772 }
58773 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
58774 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
58775 }
58776 // defined here to avoid outer scope pollution
58777 function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
58778 // program does not have any files with type reference directives - bail out
58779 if (!fileToDirective) {
58780 return undefined;
58781 }
58782 if (!isSymbolFromTypeDeclarationFile(symbol)) {
58783 return undefined;
58784 }
58785 // check what declarations in the symbol can contribute to the target meaning
58786 var typeReferenceDirectives;
58787 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
58788 var decl = _a[_i];
58789 // check meaning of the local symbol to see if declaration needs to be analyzed further
58790 if (decl.symbol && decl.symbol.flags & meaning) {
58791 var file = ts.getSourceFileOfNode(decl);
58792 var typeReferenceDirective = fileToDirective.get(file.path);
58793 if (typeReferenceDirective) {
58794 (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
58795 }
58796 else {
58797 // found at least one entry that does not originate from type reference directive
58798 return undefined;
58799 }
58800 }
58801 }
58802 return typeReferenceDirectives;
58803 }
58804 function isSymbolFromTypeDeclarationFile(symbol) {
58805 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
58806 if (!symbol.declarations) {
58807 return false;
58808 }
58809 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
58810 // external modules cannot define or contribute to type declaration files
58811 var current = symbol;
58812 while (true) {
58813 var parent = getParentOfSymbol(current);
58814 if (parent) {
58815 current = parent;
58816 }
58817 else {
58818 break;
58819 }
58820 }
58821 if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
58822 return false;
58823 }
58824 // check that at least one declaration of top level symbol originates from type declaration file
58825 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
58826 var decl = _a[_i];
58827 var file = ts.getSourceFileOfNode(decl);
58828 if (fileToDirective.has(file.path)) {
58829 return true;
58830 }
58831 }
58832 return false;
58833 }
58834 function addReferencedFilesToTypeDirective(file, key) {
58835 if (fileToDirective.has(file.path))
58836 return;
58837 fileToDirective.set(file.path, key);
58838 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
58839 var fileName = _a[_i].fileName;
58840 var resolvedFile = ts.resolveTripleslashReference(fileName, file.originalFileName);
58841 var referencedFile = host.getSourceFile(resolvedFile);
58842 if (referencedFile) {
58843 addReferencedFilesToTypeDirective(referencedFile, key);
58844 }
58845 }
58846 }
58847 }
58848 function getExternalModuleFileFromDeclaration(declaration) {
58849 var specifier = declaration.kind === 244 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
58850 var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
58851 if (!moduleSymbol) {
58852 return undefined;
58853 }
58854 return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
58855 }
58856 function initializeTypeChecker() {
58857 // Bind all source files and propagate errors
58858 for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
58859 var file = _a[_i];
58860 ts.bindSourceFile(file, compilerOptions);
58861 }
58862 amalgamatedDuplicates = ts.createMap();
58863 // Initialize global symbol table
58864 var augmentations;
58865 for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
58866 var file = _c[_b];
58867 if (file.redirectInfo) {
58868 continue;
58869 }
58870 if (!ts.isExternalOrCommonJsModule(file)) {
58871 mergeSymbolTable(globals, file.locals);
58872 }
58873 if (file.jsGlobalAugmentations) {
58874 mergeSymbolTable(globals, file.jsGlobalAugmentations);
58875 }
58876 if (file.patternAmbientModules && file.patternAmbientModules.length) {
58877 patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
58878 }
58879 if (file.moduleAugmentations.length) {
58880 (augmentations || (augmentations = [])).push(file.moduleAugmentations);
58881 }
58882 if (file.symbol && file.symbol.globalExports) {
58883 // Merge in UMD exports with first-in-wins semantics (see #9771)
58884 var source = file.symbol.globalExports;
58885 source.forEach(function (sourceSymbol, id) {
58886 if (!globals.has(id)) {
58887 globals.set(id, sourceSymbol);
58888 }
58889 });
58890 }
58891 }
58892 // We do global augmentations separately from module augmentations (and before creating global types) because they
58893 // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
58894 // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
58895 // checking for an export or property on the module (if export=) which, in turn, can fall back to the
58896 // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
58897 // did module augmentations prior to finalizing the global types.
58898 if (augmentations) {
58899 // merge _global_ module augmentations.
58900 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
58901 for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) {
58902 var list = augmentations_1[_d];
58903 for (var _e = 0, list_1 = list; _e < list_1.length; _e++) {
58904 var augmentation = list_1[_e];
58905 if (!ts.isGlobalScopeAugmentation(augmentation.parent))
58906 continue;
58907 mergeModuleAugmentation(augmentation);
58908 }
58909 }
58910 }
58911 // Setup global builtins
58912 addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
58913 getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
58914 getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
58915 getSymbolLinks(unknownSymbol).type = errorType;
58916 // Initialize special types
58917 globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
58918 globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
58919 globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
58920 globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
58921 globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
58922 globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
58923 globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
58924 globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
58925 globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
58926 anyArrayType = createArrayType(anyType);
58927 autoArrayType = createArrayType(autoType);
58928 if (autoArrayType === emptyObjectType) {
58929 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
58930 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
58931 }
58932 globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
58933 anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
58934 globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
58935 if (augmentations) {
58936 // merge _nonglobal_ module augmentations.
58937 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
58938 for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) {
58939 var list = augmentations_2[_f];
58940 for (var _g = 0, list_2 = list; _g < list_2.length; _g++) {
58941 var augmentation = list_2[_g];
58942 if (ts.isGlobalScopeAugmentation(augmentation.parent))
58943 continue;
58944 mergeModuleAugmentation(augmentation);
58945 }
58946 }
58947 }
58948 amalgamatedDuplicates.forEach(function (_a) {
58949 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
58950 // If not many things conflict, issue individual errors
58951 if (conflictingSymbols.size < 8) {
58952 conflictingSymbols.forEach(function (_a, symbolName) {
58953 var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
58954 var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
58955 for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
58956 var node = firstFileLocations_1[_i];
58957 addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
58958 }
58959 for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
58960 var node = secondFileLocations_1[_b];
58961 addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
58962 }
58963 });
58964 }
58965 else {
58966 // Otherwise issue top-level error since the files appear very identical in terms of what they contain
58967 var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
58968 diagnostics.add(ts.addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file)));
58969 diagnostics.add(ts.addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file)));
58970 }
58971 });
58972 amalgamatedDuplicates = undefined;
58973 }
58974 function checkExternalEmitHelpers(location, helpers) {
58975 if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
58976 var sourceFile = ts.getSourceFileOfNode(location);
58977 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 4194304 /* Ambient */)) {
58978 var helpersModule = resolveHelpersModule(sourceFile, location);
58979 if (helpersModule !== unknownSymbol) {
58980 var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
58981 for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) {
58982 if (uncheckedHelpers & helper) {
58983 var name = getHelperName(helper);
58984 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */);
58985 if (!symbol) {
58986 error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name);
58987 }
58988 }
58989 }
58990 }
58991 requestedExternalEmitHelpers |= helpers;
58992 }
58993 }
58994 }
58995 function getHelperName(helper) {
58996 switch (helper) {
58997 case 1 /* Extends */: return "__extends";
58998 case 2 /* Assign */: return "__assign";
58999 case 4 /* Rest */: return "__rest";
59000 case 8 /* Decorate */: return "__decorate";
59001 case 16 /* Metadata */: return "__metadata";
59002 case 32 /* Param */: return "__param";
59003 case 64 /* Awaiter */: return "__awaiter";
59004 case 128 /* Generator */: return "__generator";
59005 case 256 /* Values */: return "__values";
59006 case 512 /* Read */: return "__read";
59007 case 1024 /* Spread */: return "__spread";
59008 case 2048 /* Await */: return "__await";
59009 case 4096 /* AsyncGenerator */: return "__asyncGenerator";
59010 case 8192 /* AsyncDelegator */: return "__asyncDelegator";
59011 case 16384 /* AsyncValues */: return "__asyncValues";
59012 case 32768 /* ExportStar */: return "__exportStar";
59013 case 65536 /* MakeTemplateObject */: return "__makeTemplateObject";
59014 default: return ts.Debug.fail("Unrecognized helper");
59015 }
59016 }
59017 function resolveHelpersModule(node, errorNode) {
59018 if (!externalHelpersModule) {
59019 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
59020 }
59021 return externalHelpersModule;
59022 }
59023 // GRAMMAR CHECKING
59024 function checkGrammarDecoratorsAndModifiers(node) {
59025 return checkGrammarDecorators(node) || checkGrammarModifiers(node);
59026 }
59027 function checkGrammarDecorators(node) {
59028 if (!node.decorators) {
59029 return false;
59030 }
59031 if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
59032 if (node.kind === 156 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
59033 return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
59034 }
59035 else {
59036 return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
59037 }
59038 }
59039 else if (node.kind === 158 /* GetAccessor */ || node.kind === 159 /* SetAccessor */) {
59040 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
59041 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
59042 return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
59043 }
59044 }
59045 return false;
59046 }
59047 function checkGrammarModifiers(node) {
59048 var quickResult = reportObviousModifierErrors(node);
59049 if (quickResult !== undefined) {
59050 return quickResult;
59051 }
59052 var lastStatic, lastDeclare, lastAsync, lastReadonly;
59053 var flags = 0 /* None */;
59054 for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
59055 var modifier = _a[_i];
59056 if (modifier.kind !== 133 /* ReadonlyKeyword */) {
59057 if (node.kind === 153 /* PropertySignature */ || node.kind === 155 /* MethodSignature */) {
59058 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
59059 }
59060 if (node.kind === 162 /* IndexSignature */) {
59061 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
59062 }
59063 }
59064 switch (modifier.kind) {
59065 case 77 /* ConstKeyword */:
59066 if (node.kind !== 243 /* EnumDeclaration */) {
59067 return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(77 /* ConstKeyword */));
59068 }
59069 break;
59070 case 115 /* PublicKeyword */:
59071 case 114 /* ProtectedKeyword */:
59072 case 113 /* PrivateKeyword */:
59073 var text = visibilityToString(ts.modifierToFlag(modifier.kind));
59074 if (flags & 28 /* AccessibilityModifier */) {
59075 return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
59076 }
59077 else if (flags & 32 /* Static */) {
59078 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
59079 }
59080 else if (flags & 64 /* Readonly */) {
59081 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
59082 }
59083 else if (flags & 256 /* Async */) {
59084 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
59085 }
59086 else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
59087 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
59088 }
59089 else if (flags & 128 /* Abstract */) {
59090 if (modifier.kind === 113 /* PrivateKeyword */) {
59091 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
59092 }
59093 else {
59094 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
59095 }
59096 }
59097 flags |= ts.modifierToFlag(modifier.kind);
59098 break;
59099 case 116 /* StaticKeyword */:
59100 if (flags & 32 /* Static */) {
59101 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
59102 }
59103 else if (flags & 64 /* Readonly */) {
59104 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
59105 }
59106 else if (flags & 256 /* Async */) {
59107 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
59108 }
59109 else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
59110 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
59111 }
59112 else if (node.kind === 151 /* Parameter */) {
59113 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
59114 }
59115 else if (flags & 128 /* Abstract */) {
59116 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
59117 }
59118 flags |= 32 /* Static */;
59119 lastStatic = modifier;
59120 break;
59121 case 133 /* ReadonlyKeyword */:
59122 if (flags & 64 /* Readonly */) {
59123 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
59124 }
59125 else if (node.kind !== 154 /* PropertyDeclaration */ && node.kind !== 153 /* PropertySignature */ && node.kind !== 162 /* IndexSignature */ && node.kind !== 151 /* Parameter */) {
59126 // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
59127 return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
59128 }
59129 flags |= 64 /* Readonly */;
59130 lastReadonly = modifier;
59131 break;
59132 case 85 /* ExportKeyword */:
59133 if (flags & 1 /* Export */) {
59134 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
59135 }
59136 else if (flags & 2 /* Ambient */) {
59137 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
59138 }
59139 else if (flags & 128 /* Abstract */) {
59140 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
59141 }
59142 else if (flags & 256 /* Async */) {
59143 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
59144 }
59145 else if (node.parent.kind === 240 /* ClassDeclaration */) {
59146 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
59147 }
59148 else if (node.kind === 151 /* Parameter */) {
59149 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
59150 }
59151 flags |= 1 /* Export */;
59152 break;
59153 case 80 /* DefaultKeyword */:
59154 var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
59155 if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
59156 return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
59157 }
59158 flags |= 512 /* Default */;
59159 break;
59160 case 125 /* DeclareKeyword */:
59161 if (flags & 2 /* Ambient */) {
59162 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
59163 }
59164 else if (flags & 256 /* Async */) {
59165 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
59166 }
59167 else if (node.parent.kind === 240 /* ClassDeclaration */) {
59168 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
59169 }
59170 else if (node.kind === 151 /* Parameter */) {
59171 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
59172 }
59173 else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 245 /* ModuleBlock */) {
59174 return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
59175 }
59176 flags |= 2 /* Ambient */;
59177 lastDeclare = modifier;
59178 break;
59179 case 118 /* AbstractKeyword */:
59180 if (flags & 128 /* Abstract */) {
59181 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
59182 }
59183 if (node.kind !== 240 /* ClassDeclaration */) {
59184 if (node.kind !== 156 /* MethodDeclaration */ &&
59185 node.kind !== 154 /* PropertyDeclaration */ &&
59186 node.kind !== 158 /* GetAccessor */ &&
59187 node.kind !== 159 /* SetAccessor */) {
59188 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
59189 }
59190 if (!(node.parent.kind === 240 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) {
59191 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
59192 }
59193 if (flags & 32 /* Static */) {
59194 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
59195 }
59196 if (flags & 8 /* Private */) {
59197 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
59198 }
59199 }
59200 flags |= 128 /* Abstract */;
59201 break;
59202 case 121 /* AsyncKeyword */:
59203 if (flags & 256 /* Async */) {
59204 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
59205 }
59206 else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) {
59207 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
59208 }
59209 else if (node.kind === 151 /* Parameter */) {
59210 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
59211 }
59212 flags |= 256 /* Async */;
59213 lastAsync = modifier;
59214 break;
59215 }
59216 }
59217 if (node.kind === 157 /* Constructor */) {
59218 if (flags & 32 /* Static */) {
59219 return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
59220 }
59221 if (flags & 128 /* Abstract */) {
59222 return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
59223 }
59224 else if (flags & 256 /* Async */) {
59225 return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
59226 }
59227 else if (flags & 64 /* Readonly */) {
59228 return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
59229 }
59230 return false;
59231 }
59232 else if ((node.kind === 249 /* ImportDeclaration */ || node.kind === 248 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
59233 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
59234 }
59235 else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
59236 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
59237 }
59238 else if (node.kind === 151 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
59239 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
59240 }
59241 if (flags & 256 /* Async */) {
59242 return checkGrammarAsyncModifier(node, lastAsync);
59243 }
59244 return false;
59245 }
59246 /**
59247 * true | false: Early return this value from checkGrammarModifiers.
59248 * undefined: Need to do full checking on the modifiers.
59249 */
59250 function reportObviousModifierErrors(node) {
59251 return !node.modifiers
59252 ? false
59253 : shouldReportBadModifier(node)
59254 ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
59255 : undefined;
59256 }
59257 function shouldReportBadModifier(node) {
59258 switch (node.kind) {
59259 case 158 /* GetAccessor */:
59260 case 159 /* SetAccessor */:
59261 case 157 /* Constructor */:
59262 case 154 /* PropertyDeclaration */:
59263 case 153 /* PropertySignature */:
59264 case 156 /* MethodDeclaration */:
59265 case 155 /* MethodSignature */:
59266 case 162 /* IndexSignature */:
59267 case 244 /* ModuleDeclaration */:
59268 case 249 /* ImportDeclaration */:
59269 case 248 /* ImportEqualsDeclaration */:
59270 case 255 /* ExportDeclaration */:
59271 case 254 /* ExportAssignment */:
59272 case 196 /* FunctionExpression */:
59273 case 197 /* ArrowFunction */:
59274 case 151 /* Parameter */:
59275 return false;
59276 default:
59277 if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
59278 return false;
59279 }
59280 switch (node.kind) {
59281 case 239 /* FunctionDeclaration */:
59282 return nodeHasAnyModifiersExcept(node, 121 /* AsyncKeyword */);
59283 case 240 /* ClassDeclaration */:
59284 return nodeHasAnyModifiersExcept(node, 118 /* AbstractKeyword */);
59285 case 241 /* InterfaceDeclaration */:
59286 case 219 /* VariableStatement */:
59287 case 242 /* TypeAliasDeclaration */:
59288 return true;
59289 case 243 /* EnumDeclaration */:
59290 return nodeHasAnyModifiersExcept(node, 77 /* ConstKeyword */);
59291 default:
59292 ts.Debug.fail();
59293 return false;
59294 }
59295 }
59296 }
59297 function nodeHasAnyModifiersExcept(node, allowedModifier) {
59298 return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
59299 }
59300 function checkGrammarAsyncModifier(node, asyncModifier) {
59301 switch (node.kind) {
59302 case 156 /* MethodDeclaration */:
59303 case 239 /* FunctionDeclaration */:
59304 case 196 /* FunctionExpression */:
59305 case 197 /* ArrowFunction */:
59306 return false;
59307 }
59308 return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
59309 }
59310 function checkGrammarForDisallowedTrailingComma(list, diag) {
59311 if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
59312 if (list && list.hasTrailingComma) {
59313 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
59314 }
59315 return false;
59316 }
59317 function checkGrammarTypeParameterList(typeParameters, file) {
59318 if (typeParameters && typeParameters.length === 0) {
59319 var start = typeParameters.pos - "<".length;
59320 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
59321 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
59322 }
59323 return false;
59324 }
59325 function checkGrammarParameterList(parameters) {
59326 var seenOptionalParameter = false;
59327 var parameterCount = parameters.length;
59328 for (var i = 0; i < parameterCount; i++) {
59329 var parameter = parameters[i];
59330 if (parameter.dotDotDotToken) {
59331 if (i !== (parameterCount - 1)) {
59332 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
59333 }
59334 if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
59335 checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
59336 }
59337 if (parameter.questionToken) {
59338 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
59339 }
59340 if (parameter.initializer) {
59341 return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
59342 }
59343 }
59344 else if (parameter.questionToken) {
59345 seenOptionalParameter = true;
59346 if (parameter.initializer) {
59347 return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
59348 }
59349 }
59350 else if (seenOptionalParameter && !parameter.initializer) {
59351 return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
59352 }
59353 }
59354 }
59355 function getNonSimpleParameters(parameters) {
59356 return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
59357 }
59358 function checkGrammarForUseStrictSimpleParameterList(node) {
59359 if (languageVersion >= 3 /* ES2016 */) {
59360 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
59361 if (useStrictDirective_1) {
59362 var nonSimpleParameters = getNonSimpleParameters(node.parameters);
59363 if (ts.length(nonSimpleParameters)) {
59364 ts.forEach(nonSimpleParameters, function (parameter) {
59365 ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
59366 });
59367 var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
59368 ts.addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
59369 return true;
59370 }
59371 }
59372 }
59373 return false;
59374 }
59375 function checkGrammarFunctionLikeDeclaration(node) {
59376 // Prevent cascading error by short-circuit
59377 var file = ts.getSourceFileOfNode(node);
59378 return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
59379 checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) ||
59380 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
59381 }
59382 function checkGrammarClassLikeDeclaration(node) {
59383 var file = ts.getSourceFileOfNode(node);
59384 return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
59385 }
59386 function checkGrammarArrowFunction(node, file) {
59387 if (!ts.isArrowFunction(node)) {
59388 return false;
59389 }
59390 var equalsGreaterThanToken = node.equalsGreaterThanToken;
59391 var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
59392 var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
59393 return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
59394 }
59395 function checkGrammarIndexSignatureParameters(node) {
59396 var parameter = node.parameters[0];
59397 if (node.parameters.length !== 1) {
59398 if (parameter) {
59399 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
59400 }
59401 else {
59402 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
59403 }
59404 }
59405 if (parameter.dotDotDotToken) {
59406 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
59407 }
59408 if (ts.hasModifiers(parameter)) {
59409 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
59410 }
59411 if (parameter.questionToken) {
59412 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
59413 }
59414 if (parameter.initializer) {
59415 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
59416 }
59417 if (!parameter.type) {
59418 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
59419 }
59420 if (parameter.type.kind !== 138 /* StringKeyword */ && parameter.type.kind !== 135 /* NumberKeyword */) {
59421 var type = getTypeFromTypeNode(parameter.type);
59422 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
59423 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type)));
59424 }
59425 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) {
59426 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
59427 }
59428 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number);
59429 }
59430 if (!node.type) {
59431 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
59432 }
59433 return false;
59434 }
59435 function checkGrammarIndexSignature(node) {
59436 // Prevent cascading error by short-circuit
59437 return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
59438 }
59439 function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
59440 if (typeArguments && typeArguments.length === 0) {
59441 var sourceFile = ts.getSourceFileOfNode(node);
59442 var start = typeArguments.pos - "<".length;
59443 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
59444 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
59445 }
59446 return false;
59447 }
59448 function checkGrammarTypeArguments(node, typeArguments) {
59449 return checkGrammarForDisallowedTrailingComma(typeArguments) ||
59450 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
59451 }
59452 function checkGrammarForOmittedArgument(args) {
59453 if (args) {
59454 for (var _i = 0, args_5 = args; _i < args_5.length; _i++) {
59455 var arg = args_5[_i];
59456 if (arg.kind === 210 /* OmittedExpression */) {
59457 return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
59458 }
59459 }
59460 }
59461 return false;
59462 }
59463 function checkGrammarArguments(args) {
59464 return checkGrammarForOmittedArgument(args);
59465 }
59466 function checkGrammarHeritageClause(node) {
59467 var types = node.types;
59468 if (checkGrammarForDisallowedTrailingComma(types)) {
59469 return true;
59470 }
59471 if (types && types.length === 0) {
59472 var listType = ts.tokenToString(node.token);
59473 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
59474 }
59475 return ts.some(types, checkGrammarExpressionWithTypeArguments);
59476 }
59477 function checkGrammarExpressionWithTypeArguments(node) {
59478 return checkGrammarTypeArguments(node, node.typeArguments);
59479 }
59480 function checkGrammarClassDeclarationHeritageClauses(node) {
59481 var seenExtendsClause = false;
59482 var seenImplementsClause = false;
59483 if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
59484 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
59485 var heritageClause = _a[_i];
59486 if (heritageClause.token === 86 /* ExtendsKeyword */) {
59487 if (seenExtendsClause) {
59488 return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
59489 }
59490 if (seenImplementsClause) {
59491 return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
59492 }
59493 if (heritageClause.types.length > 1) {
59494 return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
59495 }
59496 seenExtendsClause = true;
59497 }
59498 else {
59499 ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */);
59500 if (seenImplementsClause) {
59501 return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
59502 }
59503 seenImplementsClause = true;
59504 }
59505 // Grammar checking heritageClause inside class declaration
59506 checkGrammarHeritageClause(heritageClause);
59507 }
59508 }
59509 }
59510 function checkGrammarInterfaceDeclaration(node) {
59511 var seenExtendsClause = false;
59512 if (node.heritageClauses) {
59513 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
59514 var heritageClause = _a[_i];
59515 if (heritageClause.token === 86 /* ExtendsKeyword */) {
59516 if (seenExtendsClause) {
59517 return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
59518 }
59519 seenExtendsClause = true;
59520 }
59521 else {
59522 ts.Debug.assert(heritageClause.token === 109 /* ImplementsKeyword */);
59523 return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
59524 }
59525 // Grammar checking heritageClause inside class declaration
59526 checkGrammarHeritageClause(heritageClause);
59527 }
59528 }
59529 return false;
59530 }
59531 function checkGrammarComputedPropertyName(node) {
59532 // If node is not a computedPropertyName, just skip the grammar checking
59533 if (node.kind !== 149 /* ComputedPropertyName */) {
59534 return false;
59535 }
59536 var computedPropertyName = node;
59537 if (computedPropertyName.expression.kind === 204 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
59538 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
59539 }
59540 return false;
59541 }
59542 function checkGrammarForGenerator(node) {
59543 if (node.asteriskToken) {
59544 ts.Debug.assert(node.kind === 239 /* FunctionDeclaration */ ||
59545 node.kind === 196 /* FunctionExpression */ ||
59546 node.kind === 156 /* MethodDeclaration */);
59547 if (node.flags & 4194304 /* Ambient */) {
59548 return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
59549 }
59550 if (!node.body) {
59551 return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
59552 }
59553 }
59554 }
59555 function checkGrammarForInvalidQuestionMark(questionToken, message) {
59556 return !!questionToken && grammarErrorOnNode(questionToken, message);
59557 }
59558 function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
59559 return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
59560 }
59561 function checkGrammarObjectLiteralExpression(node, inDestructuring) {
59562 var Flags;
59563 (function (Flags) {
59564 Flags[Flags["Property"] = 1] = "Property";
59565 Flags[Flags["GetAccessor"] = 2] = "GetAccessor";
59566 Flags[Flags["SetAccessor"] = 4] = "SetAccessor";
59567 Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor";
59568 })(Flags || (Flags = {}));
59569 var seen = ts.createUnderscoreEscapedMap();
59570 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
59571 var prop = _a[_i];
59572 if (prop.kind === 277 /* SpreadAssignment */) {
59573 continue;
59574 }
59575 var name = prop.name;
59576 if (name.kind === 149 /* ComputedPropertyName */) {
59577 // If the name is not a ComputedPropertyName, the grammar checking will skip it
59578 checkGrammarComputedPropertyName(name);
59579 }
59580 if (prop.kind === 276 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
59581 // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
59582 // outside of destructuring it is a syntax error
59583 return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
59584 }
59585 // Modifiers are never allowed on properties except for 'async' on a method declaration
59586 if (prop.modifiers) {
59587 for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
59588 var mod = _c[_b];
59589 if (mod.kind !== 121 /* AsyncKeyword */ || prop.kind !== 156 /* MethodDeclaration */) {
59590 grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
59591 }
59592 }
59593 }
59594 // ECMA-262 11.1.5 Object Initializer
59595 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
59596 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
59597 // IsDataDescriptor(propId.descriptor) is true.
59598 // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
59599 // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
59600 // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
59601 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
59602 var currentKind = void 0;
59603 switch (prop.kind) {
59604 case 276 /* ShorthandPropertyAssignment */:
59605 checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
59606 /* tslint:disable:no-switch-case-fall-through */
59607 case 275 /* PropertyAssignment */:
59608 // Grammar checking for computedPropertyName and shorthandPropertyAssignment
59609 checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
59610 if (name.kind === 8 /* NumericLiteral */) {
59611 checkGrammarNumericLiteral(name);
59612 }
59613 // falls through
59614 case 156 /* MethodDeclaration */:
59615 currentKind = 1 /* Property */;
59616 break;
59617 case 158 /* GetAccessor */:
59618 currentKind = 2 /* GetAccessor */;
59619 break;
59620 case 159 /* SetAccessor */:
59621 currentKind = 4 /* SetAccessor */;
59622 break;
59623 default:
59624 throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
59625 }
59626 var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
59627 if (effectiveName === undefined) {
59628 continue;
59629 }
59630 var existingKind = seen.get(effectiveName);
59631 if (!existingKind) {
59632 seen.set(effectiveName, currentKind);
59633 }
59634 else {
59635 if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
59636 grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
59637 }
59638 else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) {
59639 if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) {
59640 seen.set(effectiveName, currentKind | existingKind);
59641 }
59642 else {
59643 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
59644 }
59645 }
59646 else {
59647 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
59648 }
59649 }
59650 }
59651 }
59652 function checkGrammarJsxElement(node) {
59653 checkGrammarTypeArguments(node, node.typeArguments);
59654 var seen = ts.createUnderscoreEscapedMap();
59655 for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
59656 var attr = _a[_i];
59657 if (attr.kind === 269 /* JsxSpreadAttribute */) {
59658 continue;
59659 }
59660 var name = attr.name, initializer = attr.initializer;
59661 if (!seen.get(name.escapedText)) {
59662 seen.set(name.escapedText, true);
59663 }
59664 else {
59665 return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
59666 }
59667 if (initializer && initializer.kind === 270 /* JsxExpression */ && !initializer.expression) {
59668 return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
59669 }
59670 }
59671 }
59672 function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
59673 if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
59674 return true;
59675 }
59676 if (forInOrOfStatement.kind === 227 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
59677 if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) {
59678 return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
59679 }
59680 }
59681 if (forInOrOfStatement.initializer.kind === 238 /* VariableDeclarationList */) {
59682 var variableList = forInOrOfStatement.initializer;
59683 if (!checkGrammarVariableDeclarationList(variableList)) {
59684 var declarations = variableList.declarations;
59685 // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
59686 // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
59687 // For example:
59688 // var let = 10;
59689 // for (let of [1,2,3]) {} // this is invalid ES6 syntax
59690 // for (let in [1,2,3]) {} // this is invalid ES6 syntax
59691 // We will then want to skip on grammar checking on variableList declaration
59692 if (!declarations.length) {
59693 return false;
59694 }
59695 if (declarations.length > 1) {
59696 var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */
59697 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
59698 : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
59699 return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
59700 }
59701 var firstDeclaration = declarations[0];
59702 if (firstDeclaration.initializer) {
59703 var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */
59704 ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
59705 : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
59706 return grammarErrorOnNode(firstDeclaration.name, diagnostic);
59707 }
59708 if (firstDeclaration.type) {
59709 var diagnostic = forInOrOfStatement.kind === 226 /* ForInStatement */
59710 ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
59711 : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
59712 return grammarErrorOnNode(firstDeclaration, diagnostic);
59713 }
59714 }
59715 }
59716 return false;
59717 }
59718 function checkGrammarAccessor(accessor) {
59719 var kind = accessor.kind;
59720 if (languageVersion < 1 /* ES5 */) {
59721 return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
59722 }
59723 else if (accessor.flags & 4194304 /* Ambient */) {
59724 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context);
59725 }
59726 else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) {
59727 return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
59728 }
59729 else if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) {
59730 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
59731 }
59732 else if (accessor.typeParameters) {
59733 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
59734 }
59735 else if (!doesAccessorHaveCorrectParameterCount(accessor)) {
59736 return grammarErrorOnNode(accessor.name, kind === 158 /* GetAccessor */ ?
59737 ts.Diagnostics.A_get_accessor_cannot_have_parameters :
59738 ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
59739 }
59740 else if (kind === 159 /* SetAccessor */) {
59741 if (accessor.type) {
59742 return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
59743 }
59744 else {
59745 var parameter = accessor.parameters[0];
59746 if (parameter.dotDotDotToken) {
59747 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
59748 }
59749 else if (parameter.questionToken) {
59750 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
59751 }
59752 else if (parameter.initializer) {
59753 return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
59754 }
59755 }
59756 }
59757 return false;
59758 }
59759 /** Does the accessor have the right number of parameters?
59760 * A get accessor has no parameters or a single `this` parameter.
59761 * A set accessor has one parameter or a `this` parameter and one more parameter.
59762 */
59763 function doesAccessorHaveCorrectParameterCount(accessor) {
59764 return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 0 : 1);
59765 }
59766 function getAccessorThisParameter(accessor) {
59767 if (accessor.parameters.length === (accessor.kind === 158 /* GetAccessor */ ? 1 : 2)) {
59768 return ts.getThisParameter(accessor);
59769 }
59770 }
59771 function checkGrammarTypeOperatorNode(node) {
59772 if (node.operator === 142 /* UniqueKeyword */) {
59773 if (node.type.kind !== 139 /* SymbolKeyword */) {
59774 return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(139 /* SymbolKeyword */));
59775 }
59776 var parent = ts.walkUpParenthesizedTypes(node.parent);
59777 switch (parent.kind) {
59778 case 237 /* VariableDeclaration */:
59779 var decl = parent;
59780 if (decl.name.kind !== 72 /* Identifier */) {
59781 return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
59782 }
59783 if (!ts.isVariableDeclarationInVariableStatement(decl)) {
59784 return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
59785 }
59786 if (!(decl.parent.flags & 2 /* Const */)) {
59787 return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
59788 }
59789 break;
59790 case 154 /* PropertyDeclaration */:
59791 if (!ts.hasModifier(parent, 32 /* Static */) ||
59792 !ts.hasModifier(parent, 64 /* Readonly */)) {
59793 return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
59794 }
59795 break;
59796 case 153 /* PropertySignature */:
59797 if (!ts.hasModifier(parent, 64 /* Readonly */)) {
59798 return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
59799 }
59800 break;
59801 default:
59802 return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
59803 }
59804 }
59805 else if (node.operator === 133 /* ReadonlyKeyword */) {
59806 if (node.type.kind !== 169 /* ArrayType */ && node.type.kind !== 170 /* TupleType */) {
59807 return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(139 /* SymbolKeyword */));
59808 }
59809 }
59810 }
59811 function checkGrammarForInvalidDynamicName(node, message) {
59812 if (isNonBindableDynamicName(node)) {
59813 return grammarErrorOnNode(node, message);
59814 }
59815 }
59816 function checkGrammarMethod(node) {
59817 if (checkGrammarFunctionLikeDeclaration(node)) {
59818 return true;
59819 }
59820 if (node.kind === 156 /* MethodDeclaration */) {
59821 if (node.parent.kind === 188 /* ObjectLiteralExpression */) {
59822 // We only disallow modifier on a method declaration if it is a property of object-literal-expression
59823 if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 121 /* AsyncKeyword */)) {
59824 return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
59825 }
59826 else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
59827 return true;
59828 }
59829 else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
59830 return true;
59831 }
59832 else if (node.body === undefined) {
59833 return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
59834 }
59835 }
59836 if (checkGrammarForGenerator(node)) {
59837 return true;
59838 }
59839 }
59840 if (ts.isClassLike(node.parent)) {
59841 // Technically, computed properties in ambient contexts is disallowed
59842 // for property declarations and accessors too, not just methods.
59843 // However, property declarations disallow computed names in general,
59844 // and accessors are not allowed in ambient contexts in general,
59845 // so this error only really matters for methods.
59846 if (node.flags & 4194304 /* Ambient */) {
59847 return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
59848 }
59849 else if (node.kind === 156 /* MethodDeclaration */ && !node.body) {
59850 return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
59851 }
59852 }
59853 else if (node.parent.kind === 241 /* InterfaceDeclaration */) {
59854 return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
59855 }
59856 else if (node.parent.kind === 168 /* TypeLiteral */) {
59857 return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
59858 }
59859 }
59860 function checkGrammarBreakOrContinueStatement(node) {
59861 var current = node;
59862 while (current) {
59863 if (ts.isFunctionLike(current)) {
59864 return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
59865 }
59866 switch (current.kind) {
59867 case 233 /* LabeledStatement */:
59868 if (node.label && current.label.escapedText === node.label.escapedText) {
59869 // found matching label - verify that label usage is correct
59870 // continue can only target labels that are on iteration statements
59871 var isMisplacedContinueLabel = node.kind === 228 /* ContinueStatement */
59872 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
59873 if (isMisplacedContinueLabel) {
59874 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
59875 }
59876 return false;
59877 }
59878 break;
59879 case 232 /* SwitchStatement */:
59880 if (node.kind === 229 /* BreakStatement */ && !node.label) {
59881 // unlabeled break within switch statement - ok
59882 return false;
59883 }
59884 break;
59885 default:
59886 if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
59887 // unlabeled break or continue within iteration statement - ok
59888 return false;
59889 }
59890 break;
59891 }
59892 current = current.parent;
59893 }
59894 if (node.label) {
59895 var message = node.kind === 229 /* BreakStatement */
59896 ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
59897 : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
59898 return grammarErrorOnNode(node, message);
59899 }
59900 else {
59901 var message = node.kind === 229 /* BreakStatement */
59902 ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
59903 : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
59904 return grammarErrorOnNode(node, message);
59905 }
59906 }
59907 function checkGrammarBindingElement(node) {
59908 if (node.dotDotDotToken) {
59909 var elements = node.parent.elements;
59910 if (node !== ts.last(elements)) {
59911 return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
59912 }
59913 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
59914 if (node.propertyName) {
59915 return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
59916 }
59917 if (node.initializer) {
59918 // Error on equals token which immediately precedes the initializer
59919 return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
59920 }
59921 }
59922 }
59923 function isStringOrNumberLiteralExpression(expr) {
59924 return expr.kind === 10 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ ||
59925 expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ &&
59926 expr.operand.kind === 8 /* NumericLiteral */;
59927 }
59928 function isBigIntLiteralExpression(expr) {
59929 return expr.kind === 9 /* BigIntLiteral */ ||
59930 expr.kind === 202 /* PrefixUnaryExpression */ && expr.operator === 39 /* MinusToken */ &&
59931 expr.operand.kind === 9 /* BigIntLiteral */;
59932 }
59933 function isSimpleLiteralEnumReference(expr) {
59934 if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
59935 ts.isEntityNameExpression(expr.expression))
59936 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
59937 }
59938 function checkAmbientInitializer(node) {
59939 var initializer = node.initializer;
59940 if (initializer) {
59941 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
59942 isSimpleLiteralEnumReference(initializer) ||
59943 initializer.kind === 102 /* TrueKeyword */ || initializer.kind === 87 /* FalseKeyword */ ||
59944 isBigIntLiteralExpression(initializer));
59945 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
59946 if (isConstOrReadonly && !node.type) {
59947 if (isInvalidInitializer) {
59948 return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
59949 }
59950 }
59951 else {
59952 return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
59953 }
59954 if (!isConstOrReadonly || isInvalidInitializer) {
59955 return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
59956 }
59957 }
59958 }
59959 function checkGrammarVariableDeclaration(node) {
59960 if (node.parent.parent.kind !== 226 /* ForInStatement */ && node.parent.parent.kind !== 227 /* ForOfStatement */) {
59961 if (node.flags & 4194304 /* Ambient */) {
59962 checkAmbientInitializer(node);
59963 }
59964 else if (!node.initializer) {
59965 if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
59966 return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
59967 }
59968 if (ts.isVarConst(node)) {
59969 return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
59970 }
59971 }
59972 }
59973 if (node.exclamationToken && (node.parent.parent.kind !== 219 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) {
59974 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
59975 }
59976 if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit &&
59977 !(node.parent.parent.flags & 4194304 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) {
59978 checkESModuleMarker(node.name);
59979 }
59980 var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
59981 // 1. LexicalDeclaration : LetOrConst BindingList ;
59982 // It is a Syntax Error if the BoundNames of BindingList contains "let".
59983 // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
59984 // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
59985 // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
59986 // and its Identifier is eval or arguments
59987 return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
59988 }
59989 function checkESModuleMarker(name) {
59990 if (name.kind === 72 /* Identifier */) {
59991 if (ts.idText(name) === "__esModule") {
59992 return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
59993 }
59994 }
59995 else {
59996 var elements = name.elements;
59997 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
59998 var element = elements_1[_i];
59999 if (!ts.isOmittedExpression(element)) {
60000 return checkESModuleMarker(element.name);
60001 }
60002 }
60003 }
60004 return false;
60005 }
60006 function checkGrammarNameInLetOrConstDeclarations(name) {
60007 if (name.kind === 72 /* Identifier */) {
60008 if (name.originalKeywordKind === 111 /* LetKeyword */) {
60009 return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
60010 }
60011 }
60012 else {
60013 var elements = name.elements;
60014 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
60015 var element = elements_2[_i];
60016 if (!ts.isOmittedExpression(element)) {
60017 checkGrammarNameInLetOrConstDeclarations(element.name);
60018 }
60019 }
60020 }
60021 return false;
60022 }
60023 function checkGrammarVariableDeclarationList(declarationList) {
60024 var declarations = declarationList.declarations;
60025 if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
60026 return true;
60027 }
60028 if (!declarationList.declarations.length) {
60029 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
60030 }
60031 return false;
60032 }
60033 function allowLetAndConstDeclarations(parent) {
60034 switch (parent.kind) {
60035 case 222 /* IfStatement */:
60036 case 223 /* DoStatement */:
60037 case 224 /* WhileStatement */:
60038 case 231 /* WithStatement */:
60039 case 225 /* ForStatement */:
60040 case 226 /* ForInStatement */:
60041 case 227 /* ForOfStatement */:
60042 return false;
60043 case 233 /* LabeledStatement */:
60044 return allowLetAndConstDeclarations(parent.parent);
60045 }
60046 return true;
60047 }
60048 function checkGrammarForDisallowedLetOrConstStatement(node) {
60049 if (!allowLetAndConstDeclarations(node.parent)) {
60050 if (ts.isLet(node.declarationList)) {
60051 return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
60052 }
60053 else if (ts.isVarConst(node.declarationList)) {
60054 return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
60055 }
60056 }
60057 }
60058 function checkGrammarMetaProperty(node) {
60059 var escapedText = node.name.escapedText;
60060 switch (node.keywordToken) {
60061 case 95 /* NewKeyword */:
60062 if (escapedText !== "target") {
60063 return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target");
60064 }
60065 break;
60066 case 92 /* ImportKeyword */:
60067 if (escapedText !== "meta") {
60068 return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta");
60069 }
60070 break;
60071 }
60072 }
60073 function hasParseDiagnostics(sourceFile) {
60074 return sourceFile.parseDiagnostics.length > 0;
60075 }
60076 function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
60077 var sourceFile = ts.getSourceFileOfNode(node);
60078 if (!hasParseDiagnostics(sourceFile)) {
60079 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60080 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
60081 return true;
60082 }
60083 return false;
60084 }
60085 function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
60086 var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
60087 if (!hasParseDiagnostics(sourceFile)) {
60088 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
60089 return true;
60090 }
60091 return false;
60092 }
60093 function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
60094 var sourceFile = ts.getSourceFileOfNode(node);
60095 if (!hasParseDiagnostics(sourceFile)) {
60096 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
60097 return true;
60098 }
60099 return false;
60100 }
60101 function checkGrammarConstructorTypeParameters(node) {
60102 var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
60103 var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
60104 if (range) {
60105 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
60106 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
60107 }
60108 }
60109 function checkGrammarConstructorTypeAnnotation(node) {
60110 var type = ts.getEffectiveReturnTypeNode(node);
60111 if (type) {
60112 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
60113 }
60114 }
60115 function checkGrammarProperty(node) {
60116 if (ts.isClassLike(node.parent)) {
60117 if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.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)) {
60118 return true;
60119 }
60120 }
60121 else if (node.parent.kind === 241 /* InterfaceDeclaration */) {
60122 if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
60123 return true;
60124 }
60125 if (node.initializer) {
60126 return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
60127 }
60128 }
60129 else if (node.parent.kind === 168 /* TypeLiteral */) {
60130 if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
60131 return true;
60132 }
60133 if (node.initializer) {
60134 return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
60135 }
60136 }
60137 if (node.flags & 4194304 /* Ambient */) {
60138 checkAmbientInitializer(node);
60139 }
60140 if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
60141 node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
60142 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
60143 }
60144 }
60145 function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
60146 // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
60147 // interfaces and imports categories:
60148 //
60149 // DeclarationElement:
60150 // ExportAssignment
60151 // export_opt InterfaceDeclaration
60152 // export_opt TypeAliasDeclaration
60153 // export_opt ImportDeclaration
60154 // export_opt ExternalImportDeclaration
60155 // export_opt AmbientDeclaration
60156 //
60157 // TODO: The spec needs to be amended to reflect this grammar.
60158 if (node.kind === 241 /* InterfaceDeclaration */ ||
60159 node.kind === 242 /* TypeAliasDeclaration */ ||
60160 node.kind === 249 /* ImportDeclaration */ ||
60161 node.kind === 248 /* ImportEqualsDeclaration */ ||
60162 node.kind === 255 /* ExportDeclaration */ ||
60163 node.kind === 254 /* ExportAssignment */ ||
60164 node.kind === 247 /* NamespaceExportDeclaration */ ||
60165 ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
60166 return false;
60167 }
60168 return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file);
60169 }
60170 function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
60171 for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
60172 var decl = _a[_i];
60173 if (ts.isDeclaration(decl) || decl.kind === 219 /* VariableStatement */) {
60174 if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
60175 return true;
60176 }
60177 }
60178 }
60179 return false;
60180 }
60181 function checkGrammarSourceFile(node) {
60182 return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
60183 }
60184 function checkGrammarStatementInAmbientContext(node) {
60185 if (node.flags & 4194304 /* Ambient */) {
60186 // An accessors is already reported about the ambient context
60187 if (ts.isAccessor(node.parent)) {
60188 return getNodeLinks(node).hasReportedStatementInAmbientContext = true;
60189 }
60190 // Find containing block which is either Block, ModuleBlock, SourceFile
60191 var links = getNodeLinks(node);
60192 if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) {
60193 return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
60194 }
60195 // We are either parented by another statement, or some sort of block.
60196 // If we're in a block, we only want to really report an error once
60197 // to prevent noisiness. So use a bit on the block to indicate if
60198 // this has already been reported, and don't report if it has.
60199 //
60200 if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
60201 var links_2 = getNodeLinks(node.parent);
60202 // Check if the containing block ever report this error
60203 if (!links_2.hasReportedStatementInAmbientContext) {
60204 return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
60205 }
60206 }
60207 else {
60208 // We must be parented by a statement. If so, there's no need
60209 // to report the error as our parent will have already done it.
60210 // Debug.assert(isStatement(node.parent));
60211 }
60212 }
60213 return false;
60214 }
60215 function checkGrammarNumericLiteral(node) {
60216 // Grammar checking
60217 if (node.numericLiteralFlags & 32 /* Octal */) {
60218 var diagnosticMessage = void 0;
60219 if (languageVersion >= 1 /* ES5 */) {
60220 diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
60221 }
60222 else if (ts.isChildOfNodeWithKind(node, 182 /* LiteralType */)) {
60223 diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
60224 }
60225 else if (ts.isChildOfNodeWithKind(node, 278 /* EnumMember */)) {
60226 diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
60227 }
60228 if (diagnosticMessage) {
60229 var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 39 /* MinusToken */;
60230 var literal = (withMinus ? "-" : "") + "0o" + node.text;
60231 return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
60232 }
60233 }
60234 return false;
60235 }
60236 function checkGrammarBigIntLiteral(node) {
60237 var literalType = ts.isLiteralTypeNode(node.parent) ||
60238 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
60239 if (!literalType) {
60240 if (languageVersion < 7 /* ESNext */) {
60241 if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) {
60242 return true;
60243 }
60244 }
60245 }
60246 return false;
60247 }
60248 function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
60249 var sourceFile = ts.getSourceFileOfNode(node);
60250 if (!hasParseDiagnostics(sourceFile)) {
60251 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60252 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
60253 return true;
60254 }
60255 return false;
60256 }
60257 function getAmbientModules() {
60258 if (!ambientModulesCache) {
60259 ambientModulesCache = [];
60260 globals.forEach(function (global, sym) {
60261 // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
60262 if (ambientModuleSymbolRegex.test(sym)) {
60263 ambientModulesCache.push(global);
60264 }
60265 });
60266 }
60267 return ambientModulesCache;
60268 }
60269 function checkGrammarImportCallExpression(node) {
60270 if (moduleKind === ts.ModuleKind.ES2015) {
60271 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext);
60272 }
60273 if (node.typeArguments) {
60274 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
60275 }
60276 var nodeArguments = node.arguments;
60277 if (nodeArguments.length !== 1) {
60278 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
60279 }
60280 checkGrammarForDisallowedTrailingComma(nodeArguments);
60281 // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
60282 // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
60283 if (ts.isSpreadElement(nodeArguments[0])) {
60284 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
60285 }
60286 return false;
60287 }
60288 }
60289 ts.createTypeChecker = createTypeChecker;
60290 /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
60291 function isDeclarationNameOrImportPropertyName(name) {
60292 switch (name.parent.kind) {
60293 case 253 /* ImportSpecifier */:
60294 case 257 /* ExportSpecifier */:
60295 return ts.isIdentifier(name);
60296 default:
60297 return ts.isDeclarationName(name);
60298 }
60299 }
60300 function isSomeImportDeclaration(decl) {
60301 switch (decl.kind) {
60302 case 250 /* ImportClause */: // For default import
60303 case 248 /* ImportEqualsDeclaration */:
60304 case 251 /* NamespaceImport */:
60305 case 253 /* ImportSpecifier */: // For rename import `x as y`
60306 return true;
60307 case 72 /* Identifier */:
60308 // For regular import, `decl` is an Identifier under the ImportSpecifier.
60309 return decl.parent.kind === 253 /* ImportSpecifier */;
60310 default:
60311 return false;
60312 }
60313 }
60314 var JsxNames;
60315 (function (JsxNames) {
60316 // tslint:disable variable-name
60317 JsxNames.JSX = "JSX";
60318 JsxNames.IntrinsicElements = "IntrinsicElements";
60319 JsxNames.ElementClass = "ElementClass";
60320 JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
60321 JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
60322 JsxNames.Element = "Element";
60323 JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
60324 JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
60325 JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
60326 // tslint:enable variable-name
60327 })(JsxNames || (JsxNames = {}));
60328})(ts || (ts = {}));
60329var ts;
60330(function (ts) {
60331 function createSynthesizedNode(kind) {
60332 var node = ts.createNode(kind, -1, -1);
60333 node.flags |= 8 /* Synthesized */;
60334 return node;
60335 }
60336 /* @internal */
60337 function updateNode(updated, original) {
60338 if (updated !== original) {
60339 setOriginalNode(updated, original);
60340 setTextRange(updated, original);
60341 ts.aggregateTransformFlags(updated);
60342 }
60343 return updated;
60344 }
60345 ts.updateNode = updateNode;
60346 /**
60347 * Make `elements` into a `NodeArray<T>`. If `elements` is `undefined`, returns an empty `NodeArray<T>`.
60348 */
60349 function createNodeArray(elements, hasTrailingComma) {
60350 if (!elements || elements === ts.emptyArray) {
60351 elements = [];
60352 }
60353 else if (ts.isNodeArray(elements)) {
60354 return elements;
60355 }
60356 var array = elements;
60357 array.pos = -1;
60358 array.end = -1;
60359 array.hasTrailingComma = hasTrailingComma;
60360 return array;
60361 }
60362 ts.createNodeArray = createNodeArray;
60363 /**
60364 * Creates a shallow, memberwise clone of a node with no source map location.
60365 */
60366 /* @internal */
60367 function getSynthesizedClone(node) {
60368 // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
60369 // the original node. We also need to exclude specific properties and only include own-
60370 // properties (to skip members already defined on the shared prototype).
60371 if (node === undefined) {
60372 return node;
60373 }
60374 var clone = createSynthesizedNode(node.kind);
60375 clone.flags |= node.flags;
60376 setOriginalNode(clone, node);
60377 for (var key in node) {
60378 if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
60379 continue;
60380 }
60381 clone[key] = node[key];
60382 }
60383 return clone;
60384 }
60385 ts.getSynthesizedClone = getSynthesizedClone;
60386 function createLiteral(value, isSingleQuote) {
60387 if (typeof value === "number") {
60388 return createNumericLiteral(value + "");
60389 }
60390 if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt
60391 return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n");
60392 }
60393 if (typeof value === "boolean") {
60394 return value ? createTrue() : createFalse();
60395 }
60396 if (ts.isString(value)) {
60397 var res = createStringLiteral(value);
60398 if (isSingleQuote)
60399 res.singleQuote = true;
60400 return res;
60401 }
60402 return createLiteralFromNode(value);
60403 }
60404 ts.createLiteral = createLiteral;
60405 function createNumericLiteral(value, numericLiteralFlags) {
60406 if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
60407 var node = createSynthesizedNode(8 /* NumericLiteral */);
60408 node.text = value;
60409 node.numericLiteralFlags = numericLiteralFlags;
60410 return node;
60411 }
60412 ts.createNumericLiteral = createNumericLiteral;
60413 function createBigIntLiteral(value) {
60414 var node = createSynthesizedNode(9 /* BigIntLiteral */);
60415 node.text = value;
60416 return node;
60417 }
60418 ts.createBigIntLiteral = createBigIntLiteral;
60419 function createStringLiteral(text) {
60420 var node = createSynthesizedNode(10 /* StringLiteral */);
60421 node.text = text;
60422 return node;
60423 }
60424 ts.createStringLiteral = createStringLiteral;
60425 function createRegularExpressionLiteral(text) {
60426 var node = createSynthesizedNode(13 /* RegularExpressionLiteral */);
60427 node.text = text;
60428 return node;
60429 }
60430 ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
60431 function createLiteralFromNode(sourceNode) {
60432 var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
60433 node.textSourceNode = sourceNode;
60434 return node;
60435 }
60436 function createIdentifier(text, typeArguments) {
60437 var node = createSynthesizedNode(72 /* Identifier */);
60438 node.escapedText = ts.escapeLeadingUnderscores(text);
60439 node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
60440 node.autoGenerateFlags = 0 /* None */;
60441 node.autoGenerateId = 0;
60442 if (typeArguments) {
60443 node.typeArguments = createNodeArray(typeArguments);
60444 }
60445 return node;
60446 }
60447 ts.createIdentifier = createIdentifier;
60448 function updateIdentifier(node, typeArguments) {
60449 return node.typeArguments !== typeArguments
60450 ? updateNode(createIdentifier(ts.idText(node), typeArguments), node)
60451 : node;
60452 }
60453 ts.updateIdentifier = updateIdentifier;
60454 var nextAutoGenerateId = 0;
60455 function createTempVariable(recordTempVariable, reservedInNestedScopes) {
60456 var name = createIdentifier("");
60457 name.autoGenerateFlags = 1 /* Auto */;
60458 name.autoGenerateId = nextAutoGenerateId;
60459 nextAutoGenerateId++;
60460 if (recordTempVariable) {
60461 recordTempVariable(name);
60462 }
60463 if (reservedInNestedScopes) {
60464 name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
60465 }
60466 return name;
60467 }
60468 ts.createTempVariable = createTempVariable;
60469 /** Create a unique temporary variable for use in a loop. */
60470 function createLoopVariable() {
60471 var name = createIdentifier("");
60472 name.autoGenerateFlags = 2 /* Loop */;
60473 name.autoGenerateId = nextAutoGenerateId;
60474 nextAutoGenerateId++;
60475 return name;
60476 }
60477 ts.createLoopVariable = createLoopVariable;
60478 /** Create a unique name based on the supplied text. */
60479 function createUniqueName(text) {
60480 var name = createIdentifier(text);
60481 name.autoGenerateFlags = 3 /* Unique */;
60482 name.autoGenerateId = nextAutoGenerateId;
60483 nextAutoGenerateId++;
60484 return name;
60485 }
60486 ts.createUniqueName = createUniqueName;
60487 function createOptimisticUniqueName(text) {
60488 var name = createIdentifier(text);
60489 name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
60490 name.autoGenerateId = nextAutoGenerateId;
60491 nextAutoGenerateId++;
60492 return name;
60493 }
60494 ts.createOptimisticUniqueName = createOptimisticUniqueName;
60495 /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
60496 function createFileLevelUniqueName(text) {
60497 var name = createOptimisticUniqueName(text);
60498 name.autoGenerateFlags |= 32 /* FileLevel */;
60499 return name;
60500 }
60501 ts.createFileLevelUniqueName = createFileLevelUniqueName;
60502 function getGeneratedNameForNode(node, flags) {
60503 var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "");
60504 name.autoGenerateFlags = 4 /* Node */ | flags;
60505 name.autoGenerateId = nextAutoGenerateId;
60506 name.original = node;
60507 nextAutoGenerateId++;
60508 return name;
60509 }
60510 ts.getGeneratedNameForNode = getGeneratedNameForNode;
60511 // Punctuation
60512 function createToken(token) {
60513 return createSynthesizedNode(token);
60514 }
60515 ts.createToken = createToken;
60516 // Reserved words
60517 function createSuper() {
60518 return createSynthesizedNode(98 /* SuperKeyword */);
60519 }
60520 ts.createSuper = createSuper;
60521 function createThis() {
60522 return createSynthesizedNode(100 /* ThisKeyword */);
60523 }
60524 ts.createThis = createThis;
60525 function createNull() {
60526 return createSynthesizedNode(96 /* NullKeyword */);
60527 }
60528 ts.createNull = createNull;
60529 function createTrue() {
60530 return createSynthesizedNode(102 /* TrueKeyword */);
60531 }
60532 ts.createTrue = createTrue;
60533 function createFalse() {
60534 return createSynthesizedNode(87 /* FalseKeyword */);
60535 }
60536 ts.createFalse = createFalse;
60537 // Modifiers
60538 function createModifier(kind) {
60539 return createToken(kind);
60540 }
60541 ts.createModifier = createModifier;
60542 function createModifiersFromModifierFlags(flags) {
60543 var result = [];
60544 if (flags & 1 /* Export */) {
60545 result.push(createModifier(85 /* ExportKeyword */));
60546 }
60547 if (flags & 2 /* Ambient */) {
60548 result.push(createModifier(125 /* DeclareKeyword */));
60549 }
60550 if (flags & 512 /* Default */) {
60551 result.push(createModifier(80 /* DefaultKeyword */));
60552 }
60553 if (flags & 2048 /* Const */) {
60554 result.push(createModifier(77 /* ConstKeyword */));
60555 }
60556 if (flags & 4 /* Public */) {
60557 result.push(createModifier(115 /* PublicKeyword */));
60558 }
60559 if (flags & 8 /* Private */) {
60560 result.push(createModifier(113 /* PrivateKeyword */));
60561 }
60562 if (flags & 16 /* Protected */) {
60563 result.push(createModifier(114 /* ProtectedKeyword */));
60564 }
60565 if (flags & 128 /* Abstract */) {
60566 result.push(createModifier(118 /* AbstractKeyword */));
60567 }
60568 if (flags & 32 /* Static */) {
60569 result.push(createModifier(116 /* StaticKeyword */));
60570 }
60571 if (flags & 64 /* Readonly */) {
60572 result.push(createModifier(133 /* ReadonlyKeyword */));
60573 }
60574 if (flags & 256 /* Async */) {
60575 result.push(createModifier(121 /* AsyncKeyword */));
60576 }
60577 return result;
60578 }
60579 ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags;
60580 // Names
60581 function createQualifiedName(left, right) {
60582 var node = createSynthesizedNode(148 /* QualifiedName */);
60583 node.left = left;
60584 node.right = asName(right);
60585 return node;
60586 }
60587 ts.createQualifiedName = createQualifiedName;
60588 function updateQualifiedName(node, left, right) {
60589 return node.left !== left
60590 || node.right !== right
60591 ? updateNode(createQualifiedName(left, right), node)
60592 : node;
60593 }
60594 ts.updateQualifiedName = updateQualifiedName;
60595 function parenthesizeForComputedName(expression) {
60596 return ts.isCommaSequence(expression)
60597 ? createParen(expression)
60598 : expression;
60599 }
60600 function createComputedPropertyName(expression) {
60601 var node = createSynthesizedNode(149 /* ComputedPropertyName */);
60602 node.expression = parenthesizeForComputedName(expression);
60603 return node;
60604 }
60605 ts.createComputedPropertyName = createComputedPropertyName;
60606 function updateComputedPropertyName(node, expression) {
60607 return node.expression !== expression
60608 ? updateNode(createComputedPropertyName(expression), node)
60609 : node;
60610 }
60611 ts.updateComputedPropertyName = updateComputedPropertyName;
60612 // Signature elements
60613 function createTypeParameterDeclaration(name, constraint, defaultType) {
60614 var node = createSynthesizedNode(150 /* TypeParameter */);
60615 node.name = asName(name);
60616 node.constraint = constraint;
60617 node.default = defaultType;
60618 return node;
60619 }
60620 ts.createTypeParameterDeclaration = createTypeParameterDeclaration;
60621 function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
60622 return node.name !== name
60623 || node.constraint !== constraint
60624 || node.default !== defaultType
60625 ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
60626 : node;
60627 }
60628 ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration;
60629 function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
60630 var node = createSynthesizedNode(151 /* Parameter */);
60631 node.decorators = asNodeArray(decorators);
60632 node.modifiers = asNodeArray(modifiers);
60633 node.dotDotDotToken = dotDotDotToken;
60634 node.name = asName(name);
60635 node.questionToken = questionToken;
60636 node.type = type;
60637 node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
60638 return node;
60639 }
60640 ts.createParameter = createParameter;
60641 function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
60642 return node.decorators !== decorators
60643 || node.modifiers !== modifiers
60644 || node.dotDotDotToken !== dotDotDotToken
60645 || node.name !== name
60646 || node.questionToken !== questionToken
60647 || node.type !== type
60648 || node.initializer !== initializer
60649 ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
60650 : node;
60651 }
60652 ts.updateParameter = updateParameter;
60653 function createDecorator(expression) {
60654 var node = createSynthesizedNode(152 /* Decorator */);
60655 node.expression = ts.parenthesizeForAccess(expression);
60656 return node;
60657 }
60658 ts.createDecorator = createDecorator;
60659 function updateDecorator(node, expression) {
60660 return node.expression !== expression
60661 ? updateNode(createDecorator(expression), node)
60662 : node;
60663 }
60664 ts.updateDecorator = updateDecorator;
60665 // Type Elements
60666 function createPropertySignature(modifiers, name, questionToken, type, initializer) {
60667 var node = createSynthesizedNode(153 /* PropertySignature */);
60668 node.modifiers = asNodeArray(modifiers);
60669 node.name = asName(name);
60670 node.questionToken = questionToken;
60671 node.type = type;
60672 node.initializer = initializer;
60673 return node;
60674 }
60675 ts.createPropertySignature = createPropertySignature;
60676 function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) {
60677 return node.modifiers !== modifiers
60678 || node.name !== name
60679 || node.questionToken !== questionToken
60680 || node.type !== type
60681 || node.initializer !== initializer
60682 ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node)
60683 : node;
60684 }
60685 ts.updatePropertySignature = updatePropertySignature;
60686 function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
60687 var node = createSynthesizedNode(154 /* PropertyDeclaration */);
60688 node.decorators = asNodeArray(decorators);
60689 node.modifiers = asNodeArray(modifiers);
60690 node.name = asName(name);
60691 node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined;
60692 node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined;
60693 node.type = type;
60694 node.initializer = initializer;
60695 return node;
60696 }
60697 ts.createProperty = createProperty;
60698 function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
60699 return node.decorators !== decorators
60700 || node.modifiers !== modifiers
60701 || node.name !== name
60702 || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 56 /* QuestionToken */ ? questionOrExclamationToken : undefined)
60703 || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 52 /* ExclamationToken */ ? questionOrExclamationToken : undefined)
60704 || node.type !== type
60705 || node.initializer !== initializer
60706 ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
60707 : node;
60708 }
60709 ts.updateProperty = updateProperty;
60710 function createMethodSignature(typeParameters, parameters, type, name, questionToken) {
60711 var node = createSignatureDeclaration(155 /* MethodSignature */, typeParameters, parameters, type);
60712 node.name = asName(name);
60713 node.questionToken = questionToken;
60714 return node;
60715 }
60716 ts.createMethodSignature = createMethodSignature;
60717 function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) {
60718 return node.typeParameters !== typeParameters
60719 || node.parameters !== parameters
60720 || node.type !== type
60721 || node.name !== name
60722 || node.questionToken !== questionToken
60723 ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
60724 : node;
60725 }
60726 ts.updateMethodSignature = updateMethodSignature;
60727 function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
60728 var node = createSynthesizedNode(156 /* MethodDeclaration */);
60729 node.decorators = asNodeArray(decorators);
60730 node.modifiers = asNodeArray(modifiers);
60731 node.asteriskToken = asteriskToken;
60732 node.name = asName(name);
60733 node.questionToken = questionToken;
60734 node.typeParameters = asNodeArray(typeParameters);
60735 node.parameters = createNodeArray(parameters);
60736 node.type = type;
60737 node.body = body;
60738 return node;
60739 }
60740 ts.createMethod = createMethod;
60741 function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
60742 return node.decorators !== decorators
60743 || node.modifiers !== modifiers
60744 || node.asteriskToken !== asteriskToken
60745 || node.name !== name
60746 || node.questionToken !== questionToken
60747 || node.typeParameters !== typeParameters
60748 || node.parameters !== parameters
60749 || node.type !== type
60750 || node.body !== body
60751 ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
60752 : node;
60753 }
60754 ts.updateMethod = updateMethod;
60755 function createConstructor(decorators, modifiers, parameters, body) {
60756 var node = createSynthesizedNode(157 /* Constructor */);
60757 node.decorators = asNodeArray(decorators);
60758 node.modifiers = asNodeArray(modifiers);
60759 node.typeParameters = undefined;
60760 node.parameters = createNodeArray(parameters);
60761 node.type = undefined;
60762 node.body = body;
60763 return node;
60764 }
60765 ts.createConstructor = createConstructor;
60766 function updateConstructor(node, decorators, modifiers, parameters, body) {
60767 return node.decorators !== decorators
60768 || node.modifiers !== modifiers
60769 || node.parameters !== parameters
60770 || node.body !== body
60771 ? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
60772 : node;
60773 }
60774 ts.updateConstructor = updateConstructor;
60775 function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
60776 var node = createSynthesizedNode(158 /* GetAccessor */);
60777 node.decorators = asNodeArray(decorators);
60778 node.modifiers = asNodeArray(modifiers);
60779 node.name = asName(name);
60780 node.typeParameters = undefined;
60781 node.parameters = createNodeArray(parameters);
60782 node.type = type;
60783 node.body = body;
60784 return node;
60785 }
60786 ts.createGetAccessor = createGetAccessor;
60787 function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
60788 return node.decorators !== decorators
60789 || node.modifiers !== modifiers
60790 || node.name !== name
60791 || node.parameters !== parameters
60792 || node.type !== type
60793 || node.body !== body
60794 ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
60795 : node;
60796 }
60797 ts.updateGetAccessor = updateGetAccessor;
60798 function createSetAccessor(decorators, modifiers, name, parameters, body) {
60799 var node = createSynthesizedNode(159 /* SetAccessor */);
60800 node.decorators = asNodeArray(decorators);
60801 node.modifiers = asNodeArray(modifiers);
60802 node.name = asName(name);
60803 node.typeParameters = undefined;
60804 node.parameters = createNodeArray(parameters);
60805 node.body = body;
60806 return node;
60807 }
60808 ts.createSetAccessor = createSetAccessor;
60809 function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
60810 return node.decorators !== decorators
60811 || node.modifiers !== modifiers
60812 || node.name !== name
60813 || node.parameters !== parameters
60814 || node.body !== body
60815 ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
60816 : node;
60817 }
60818 ts.updateSetAccessor = updateSetAccessor;
60819 function createCallSignature(typeParameters, parameters, type) {
60820 return createSignatureDeclaration(160 /* CallSignature */, typeParameters, parameters, type);
60821 }
60822 ts.createCallSignature = createCallSignature;
60823 function updateCallSignature(node, typeParameters, parameters, type) {
60824 return updateSignatureDeclaration(node, typeParameters, parameters, type);
60825 }
60826 ts.updateCallSignature = updateCallSignature;
60827 function createConstructSignature(typeParameters, parameters, type) {
60828 return createSignatureDeclaration(161 /* ConstructSignature */, typeParameters, parameters, type);
60829 }
60830 ts.createConstructSignature = createConstructSignature;
60831 function updateConstructSignature(node, typeParameters, parameters, type) {
60832 return updateSignatureDeclaration(node, typeParameters, parameters, type);
60833 }
60834 ts.updateConstructSignature = updateConstructSignature;
60835 function createIndexSignature(decorators, modifiers, parameters, type) {
60836 var node = createSynthesizedNode(162 /* IndexSignature */);
60837 node.decorators = asNodeArray(decorators);
60838 node.modifiers = asNodeArray(modifiers);
60839 node.parameters = createNodeArray(parameters);
60840 node.type = type;
60841 return node;
60842 }
60843 ts.createIndexSignature = createIndexSignature;
60844 function updateIndexSignature(node, decorators, modifiers, parameters, type) {
60845 return node.parameters !== parameters
60846 || node.type !== type
60847 || node.decorators !== decorators
60848 || node.modifiers !== modifiers
60849 ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node)
60850 : node;
60851 }
60852 ts.updateIndexSignature = updateIndexSignature;
60853 /* @internal */
60854 function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) {
60855 var node = createSynthesizedNode(kind);
60856 node.typeParameters = asNodeArray(typeParameters);
60857 node.parameters = asNodeArray(parameters);
60858 node.type = type;
60859 node.typeArguments = asNodeArray(typeArguments);
60860 return node;
60861 }
60862 ts.createSignatureDeclaration = createSignatureDeclaration;
60863 function updateSignatureDeclaration(node, typeParameters, parameters, type) {
60864 return node.typeParameters !== typeParameters
60865 || node.parameters !== parameters
60866 || node.type !== type
60867 ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
60868 : node;
60869 }
60870 // Types
60871 function createKeywordTypeNode(kind) {
60872 return createSynthesizedNode(kind);
60873 }
60874 ts.createKeywordTypeNode = createKeywordTypeNode;
60875 function createTypePredicateNode(parameterName, type) {
60876 var node = createSynthesizedNode(163 /* TypePredicate */);
60877 node.parameterName = asName(parameterName);
60878 node.type = type;
60879 return node;
60880 }
60881 ts.createTypePredicateNode = createTypePredicateNode;
60882 function updateTypePredicateNode(node, parameterName, type) {
60883 return node.parameterName !== parameterName
60884 || node.type !== type
60885 ? updateNode(createTypePredicateNode(parameterName, type), node)
60886 : node;
60887 }
60888 ts.updateTypePredicateNode = updateTypePredicateNode;
60889 function createTypeReferenceNode(typeName, typeArguments) {
60890 var node = createSynthesizedNode(164 /* TypeReference */);
60891 node.typeName = asName(typeName);
60892 node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments);
60893 return node;
60894 }
60895 ts.createTypeReferenceNode = createTypeReferenceNode;
60896 function updateTypeReferenceNode(node, typeName, typeArguments) {
60897 return node.typeName !== typeName
60898 || node.typeArguments !== typeArguments
60899 ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
60900 : node;
60901 }
60902 ts.updateTypeReferenceNode = updateTypeReferenceNode;
60903 function createFunctionTypeNode(typeParameters, parameters, type) {
60904 return createSignatureDeclaration(165 /* FunctionType */, typeParameters, parameters, type);
60905 }
60906 ts.createFunctionTypeNode = createFunctionTypeNode;
60907 function updateFunctionTypeNode(node, typeParameters, parameters, type) {
60908 return updateSignatureDeclaration(node, typeParameters, parameters, type);
60909 }
60910 ts.updateFunctionTypeNode = updateFunctionTypeNode;
60911 function createConstructorTypeNode(typeParameters, parameters, type) {
60912 return createSignatureDeclaration(166 /* ConstructorType */, typeParameters, parameters, type);
60913 }
60914 ts.createConstructorTypeNode = createConstructorTypeNode;
60915 function updateConstructorTypeNode(node, typeParameters, parameters, type) {
60916 return updateSignatureDeclaration(node, typeParameters, parameters, type);
60917 }
60918 ts.updateConstructorTypeNode = updateConstructorTypeNode;
60919 function createTypeQueryNode(exprName) {
60920 var node = createSynthesizedNode(167 /* TypeQuery */);
60921 node.exprName = exprName;
60922 return node;
60923 }
60924 ts.createTypeQueryNode = createTypeQueryNode;
60925 function updateTypeQueryNode(node, exprName) {
60926 return node.exprName !== exprName
60927 ? updateNode(createTypeQueryNode(exprName), node)
60928 : node;
60929 }
60930 ts.updateTypeQueryNode = updateTypeQueryNode;
60931 function createTypeLiteralNode(members) {
60932 var node = createSynthesizedNode(168 /* TypeLiteral */);
60933 node.members = createNodeArray(members);
60934 return node;
60935 }
60936 ts.createTypeLiteralNode = createTypeLiteralNode;
60937 function updateTypeLiteralNode(node, members) {
60938 return node.members !== members
60939 ? updateNode(createTypeLiteralNode(members), node)
60940 : node;
60941 }
60942 ts.updateTypeLiteralNode = updateTypeLiteralNode;
60943 function createArrayTypeNode(elementType) {
60944 var node = createSynthesizedNode(169 /* ArrayType */);
60945 node.elementType = ts.parenthesizeArrayTypeMember(elementType);
60946 return node;
60947 }
60948 ts.createArrayTypeNode = createArrayTypeNode;
60949 function updateArrayTypeNode(node, elementType) {
60950 return node.elementType !== elementType
60951 ? updateNode(createArrayTypeNode(elementType), node)
60952 : node;
60953 }
60954 ts.updateArrayTypeNode = updateArrayTypeNode;
60955 function createTupleTypeNode(elementTypes) {
60956 var node = createSynthesizedNode(170 /* TupleType */);
60957 node.elementTypes = createNodeArray(elementTypes);
60958 return node;
60959 }
60960 ts.createTupleTypeNode = createTupleTypeNode;
60961 function updateTupleTypeNode(node, elementTypes) {
60962 return node.elementTypes !== elementTypes
60963 ? updateNode(createTupleTypeNode(elementTypes), node)
60964 : node;
60965 }
60966 ts.updateTupleTypeNode = updateTupleTypeNode;
60967 function createOptionalTypeNode(type) {
60968 var node = createSynthesizedNode(171 /* OptionalType */);
60969 node.type = ts.parenthesizeArrayTypeMember(type);
60970 return node;
60971 }
60972 ts.createOptionalTypeNode = createOptionalTypeNode;
60973 function updateOptionalTypeNode(node, type) {
60974 return node.type !== type
60975 ? updateNode(createOptionalTypeNode(type), node)
60976 : node;
60977 }
60978 ts.updateOptionalTypeNode = updateOptionalTypeNode;
60979 function createRestTypeNode(type) {
60980 var node = createSynthesizedNode(172 /* RestType */);
60981 node.type = type;
60982 return node;
60983 }
60984 ts.createRestTypeNode = createRestTypeNode;
60985 function updateRestTypeNode(node, type) {
60986 return node.type !== type
60987 ? updateNode(createRestTypeNode(type), node)
60988 : node;
60989 }
60990 ts.updateRestTypeNode = updateRestTypeNode;
60991 function createUnionTypeNode(types) {
60992 return createUnionOrIntersectionTypeNode(173 /* UnionType */, types);
60993 }
60994 ts.createUnionTypeNode = createUnionTypeNode;
60995 function updateUnionTypeNode(node, types) {
60996 return updateUnionOrIntersectionTypeNode(node, types);
60997 }
60998 ts.updateUnionTypeNode = updateUnionTypeNode;
60999 function createIntersectionTypeNode(types) {
61000 return createUnionOrIntersectionTypeNode(174 /* IntersectionType */, types);
61001 }
61002 ts.createIntersectionTypeNode = createIntersectionTypeNode;
61003 function updateIntersectionTypeNode(node, types) {
61004 return updateUnionOrIntersectionTypeNode(node, types);
61005 }
61006 ts.updateIntersectionTypeNode = updateIntersectionTypeNode;
61007 function createUnionOrIntersectionTypeNode(kind, types) {
61008 var node = createSynthesizedNode(kind);
61009 node.types = ts.parenthesizeElementTypeMembers(types);
61010 return node;
61011 }
61012 ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode;
61013 function updateUnionOrIntersectionTypeNode(node, types) {
61014 return node.types !== types
61015 ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
61016 : node;
61017 }
61018 function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
61019 var node = createSynthesizedNode(175 /* ConditionalType */);
61020 node.checkType = ts.parenthesizeConditionalTypeMember(checkType);
61021 node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType);
61022 node.trueType = trueType;
61023 node.falseType = falseType;
61024 return node;
61025 }
61026 ts.createConditionalTypeNode = createConditionalTypeNode;
61027 function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
61028 return node.checkType !== checkType
61029 || node.extendsType !== extendsType
61030 || node.trueType !== trueType
61031 || node.falseType !== falseType
61032 ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
61033 : node;
61034 }
61035 ts.updateConditionalTypeNode = updateConditionalTypeNode;
61036 function createInferTypeNode(typeParameter) {
61037 var node = createSynthesizedNode(176 /* InferType */);
61038 node.typeParameter = typeParameter;
61039 return node;
61040 }
61041 ts.createInferTypeNode = createInferTypeNode;
61042 function updateInferTypeNode(node, typeParameter) {
61043 return node.typeParameter !== typeParameter
61044 ? updateNode(createInferTypeNode(typeParameter), node)
61045 : node;
61046 }
61047 ts.updateInferTypeNode = updateInferTypeNode;
61048 function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
61049 var node = createSynthesizedNode(183 /* ImportType */);
61050 node.argument = argument;
61051 node.qualifier = qualifier;
61052 node.typeArguments = asNodeArray(typeArguments);
61053 node.isTypeOf = isTypeOf;
61054 return node;
61055 }
61056 ts.createImportTypeNode = createImportTypeNode;
61057 function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
61058 return node.argument !== argument
61059 || node.qualifier !== qualifier
61060 || node.typeArguments !== typeArguments
61061 || node.isTypeOf !== isTypeOf
61062 ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
61063 : node;
61064 }
61065 ts.updateImportTypeNode = updateImportTypeNode;
61066 function createParenthesizedType(type) {
61067 var node = createSynthesizedNode(177 /* ParenthesizedType */);
61068 node.type = type;
61069 return node;
61070 }
61071 ts.createParenthesizedType = createParenthesizedType;
61072 function updateParenthesizedType(node, type) {
61073 return node.type !== type
61074 ? updateNode(createParenthesizedType(type), node)
61075 : node;
61076 }
61077 ts.updateParenthesizedType = updateParenthesizedType;
61078 function createThisTypeNode() {
61079 return createSynthesizedNode(178 /* ThisType */);
61080 }
61081 ts.createThisTypeNode = createThisTypeNode;
61082 function createTypeOperatorNode(operatorOrType, type) {
61083 var node = createSynthesizedNode(179 /* TypeOperator */);
61084 node.operator = typeof operatorOrType === "number" ? operatorOrType : 129 /* KeyOfKeyword */;
61085 node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType);
61086 return node;
61087 }
61088 ts.createTypeOperatorNode = createTypeOperatorNode;
61089 function updateTypeOperatorNode(node, type) {
61090 return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node;
61091 }
61092 ts.updateTypeOperatorNode = updateTypeOperatorNode;
61093 function createIndexedAccessTypeNode(objectType, indexType) {
61094 var node = createSynthesizedNode(180 /* IndexedAccessType */);
61095 node.objectType = ts.parenthesizeElementTypeMember(objectType);
61096 node.indexType = indexType;
61097 return node;
61098 }
61099 ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode;
61100 function updateIndexedAccessTypeNode(node, objectType, indexType) {
61101 return node.objectType !== objectType
61102 || node.indexType !== indexType
61103 ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
61104 : node;
61105 }
61106 ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode;
61107 function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
61108 var node = createSynthesizedNode(181 /* MappedType */);
61109 node.readonlyToken = readonlyToken;
61110 node.typeParameter = typeParameter;
61111 node.questionToken = questionToken;
61112 node.type = type;
61113 return node;
61114 }
61115 ts.createMappedTypeNode = createMappedTypeNode;
61116 function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
61117 return node.readonlyToken !== readonlyToken
61118 || node.typeParameter !== typeParameter
61119 || node.questionToken !== questionToken
61120 || node.type !== type
61121 ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
61122 : node;
61123 }
61124 ts.updateMappedTypeNode = updateMappedTypeNode;
61125 function createLiteralTypeNode(literal) {
61126 var node = createSynthesizedNode(182 /* LiteralType */);
61127 node.literal = literal;
61128 return node;
61129 }
61130 ts.createLiteralTypeNode = createLiteralTypeNode;
61131 function updateLiteralTypeNode(node, literal) {
61132 return node.literal !== literal
61133 ? updateNode(createLiteralTypeNode(literal), node)
61134 : node;
61135 }
61136 ts.updateLiteralTypeNode = updateLiteralTypeNode;
61137 // Binding Patterns
61138 function createObjectBindingPattern(elements) {
61139 var node = createSynthesizedNode(184 /* ObjectBindingPattern */);
61140 node.elements = createNodeArray(elements);
61141 return node;
61142 }
61143 ts.createObjectBindingPattern = createObjectBindingPattern;
61144 function updateObjectBindingPattern(node, elements) {
61145 return node.elements !== elements
61146 ? updateNode(createObjectBindingPattern(elements), node)
61147 : node;
61148 }
61149 ts.updateObjectBindingPattern = updateObjectBindingPattern;
61150 function createArrayBindingPattern(elements) {
61151 var node = createSynthesizedNode(185 /* ArrayBindingPattern */);
61152 node.elements = createNodeArray(elements);
61153 return node;
61154 }
61155 ts.createArrayBindingPattern = createArrayBindingPattern;
61156 function updateArrayBindingPattern(node, elements) {
61157 return node.elements !== elements
61158 ? updateNode(createArrayBindingPattern(elements), node)
61159 : node;
61160 }
61161 ts.updateArrayBindingPattern = updateArrayBindingPattern;
61162 function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
61163 var node = createSynthesizedNode(186 /* BindingElement */);
61164 node.dotDotDotToken = dotDotDotToken;
61165 node.propertyName = asName(propertyName);
61166 node.name = asName(name);
61167 node.initializer = initializer;
61168 return node;
61169 }
61170 ts.createBindingElement = createBindingElement;
61171 function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
61172 return node.propertyName !== propertyName
61173 || node.dotDotDotToken !== dotDotDotToken
61174 || node.name !== name
61175 || node.initializer !== initializer
61176 ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
61177 : node;
61178 }
61179 ts.updateBindingElement = updateBindingElement;
61180 // Expression
61181 function createArrayLiteral(elements, multiLine) {
61182 var node = createSynthesizedNode(187 /* ArrayLiteralExpression */);
61183 node.elements = ts.parenthesizeListElements(createNodeArray(elements));
61184 if (multiLine)
61185 node.multiLine = true;
61186 return node;
61187 }
61188 ts.createArrayLiteral = createArrayLiteral;
61189 function updateArrayLiteral(node, elements) {
61190 return node.elements !== elements
61191 ? updateNode(createArrayLiteral(elements, node.multiLine), node)
61192 : node;
61193 }
61194 ts.updateArrayLiteral = updateArrayLiteral;
61195 function createObjectLiteral(properties, multiLine) {
61196 var node = createSynthesizedNode(188 /* ObjectLiteralExpression */);
61197 node.properties = createNodeArray(properties);
61198 if (multiLine)
61199 node.multiLine = true;
61200 return node;
61201 }
61202 ts.createObjectLiteral = createObjectLiteral;
61203 function updateObjectLiteral(node, properties) {
61204 return node.properties !== properties
61205 ? updateNode(createObjectLiteral(properties, node.multiLine), node)
61206 : node;
61207 }
61208 ts.updateObjectLiteral = updateObjectLiteral;
61209 function createPropertyAccess(expression, name) {
61210 var node = createSynthesizedNode(189 /* PropertyAccessExpression */);
61211 node.expression = ts.parenthesizeForAccess(expression);
61212 node.name = asName(name); // TODO: GH#18217
61213 setEmitFlags(node, 131072 /* NoIndentation */);
61214 return node;
61215 }
61216 ts.createPropertyAccess = createPropertyAccess;
61217 function updatePropertyAccess(node, expression, name) {
61218 // Because we are updating existed propertyAccess we want to inherit its emitFlags
61219 // instead of using the default from createPropertyAccess
61220 return node.expression !== expression
61221 || node.name !== name
61222 ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node)
61223 : node;
61224 }
61225 ts.updatePropertyAccess = updatePropertyAccess;
61226 function createElementAccess(expression, index) {
61227 var node = createSynthesizedNode(190 /* ElementAccessExpression */);
61228 node.expression = ts.parenthesizeForAccess(expression);
61229 node.argumentExpression = asExpression(index);
61230 return node;
61231 }
61232 ts.createElementAccess = createElementAccess;
61233 function updateElementAccess(node, expression, argumentExpression) {
61234 return node.expression !== expression
61235 || node.argumentExpression !== argumentExpression
61236 ? updateNode(createElementAccess(expression, argumentExpression), node)
61237 : node;
61238 }
61239 ts.updateElementAccess = updateElementAccess;
61240 function createCall(expression, typeArguments, argumentsArray) {
61241 var node = createSynthesizedNode(191 /* CallExpression */);
61242 node.expression = ts.parenthesizeForAccess(expression);
61243 node.typeArguments = asNodeArray(typeArguments);
61244 node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
61245 return node;
61246 }
61247 ts.createCall = createCall;
61248 function updateCall(node, expression, typeArguments, argumentsArray) {
61249 return node.expression !== expression
61250 || node.typeArguments !== typeArguments
61251 || node.arguments !== argumentsArray
61252 ? updateNode(createCall(expression, typeArguments, argumentsArray), node)
61253 : node;
61254 }
61255 ts.updateCall = updateCall;
61256 function createNew(expression, typeArguments, argumentsArray) {
61257 var node = createSynthesizedNode(192 /* NewExpression */);
61258 node.expression = ts.parenthesizeForNew(expression);
61259 node.typeArguments = asNodeArray(typeArguments);
61260 node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
61261 return node;
61262 }
61263 ts.createNew = createNew;
61264 function updateNew(node, expression, typeArguments, argumentsArray) {
61265 return node.expression !== expression
61266 || node.typeArguments !== typeArguments
61267 || node.arguments !== argumentsArray
61268 ? updateNode(createNew(expression, typeArguments, argumentsArray), node)
61269 : node;
61270 }
61271 ts.updateNew = updateNew;
61272 function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) {
61273 var node = createSynthesizedNode(193 /* TaggedTemplateExpression */);
61274 node.tag = ts.parenthesizeForAccess(tag);
61275 if (template) {
61276 node.typeArguments = asNodeArray(typeArgumentsOrTemplate);
61277 node.template = template;
61278 }
61279 else {
61280 node.typeArguments = undefined;
61281 node.template = typeArgumentsOrTemplate;
61282 }
61283 return node;
61284 }
61285 ts.createTaggedTemplate = createTaggedTemplate;
61286 function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) {
61287 return node.tag !== tag
61288 || (template
61289 ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template
61290 : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate)
61291 ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node)
61292 : node;
61293 }
61294 ts.updateTaggedTemplate = updateTaggedTemplate;
61295 function createTypeAssertion(type, expression) {
61296 var node = createSynthesizedNode(194 /* TypeAssertionExpression */);
61297 node.type = type;
61298 node.expression = ts.parenthesizePrefixOperand(expression);
61299 return node;
61300 }
61301 ts.createTypeAssertion = createTypeAssertion;
61302 function updateTypeAssertion(node, type, expression) {
61303 return node.type !== type
61304 || node.expression !== expression
61305 ? updateNode(createTypeAssertion(type, expression), node)
61306 : node;
61307 }
61308 ts.updateTypeAssertion = updateTypeAssertion;
61309 function createParen(expression) {
61310 var node = createSynthesizedNode(195 /* ParenthesizedExpression */);
61311 node.expression = expression;
61312 return node;
61313 }
61314 ts.createParen = createParen;
61315 function updateParen(node, expression) {
61316 return node.expression !== expression
61317 ? updateNode(createParen(expression), node)
61318 : node;
61319 }
61320 ts.updateParen = updateParen;
61321 function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
61322 var node = createSynthesizedNode(196 /* FunctionExpression */);
61323 node.modifiers = asNodeArray(modifiers);
61324 node.asteriskToken = asteriskToken;
61325 node.name = asName(name);
61326 node.typeParameters = asNodeArray(typeParameters);
61327 node.parameters = createNodeArray(parameters);
61328 node.type = type;
61329 node.body = body;
61330 return node;
61331 }
61332 ts.createFunctionExpression = createFunctionExpression;
61333 function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
61334 return node.name !== name
61335 || node.modifiers !== modifiers
61336 || node.asteriskToken !== asteriskToken
61337 || node.typeParameters !== typeParameters
61338 || node.parameters !== parameters
61339 || node.type !== type
61340 || node.body !== body
61341 ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
61342 : node;
61343 }
61344 ts.updateFunctionExpression = updateFunctionExpression;
61345 function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
61346 var node = createSynthesizedNode(197 /* ArrowFunction */);
61347 node.modifiers = asNodeArray(modifiers);
61348 node.typeParameters = asNodeArray(typeParameters);
61349 node.parameters = createNodeArray(parameters);
61350 node.type = type;
61351 node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(37 /* EqualsGreaterThanToken */);
61352 node.body = ts.parenthesizeConciseBody(body);
61353 return node;
61354 }
61355 ts.createArrowFunction = createArrowFunction;
61356 function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
61357 return node.modifiers !== modifiers
61358 || node.typeParameters !== typeParameters
61359 || node.parameters !== parameters
61360 || node.type !== type
61361 || node.equalsGreaterThanToken !== equalsGreaterThanToken
61362 || node.body !== body
61363 ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
61364 : node;
61365 }
61366 ts.updateArrowFunction = updateArrowFunction;
61367 function createDelete(expression) {
61368 var node = createSynthesizedNode(198 /* DeleteExpression */);
61369 node.expression = ts.parenthesizePrefixOperand(expression);
61370 return node;
61371 }
61372 ts.createDelete = createDelete;
61373 function updateDelete(node, expression) {
61374 return node.expression !== expression
61375 ? updateNode(createDelete(expression), node)
61376 : node;
61377 }
61378 ts.updateDelete = updateDelete;
61379 function createTypeOf(expression) {
61380 var node = createSynthesizedNode(199 /* TypeOfExpression */);
61381 node.expression = ts.parenthesizePrefixOperand(expression);
61382 return node;
61383 }
61384 ts.createTypeOf = createTypeOf;
61385 function updateTypeOf(node, expression) {
61386 return node.expression !== expression
61387 ? updateNode(createTypeOf(expression), node)
61388 : node;
61389 }
61390 ts.updateTypeOf = updateTypeOf;
61391 function createVoid(expression) {
61392 var node = createSynthesizedNode(200 /* VoidExpression */);
61393 node.expression = ts.parenthesizePrefixOperand(expression);
61394 return node;
61395 }
61396 ts.createVoid = createVoid;
61397 function updateVoid(node, expression) {
61398 return node.expression !== expression
61399 ? updateNode(createVoid(expression), node)
61400 : node;
61401 }
61402 ts.updateVoid = updateVoid;
61403 function createAwait(expression) {
61404 var node = createSynthesizedNode(201 /* AwaitExpression */);
61405 node.expression = ts.parenthesizePrefixOperand(expression);
61406 return node;
61407 }
61408 ts.createAwait = createAwait;
61409 function updateAwait(node, expression) {
61410 return node.expression !== expression
61411 ? updateNode(createAwait(expression), node)
61412 : node;
61413 }
61414 ts.updateAwait = updateAwait;
61415 function createPrefix(operator, operand) {
61416 var node = createSynthesizedNode(202 /* PrefixUnaryExpression */);
61417 node.operator = operator;
61418 node.operand = ts.parenthesizePrefixOperand(operand);
61419 return node;
61420 }
61421 ts.createPrefix = createPrefix;
61422 function updatePrefix(node, operand) {
61423 return node.operand !== operand
61424 ? updateNode(createPrefix(node.operator, operand), node)
61425 : node;
61426 }
61427 ts.updatePrefix = updatePrefix;
61428 function createPostfix(operand, operator) {
61429 var node = createSynthesizedNode(203 /* PostfixUnaryExpression */);
61430 node.operand = ts.parenthesizePostfixOperand(operand);
61431 node.operator = operator;
61432 return node;
61433 }
61434 ts.createPostfix = createPostfix;
61435 function updatePostfix(node, operand) {
61436 return node.operand !== operand
61437 ? updateNode(createPostfix(operand, node.operator), node)
61438 : node;
61439 }
61440 ts.updatePostfix = updatePostfix;
61441 function createBinary(left, operator, right) {
61442 var node = createSynthesizedNode(204 /* BinaryExpression */);
61443 var operatorToken = asToken(operator);
61444 var operatorKind = operatorToken.kind;
61445 node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
61446 node.operatorToken = operatorToken;
61447 node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
61448 return node;
61449 }
61450 ts.createBinary = createBinary;
61451 function updateBinary(node, left, right, operator) {
61452 return node.left !== left
61453 || node.right !== right
61454 ? updateNode(createBinary(left, operator || node.operatorToken, right), node)
61455 : node;
61456 }
61457 ts.updateBinary = updateBinary;
61458 function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
61459 var node = createSynthesizedNode(205 /* ConditionalExpression */);
61460 node.condition = ts.parenthesizeForConditionalHead(condition);
61461 node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(56 /* QuestionToken */);
61462 node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue);
61463 node.colonToken = whenFalse ? colonToken : createToken(57 /* ColonToken */);
61464 node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
61465 return node;
61466 }
61467 ts.createConditional = createConditional;
61468 function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
61469 return node.condition !== condition
61470 || node.questionToken !== questionToken
61471 || node.whenTrue !== whenTrue
61472 || node.colonToken !== colonToken
61473 || node.whenFalse !== whenFalse
61474 ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node)
61475 : node;
61476 }
61477 ts.updateConditional = updateConditional;
61478 function createTemplateExpression(head, templateSpans) {
61479 var node = createSynthesizedNode(206 /* TemplateExpression */);
61480 node.head = head;
61481 node.templateSpans = createNodeArray(templateSpans);
61482 return node;
61483 }
61484 ts.createTemplateExpression = createTemplateExpression;
61485 function updateTemplateExpression(node, head, templateSpans) {
61486 return node.head !== head
61487 || node.templateSpans !== templateSpans
61488 ? updateNode(createTemplateExpression(head, templateSpans), node)
61489 : node;
61490 }
61491 ts.updateTemplateExpression = updateTemplateExpression;
61492 function createTemplateHead(text) {
61493 var node = createSynthesizedNode(15 /* TemplateHead */);
61494 node.text = text;
61495 return node;
61496 }
61497 ts.createTemplateHead = createTemplateHead;
61498 function createTemplateMiddle(text) {
61499 var node = createSynthesizedNode(16 /* TemplateMiddle */);
61500 node.text = text;
61501 return node;
61502 }
61503 ts.createTemplateMiddle = createTemplateMiddle;
61504 function createTemplateTail(text) {
61505 var node = createSynthesizedNode(17 /* TemplateTail */);
61506 node.text = text;
61507 return node;
61508 }
61509 ts.createTemplateTail = createTemplateTail;
61510 function createNoSubstitutionTemplateLiteral(text) {
61511 var node = createSynthesizedNode(14 /* NoSubstitutionTemplateLiteral */);
61512 node.text = text;
61513 return node;
61514 }
61515 ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral;
61516 function createYield(asteriskTokenOrExpression, expression) {
61517 var node = createSynthesizedNode(207 /* YieldExpression */);
61518 node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 40 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined;
61519 node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 40 /* AsteriskToken */ ? asteriskTokenOrExpression : expression;
61520 return node;
61521 }
61522 ts.createYield = createYield;
61523 function updateYield(node, asteriskToken, expression) {
61524 return node.expression !== expression
61525 || node.asteriskToken !== asteriskToken
61526 ? updateNode(createYield(asteriskToken, expression), node)
61527 : node;
61528 }
61529 ts.updateYield = updateYield;
61530 function createSpread(expression) {
61531 var node = createSynthesizedNode(208 /* SpreadElement */);
61532 node.expression = ts.parenthesizeExpressionForList(expression);
61533 return node;
61534 }
61535 ts.createSpread = createSpread;
61536 function updateSpread(node, expression) {
61537 return node.expression !== expression
61538 ? updateNode(createSpread(expression), node)
61539 : node;
61540 }
61541 ts.updateSpread = updateSpread;
61542 function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
61543 var node = createSynthesizedNode(209 /* ClassExpression */);
61544 node.decorators = undefined;
61545 node.modifiers = asNodeArray(modifiers);
61546 node.name = asName(name);
61547 node.typeParameters = asNodeArray(typeParameters);
61548 node.heritageClauses = asNodeArray(heritageClauses);
61549 node.members = createNodeArray(members);
61550 return node;
61551 }
61552 ts.createClassExpression = createClassExpression;
61553 function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
61554 return node.modifiers !== modifiers
61555 || node.name !== name
61556 || node.typeParameters !== typeParameters
61557 || node.heritageClauses !== heritageClauses
61558 || node.members !== members
61559 ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
61560 : node;
61561 }
61562 ts.updateClassExpression = updateClassExpression;
61563 function createOmittedExpression() {
61564 return createSynthesizedNode(210 /* OmittedExpression */);
61565 }
61566 ts.createOmittedExpression = createOmittedExpression;
61567 function createExpressionWithTypeArguments(typeArguments, expression) {
61568 var node = createSynthesizedNode(211 /* ExpressionWithTypeArguments */);
61569 node.expression = ts.parenthesizeForAccess(expression);
61570 node.typeArguments = asNodeArray(typeArguments);
61571 return node;
61572 }
61573 ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments;
61574 function updateExpressionWithTypeArguments(node, typeArguments, expression) {
61575 return node.typeArguments !== typeArguments
61576 || node.expression !== expression
61577 ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
61578 : node;
61579 }
61580 ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments;
61581 function createAsExpression(expression, type) {
61582 var node = createSynthesizedNode(212 /* AsExpression */);
61583 node.expression = expression;
61584 node.type = type;
61585 return node;
61586 }
61587 ts.createAsExpression = createAsExpression;
61588 function updateAsExpression(node, expression, type) {
61589 return node.expression !== expression
61590 || node.type !== type
61591 ? updateNode(createAsExpression(expression, type), node)
61592 : node;
61593 }
61594 ts.updateAsExpression = updateAsExpression;
61595 function createNonNullExpression(expression) {
61596 var node = createSynthesizedNode(213 /* NonNullExpression */);
61597 node.expression = ts.parenthesizeForAccess(expression);
61598 return node;
61599 }
61600 ts.createNonNullExpression = createNonNullExpression;
61601 function updateNonNullExpression(node, expression) {
61602 return node.expression !== expression
61603 ? updateNode(createNonNullExpression(expression), node)
61604 : node;
61605 }
61606 ts.updateNonNullExpression = updateNonNullExpression;
61607 function createMetaProperty(keywordToken, name) {
61608 var node = createSynthesizedNode(214 /* MetaProperty */);
61609 node.keywordToken = keywordToken;
61610 node.name = name;
61611 return node;
61612 }
61613 ts.createMetaProperty = createMetaProperty;
61614 function updateMetaProperty(node, name) {
61615 return node.name !== name
61616 ? updateNode(createMetaProperty(node.keywordToken, name), node)
61617 : node;
61618 }
61619 ts.updateMetaProperty = updateMetaProperty;
61620 // Misc
61621 function createTemplateSpan(expression, literal) {
61622 var node = createSynthesizedNode(216 /* TemplateSpan */);
61623 node.expression = expression;
61624 node.literal = literal;
61625 return node;
61626 }
61627 ts.createTemplateSpan = createTemplateSpan;
61628 function updateTemplateSpan(node, expression, literal) {
61629 return node.expression !== expression
61630 || node.literal !== literal
61631 ? updateNode(createTemplateSpan(expression, literal), node)
61632 : node;
61633 }
61634 ts.updateTemplateSpan = updateTemplateSpan;
61635 function createSemicolonClassElement() {
61636 return createSynthesizedNode(217 /* SemicolonClassElement */);
61637 }
61638 ts.createSemicolonClassElement = createSemicolonClassElement;
61639 // Element
61640 function createBlock(statements, multiLine) {
61641 var block = createSynthesizedNode(218 /* Block */);
61642 block.statements = createNodeArray(statements);
61643 if (multiLine)
61644 block.multiLine = multiLine;
61645 return block;
61646 }
61647 ts.createBlock = createBlock;
61648 function updateBlock(node, statements) {
61649 return node.statements !== statements
61650 ? updateNode(createBlock(statements, node.multiLine), node)
61651 : node;
61652 }
61653 ts.updateBlock = updateBlock;
61654 function createVariableStatement(modifiers, declarationList) {
61655 var node = createSynthesizedNode(219 /* VariableStatement */);
61656 node.decorators = undefined;
61657 node.modifiers = asNodeArray(modifiers);
61658 node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
61659 return node;
61660 }
61661 ts.createVariableStatement = createVariableStatement;
61662 function updateVariableStatement(node, modifiers, declarationList) {
61663 return node.modifiers !== modifiers
61664 || node.declarationList !== declarationList
61665 ? updateNode(createVariableStatement(modifiers, declarationList), node)
61666 : node;
61667 }
61668 ts.updateVariableStatement = updateVariableStatement;
61669 function createEmptyStatement() {
61670 return createSynthesizedNode(220 /* EmptyStatement */);
61671 }
61672 ts.createEmptyStatement = createEmptyStatement;
61673 function createExpressionStatement(expression) {
61674 var node = createSynthesizedNode(221 /* ExpressionStatement */);
61675 node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
61676 return node;
61677 }
61678 ts.createExpressionStatement = createExpressionStatement;
61679 function updateExpressionStatement(node, expression) {
61680 return node.expression !== expression
61681 ? updateNode(createExpressionStatement(expression), node)
61682 : node;
61683 }
61684 ts.updateExpressionStatement = updateExpressionStatement;
61685 /** @deprecated Use `createExpressionStatement` instead. */
61686 ts.createStatement = createExpressionStatement;
61687 /** @deprecated Use `updateExpressionStatement` instead. */
61688 ts.updateStatement = updateExpressionStatement;
61689 function createIf(expression, thenStatement, elseStatement) {
61690 var node = createSynthesizedNode(222 /* IfStatement */);
61691 node.expression = expression;
61692 node.thenStatement = thenStatement;
61693 node.elseStatement = elseStatement;
61694 return node;
61695 }
61696 ts.createIf = createIf;
61697 function updateIf(node, expression, thenStatement, elseStatement) {
61698 return node.expression !== expression
61699 || node.thenStatement !== thenStatement
61700 || node.elseStatement !== elseStatement
61701 ? updateNode(createIf(expression, thenStatement, elseStatement), node)
61702 : node;
61703 }
61704 ts.updateIf = updateIf;
61705 function createDo(statement, expression) {
61706 var node = createSynthesizedNode(223 /* DoStatement */);
61707 node.statement = statement;
61708 node.expression = expression;
61709 return node;
61710 }
61711 ts.createDo = createDo;
61712 function updateDo(node, statement, expression) {
61713 return node.statement !== statement
61714 || node.expression !== expression
61715 ? updateNode(createDo(statement, expression), node)
61716 : node;
61717 }
61718 ts.updateDo = updateDo;
61719 function createWhile(expression, statement) {
61720 var node = createSynthesizedNode(224 /* WhileStatement */);
61721 node.expression = expression;
61722 node.statement = statement;
61723 return node;
61724 }
61725 ts.createWhile = createWhile;
61726 function updateWhile(node, expression, statement) {
61727 return node.expression !== expression
61728 || node.statement !== statement
61729 ? updateNode(createWhile(expression, statement), node)
61730 : node;
61731 }
61732 ts.updateWhile = updateWhile;
61733 function createFor(initializer, condition, incrementor, statement) {
61734 var node = createSynthesizedNode(225 /* ForStatement */);
61735 node.initializer = initializer;
61736 node.condition = condition;
61737 node.incrementor = incrementor;
61738 node.statement = statement;
61739 return node;
61740 }
61741 ts.createFor = createFor;
61742 function updateFor(node, initializer, condition, incrementor, statement) {
61743 return node.initializer !== initializer
61744 || node.condition !== condition
61745 || node.incrementor !== incrementor
61746 || node.statement !== statement
61747 ? updateNode(createFor(initializer, condition, incrementor, statement), node)
61748 : node;
61749 }
61750 ts.updateFor = updateFor;
61751 function createForIn(initializer, expression, statement) {
61752 var node = createSynthesizedNode(226 /* ForInStatement */);
61753 node.initializer = initializer;
61754 node.expression = expression;
61755 node.statement = statement;
61756 return node;
61757 }
61758 ts.createForIn = createForIn;
61759 function updateForIn(node, initializer, expression, statement) {
61760 return node.initializer !== initializer
61761 || node.expression !== expression
61762 || node.statement !== statement
61763 ? updateNode(createForIn(initializer, expression, statement), node)
61764 : node;
61765 }
61766 ts.updateForIn = updateForIn;
61767 function createForOf(awaitModifier, initializer, expression, statement) {
61768 var node = createSynthesizedNode(227 /* ForOfStatement */);
61769 node.awaitModifier = awaitModifier;
61770 node.initializer = initializer;
61771 node.expression = expression;
61772 node.statement = statement;
61773 return node;
61774 }
61775 ts.createForOf = createForOf;
61776 function updateForOf(node, awaitModifier, initializer, expression, statement) {
61777 return node.awaitModifier !== awaitModifier
61778 || node.initializer !== initializer
61779 || node.expression !== expression
61780 || node.statement !== statement
61781 ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node)
61782 : node;
61783 }
61784 ts.updateForOf = updateForOf;
61785 function createContinue(label) {
61786 var node = createSynthesizedNode(228 /* ContinueStatement */);
61787 node.label = asName(label);
61788 return node;
61789 }
61790 ts.createContinue = createContinue;
61791 function updateContinue(node, label) {
61792 return node.label !== label
61793 ? updateNode(createContinue(label), node)
61794 : node;
61795 }
61796 ts.updateContinue = updateContinue;
61797 function createBreak(label) {
61798 var node = createSynthesizedNode(229 /* BreakStatement */);
61799 node.label = asName(label);
61800 return node;
61801 }
61802 ts.createBreak = createBreak;
61803 function updateBreak(node, label) {
61804 return node.label !== label
61805 ? updateNode(createBreak(label), node)
61806 : node;
61807 }
61808 ts.updateBreak = updateBreak;
61809 function createReturn(expression) {
61810 var node = createSynthesizedNode(230 /* ReturnStatement */);
61811 node.expression = expression;
61812 return node;
61813 }
61814 ts.createReturn = createReturn;
61815 function updateReturn(node, expression) {
61816 return node.expression !== expression
61817 ? updateNode(createReturn(expression), node)
61818 : node;
61819 }
61820 ts.updateReturn = updateReturn;
61821 function createWith(expression, statement) {
61822 var node = createSynthesizedNode(231 /* WithStatement */);
61823 node.expression = expression;
61824 node.statement = statement;
61825 return node;
61826 }
61827 ts.createWith = createWith;
61828 function updateWith(node, expression, statement) {
61829 return node.expression !== expression
61830 || node.statement !== statement
61831 ? updateNode(createWith(expression, statement), node)
61832 : node;
61833 }
61834 ts.updateWith = updateWith;
61835 function createSwitch(expression, caseBlock) {
61836 var node = createSynthesizedNode(232 /* SwitchStatement */);
61837 node.expression = ts.parenthesizeExpressionForList(expression);
61838 node.caseBlock = caseBlock;
61839 return node;
61840 }
61841 ts.createSwitch = createSwitch;
61842 function updateSwitch(node, expression, caseBlock) {
61843 return node.expression !== expression
61844 || node.caseBlock !== caseBlock
61845 ? updateNode(createSwitch(expression, caseBlock), node)
61846 : node;
61847 }
61848 ts.updateSwitch = updateSwitch;
61849 function createLabel(label, statement) {
61850 var node = createSynthesizedNode(233 /* LabeledStatement */);
61851 node.label = asName(label);
61852 node.statement = statement;
61853 return node;
61854 }
61855 ts.createLabel = createLabel;
61856 function updateLabel(node, label, statement) {
61857 return node.label !== label
61858 || node.statement !== statement
61859 ? updateNode(createLabel(label, statement), node)
61860 : node;
61861 }
61862 ts.updateLabel = updateLabel;
61863 function createThrow(expression) {
61864 var node = createSynthesizedNode(234 /* ThrowStatement */);
61865 node.expression = expression;
61866 return node;
61867 }
61868 ts.createThrow = createThrow;
61869 function updateThrow(node, expression) {
61870 return node.expression !== expression
61871 ? updateNode(createThrow(expression), node)
61872 : node;
61873 }
61874 ts.updateThrow = updateThrow;
61875 function createTry(tryBlock, catchClause, finallyBlock) {
61876 var node = createSynthesizedNode(235 /* TryStatement */);
61877 node.tryBlock = tryBlock;
61878 node.catchClause = catchClause;
61879 node.finallyBlock = finallyBlock;
61880 return node;
61881 }
61882 ts.createTry = createTry;
61883 function updateTry(node, tryBlock, catchClause, finallyBlock) {
61884 return node.tryBlock !== tryBlock
61885 || node.catchClause !== catchClause
61886 || node.finallyBlock !== finallyBlock
61887 ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
61888 : node;
61889 }
61890 ts.updateTry = updateTry;
61891 function createDebuggerStatement() {
61892 return createSynthesizedNode(236 /* DebuggerStatement */);
61893 }
61894 ts.createDebuggerStatement = createDebuggerStatement;
61895 function createVariableDeclaration(name, type, initializer) {
61896 var node = createSynthesizedNode(237 /* VariableDeclaration */);
61897 node.name = asName(name);
61898 node.type = type;
61899 node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
61900 return node;
61901 }
61902 ts.createVariableDeclaration = createVariableDeclaration;
61903 function updateVariableDeclaration(node, name, type, initializer) {
61904 return node.name !== name
61905 || node.type !== type
61906 || node.initializer !== initializer
61907 ? updateNode(createVariableDeclaration(name, type, initializer), node)
61908 : node;
61909 }
61910 ts.updateVariableDeclaration = updateVariableDeclaration;
61911 function createVariableDeclarationList(declarations, flags) {
61912 if (flags === void 0) { flags = 0 /* None */; }
61913 var node = createSynthesizedNode(238 /* VariableDeclarationList */);
61914 node.flags |= flags & 3 /* BlockScoped */;
61915 node.declarations = createNodeArray(declarations);
61916 return node;
61917 }
61918 ts.createVariableDeclarationList = createVariableDeclarationList;
61919 function updateVariableDeclarationList(node, declarations) {
61920 return node.declarations !== declarations
61921 ? updateNode(createVariableDeclarationList(declarations, node.flags), node)
61922 : node;
61923 }
61924 ts.updateVariableDeclarationList = updateVariableDeclarationList;
61925 function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
61926 var node = createSynthesizedNode(239 /* FunctionDeclaration */);
61927 node.decorators = asNodeArray(decorators);
61928 node.modifiers = asNodeArray(modifiers);
61929 node.asteriskToken = asteriskToken;
61930 node.name = asName(name);
61931 node.typeParameters = asNodeArray(typeParameters);
61932 node.parameters = createNodeArray(parameters);
61933 node.type = type;
61934 node.body = body;
61935 return node;
61936 }
61937 ts.createFunctionDeclaration = createFunctionDeclaration;
61938 function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
61939 return node.decorators !== decorators
61940 || node.modifiers !== modifiers
61941 || node.asteriskToken !== asteriskToken
61942 || node.name !== name
61943 || node.typeParameters !== typeParameters
61944 || node.parameters !== parameters
61945 || node.type !== type
61946 || node.body !== body
61947 ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
61948 : node;
61949 }
61950 ts.updateFunctionDeclaration = updateFunctionDeclaration;
61951 function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
61952 var node = createSynthesizedNode(240 /* ClassDeclaration */);
61953 node.decorators = asNodeArray(decorators);
61954 node.modifiers = asNodeArray(modifiers);
61955 node.name = asName(name);
61956 node.typeParameters = asNodeArray(typeParameters);
61957 node.heritageClauses = asNodeArray(heritageClauses);
61958 node.members = createNodeArray(members);
61959 return node;
61960 }
61961 ts.createClassDeclaration = createClassDeclaration;
61962 function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
61963 return node.decorators !== decorators
61964 || node.modifiers !== modifiers
61965 || node.name !== name
61966 || node.typeParameters !== typeParameters
61967 || node.heritageClauses !== heritageClauses
61968 || node.members !== members
61969 ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
61970 : node;
61971 }
61972 ts.updateClassDeclaration = updateClassDeclaration;
61973 function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
61974 var node = createSynthesizedNode(241 /* InterfaceDeclaration */);
61975 node.decorators = asNodeArray(decorators);
61976 node.modifiers = asNodeArray(modifiers);
61977 node.name = asName(name);
61978 node.typeParameters = asNodeArray(typeParameters);
61979 node.heritageClauses = asNodeArray(heritageClauses);
61980 node.members = createNodeArray(members);
61981 return node;
61982 }
61983 ts.createInterfaceDeclaration = createInterfaceDeclaration;
61984 function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
61985 return node.decorators !== decorators
61986 || node.modifiers !== modifiers
61987 || node.name !== name
61988 || node.typeParameters !== typeParameters
61989 || node.heritageClauses !== heritageClauses
61990 || node.members !== members
61991 ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
61992 : node;
61993 }
61994 ts.updateInterfaceDeclaration = updateInterfaceDeclaration;
61995 function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
61996 var node = createSynthesizedNode(242 /* TypeAliasDeclaration */);
61997 node.decorators = asNodeArray(decorators);
61998 node.modifiers = asNodeArray(modifiers);
61999 node.name = asName(name);
62000 node.typeParameters = asNodeArray(typeParameters);
62001 node.type = type;
62002 return node;
62003 }
62004 ts.createTypeAliasDeclaration = createTypeAliasDeclaration;
62005 function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
62006 return node.decorators !== decorators
62007 || node.modifiers !== modifiers
62008 || node.name !== name
62009 || node.typeParameters !== typeParameters
62010 || node.type !== type
62011 ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
62012 : node;
62013 }
62014 ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration;
62015 function createEnumDeclaration(decorators, modifiers, name, members) {
62016 var node = createSynthesizedNode(243 /* EnumDeclaration */);
62017 node.decorators = asNodeArray(decorators);
62018 node.modifiers = asNodeArray(modifiers);
62019 node.name = asName(name);
62020 node.members = createNodeArray(members);
62021 return node;
62022 }
62023 ts.createEnumDeclaration = createEnumDeclaration;
62024 function updateEnumDeclaration(node, decorators, modifiers, name, members) {
62025 return node.decorators !== decorators
62026 || node.modifiers !== modifiers
62027 || node.name !== name
62028 || node.members !== members
62029 ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
62030 : node;
62031 }
62032 ts.updateEnumDeclaration = updateEnumDeclaration;
62033 function createModuleDeclaration(decorators, modifiers, name, body, flags) {
62034 if (flags === void 0) { flags = 0 /* None */; }
62035 var node = createSynthesizedNode(244 /* ModuleDeclaration */);
62036 node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */);
62037 node.decorators = asNodeArray(decorators);
62038 node.modifiers = asNodeArray(modifiers);
62039 node.name = name;
62040 node.body = body;
62041 return node;
62042 }
62043 ts.createModuleDeclaration = createModuleDeclaration;
62044 function updateModuleDeclaration(node, decorators, modifiers, name, body) {
62045 return node.decorators !== decorators
62046 || node.modifiers !== modifiers
62047 || node.name !== name
62048 || node.body !== body
62049 ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
62050 : node;
62051 }
62052 ts.updateModuleDeclaration = updateModuleDeclaration;
62053 function createModuleBlock(statements) {
62054 var node = createSynthesizedNode(245 /* ModuleBlock */);
62055 node.statements = createNodeArray(statements);
62056 return node;
62057 }
62058 ts.createModuleBlock = createModuleBlock;
62059 function updateModuleBlock(node, statements) {
62060 return node.statements !== statements
62061 ? updateNode(createModuleBlock(statements), node)
62062 : node;
62063 }
62064 ts.updateModuleBlock = updateModuleBlock;
62065 function createCaseBlock(clauses) {
62066 var node = createSynthesizedNode(246 /* CaseBlock */);
62067 node.clauses = createNodeArray(clauses);
62068 return node;
62069 }
62070 ts.createCaseBlock = createCaseBlock;
62071 function updateCaseBlock(node, clauses) {
62072 return node.clauses !== clauses
62073 ? updateNode(createCaseBlock(clauses), node)
62074 : node;
62075 }
62076 ts.updateCaseBlock = updateCaseBlock;
62077 function createNamespaceExportDeclaration(name) {
62078 var node = createSynthesizedNode(247 /* NamespaceExportDeclaration */);
62079 node.name = asName(name);
62080 return node;
62081 }
62082 ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration;
62083 function updateNamespaceExportDeclaration(node, name) {
62084 return node.name !== name
62085 ? updateNode(createNamespaceExportDeclaration(name), node)
62086 : node;
62087 }
62088 ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration;
62089 function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
62090 var node = createSynthesizedNode(248 /* ImportEqualsDeclaration */);
62091 node.decorators = asNodeArray(decorators);
62092 node.modifiers = asNodeArray(modifiers);
62093 node.name = asName(name);
62094 node.moduleReference = moduleReference;
62095 return node;
62096 }
62097 ts.createImportEqualsDeclaration = createImportEqualsDeclaration;
62098 function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
62099 return node.decorators !== decorators
62100 || node.modifiers !== modifiers
62101 || node.name !== name
62102 || node.moduleReference !== moduleReference
62103 ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
62104 : node;
62105 }
62106 ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration;
62107 function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
62108 var node = createSynthesizedNode(249 /* ImportDeclaration */);
62109 node.decorators = asNodeArray(decorators);
62110 node.modifiers = asNodeArray(modifiers);
62111 node.importClause = importClause;
62112 node.moduleSpecifier = moduleSpecifier;
62113 return node;
62114 }
62115 ts.createImportDeclaration = createImportDeclaration;
62116 function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
62117 return node.decorators !== decorators
62118 || node.modifiers !== modifiers
62119 || node.importClause !== importClause
62120 || node.moduleSpecifier !== moduleSpecifier
62121 ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
62122 : node;
62123 }
62124 ts.updateImportDeclaration = updateImportDeclaration;
62125 function createImportClause(name, namedBindings) {
62126 var node = createSynthesizedNode(250 /* ImportClause */);
62127 node.name = name;
62128 node.namedBindings = namedBindings;
62129 return node;
62130 }
62131 ts.createImportClause = createImportClause;
62132 function updateImportClause(node, name, namedBindings) {
62133 return node.name !== name
62134 || node.namedBindings !== namedBindings
62135 ? updateNode(createImportClause(name, namedBindings), node)
62136 : node;
62137 }
62138 ts.updateImportClause = updateImportClause;
62139 function createNamespaceImport(name) {
62140 var node = createSynthesizedNode(251 /* NamespaceImport */);
62141 node.name = name;
62142 return node;
62143 }
62144 ts.createNamespaceImport = createNamespaceImport;
62145 function updateNamespaceImport(node, name) {
62146 return node.name !== name
62147 ? updateNode(createNamespaceImport(name), node)
62148 : node;
62149 }
62150 ts.updateNamespaceImport = updateNamespaceImport;
62151 function createNamedImports(elements) {
62152 var node = createSynthesizedNode(252 /* NamedImports */);
62153 node.elements = createNodeArray(elements);
62154 return node;
62155 }
62156 ts.createNamedImports = createNamedImports;
62157 function updateNamedImports(node, elements) {
62158 return node.elements !== elements
62159 ? updateNode(createNamedImports(elements), node)
62160 : node;
62161 }
62162 ts.updateNamedImports = updateNamedImports;
62163 function createImportSpecifier(propertyName, name) {
62164 var node = createSynthesizedNode(253 /* ImportSpecifier */);
62165 node.propertyName = propertyName;
62166 node.name = name;
62167 return node;
62168 }
62169 ts.createImportSpecifier = createImportSpecifier;
62170 function updateImportSpecifier(node, propertyName, name) {
62171 return node.propertyName !== propertyName
62172 || node.name !== name
62173 ? updateNode(createImportSpecifier(propertyName, name), node)
62174 : node;
62175 }
62176 ts.updateImportSpecifier = updateImportSpecifier;
62177 function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
62178 var node = createSynthesizedNode(254 /* ExportAssignment */);
62179 node.decorators = asNodeArray(decorators);
62180 node.modifiers = asNodeArray(modifiers);
62181 node.isExportEquals = isExportEquals;
62182 node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(59 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression);
62183 return node;
62184 }
62185 ts.createExportAssignment = createExportAssignment;
62186 function updateExportAssignment(node, decorators, modifiers, expression) {
62187 return node.decorators !== decorators
62188 || node.modifiers !== modifiers
62189 || node.expression !== expression
62190 ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
62191 : node;
62192 }
62193 ts.updateExportAssignment = updateExportAssignment;
62194 function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) {
62195 var node = createSynthesizedNode(255 /* ExportDeclaration */);
62196 node.decorators = asNodeArray(decorators);
62197 node.modifiers = asNodeArray(modifiers);
62198 node.exportClause = exportClause;
62199 node.moduleSpecifier = moduleSpecifier;
62200 return node;
62201 }
62202 ts.createExportDeclaration = createExportDeclaration;
62203 function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) {
62204 return node.decorators !== decorators
62205 || node.modifiers !== modifiers
62206 || node.exportClause !== exportClause
62207 || node.moduleSpecifier !== moduleSpecifier
62208 ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier), node)
62209 : node;
62210 }
62211 ts.updateExportDeclaration = updateExportDeclaration;
62212 function createNamedExports(elements) {
62213 var node = createSynthesizedNode(256 /* NamedExports */);
62214 node.elements = createNodeArray(elements);
62215 return node;
62216 }
62217 ts.createNamedExports = createNamedExports;
62218 function updateNamedExports(node, elements) {
62219 return node.elements !== elements
62220 ? updateNode(createNamedExports(elements), node)
62221 : node;
62222 }
62223 ts.updateNamedExports = updateNamedExports;
62224 function createExportSpecifier(propertyName, name) {
62225 var node = createSynthesizedNode(257 /* ExportSpecifier */);
62226 node.propertyName = asName(propertyName);
62227 node.name = asName(name);
62228 return node;
62229 }
62230 ts.createExportSpecifier = createExportSpecifier;
62231 function updateExportSpecifier(node, propertyName, name) {
62232 return node.propertyName !== propertyName
62233 || node.name !== name
62234 ? updateNode(createExportSpecifier(propertyName, name), node)
62235 : node;
62236 }
62237 ts.updateExportSpecifier = updateExportSpecifier;
62238 // Module references
62239 function createExternalModuleReference(expression) {
62240 var node = createSynthesizedNode(259 /* ExternalModuleReference */);
62241 node.expression = expression;
62242 return node;
62243 }
62244 ts.createExternalModuleReference = createExternalModuleReference;
62245 function updateExternalModuleReference(node, expression) {
62246 return node.expression !== expression
62247 ? updateNode(createExternalModuleReference(expression), node)
62248 : node;
62249 }
62250 ts.updateExternalModuleReference = updateExternalModuleReference;
62251 // JSDoc
62252 /* @internal */
62253 function createJSDocTypeExpression(type) {
62254 var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
62255 node.type = type;
62256 return node;
62257 }
62258 ts.createJSDocTypeExpression = createJSDocTypeExpression;
62259 /* @internal */
62260 function createJSDocTypeTag(typeExpression, comment) {
62261 var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
62262 tag.typeExpression = typeExpression;
62263 tag.comment = comment;
62264 return tag;
62265 }
62266 ts.createJSDocTypeTag = createJSDocTypeTag;
62267 /* @internal */
62268 function createJSDocReturnTag(typeExpression, comment) {
62269 var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
62270 tag.typeExpression = typeExpression;
62271 tag.comment = comment;
62272 return tag;
62273 }
62274 ts.createJSDocReturnTag = createJSDocReturnTag;
62275 /* @internal */
62276 function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
62277 var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
62278 tag.typeExpression = typeExpression;
62279 tag.name = name;
62280 tag.isBracketed = isBracketed;
62281 tag.comment = comment;
62282 return tag;
62283 }
62284 ts.createJSDocParamTag = createJSDocParamTag;
62285 /* @internal */
62286 function createJSDocComment(comment, tags) {
62287 var node = createSynthesizedNode(296 /* JSDocComment */);
62288 node.comment = comment;
62289 node.tags = tags;
62290 return node;
62291 }
62292 ts.createJSDocComment = createJSDocComment;
62293 /* @internal */
62294 function createJSDocTag(kind, tagName) {
62295 var node = createSynthesizedNode(kind);
62296 node.tagName = createIdentifier(tagName);
62297 return node;
62298 }
62299 // JSX
62300 function createJsxElement(openingElement, children, closingElement) {
62301 var node = createSynthesizedNode(260 /* JsxElement */);
62302 node.openingElement = openingElement;
62303 node.children = createNodeArray(children);
62304 node.closingElement = closingElement;
62305 return node;
62306 }
62307 ts.createJsxElement = createJsxElement;
62308 function updateJsxElement(node, openingElement, children, closingElement) {
62309 return node.openingElement !== openingElement
62310 || node.children !== children
62311 || node.closingElement !== closingElement
62312 ? updateNode(createJsxElement(openingElement, children, closingElement), node)
62313 : node;
62314 }
62315 ts.updateJsxElement = updateJsxElement;
62316 function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
62317 var node = createSynthesizedNode(261 /* JsxSelfClosingElement */);
62318 node.tagName = tagName;
62319 node.typeArguments = asNodeArray(typeArguments);
62320 node.attributes = attributes;
62321 return node;
62322 }
62323 ts.createJsxSelfClosingElement = createJsxSelfClosingElement;
62324 function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
62325 return node.tagName !== tagName
62326 || node.typeArguments !== typeArguments
62327 || node.attributes !== attributes
62328 ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
62329 : node;
62330 }
62331 ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement;
62332 function createJsxOpeningElement(tagName, typeArguments, attributes) {
62333 var node = createSynthesizedNode(262 /* JsxOpeningElement */);
62334 node.tagName = tagName;
62335 node.typeArguments = asNodeArray(typeArguments);
62336 node.attributes = attributes;
62337 return node;
62338 }
62339 ts.createJsxOpeningElement = createJsxOpeningElement;
62340 function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
62341 return node.tagName !== tagName
62342 || node.typeArguments !== typeArguments
62343 || node.attributes !== attributes
62344 ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node)
62345 : node;
62346 }
62347 ts.updateJsxOpeningElement = updateJsxOpeningElement;
62348 function createJsxClosingElement(tagName) {
62349 var node = createSynthesizedNode(263 /* JsxClosingElement */);
62350 node.tagName = tagName;
62351 return node;
62352 }
62353 ts.createJsxClosingElement = createJsxClosingElement;
62354 function updateJsxClosingElement(node, tagName) {
62355 return node.tagName !== tagName
62356 ? updateNode(createJsxClosingElement(tagName), node)
62357 : node;
62358 }
62359 ts.updateJsxClosingElement = updateJsxClosingElement;
62360 function createJsxFragment(openingFragment, children, closingFragment) {
62361 var node = createSynthesizedNode(264 /* JsxFragment */);
62362 node.openingFragment = openingFragment;
62363 node.children = createNodeArray(children);
62364 node.closingFragment = closingFragment;
62365 return node;
62366 }
62367 ts.createJsxFragment = createJsxFragment;
62368 function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
62369 var node = createSynthesizedNode(11 /* JsxText */);
62370 node.text = text;
62371 node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
62372 return node;
62373 }
62374 ts.createJsxText = createJsxText;
62375 function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
62376 return node.text !== text
62377 || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
62378 ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
62379 : node;
62380 }
62381 ts.updateJsxText = updateJsxText;
62382 function createJsxOpeningFragment() {
62383 return createSynthesizedNode(265 /* JsxOpeningFragment */);
62384 }
62385 ts.createJsxOpeningFragment = createJsxOpeningFragment;
62386 function createJsxJsxClosingFragment() {
62387 return createSynthesizedNode(266 /* JsxClosingFragment */);
62388 }
62389 ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
62390 function updateJsxFragment(node, openingFragment, children, closingFragment) {
62391 return node.openingFragment !== openingFragment
62392 || node.children !== children
62393 || node.closingFragment !== closingFragment
62394 ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node)
62395 : node;
62396 }
62397 ts.updateJsxFragment = updateJsxFragment;
62398 function createJsxAttribute(name, initializer) {
62399 var node = createSynthesizedNode(267 /* JsxAttribute */);
62400 node.name = name;
62401 node.initializer = initializer;
62402 return node;
62403 }
62404 ts.createJsxAttribute = createJsxAttribute;
62405 function updateJsxAttribute(node, name, initializer) {
62406 return node.name !== name
62407 || node.initializer !== initializer
62408 ? updateNode(createJsxAttribute(name, initializer), node)
62409 : node;
62410 }
62411 ts.updateJsxAttribute = updateJsxAttribute;
62412 function createJsxAttributes(properties) {
62413 var node = createSynthesizedNode(268 /* JsxAttributes */);
62414 node.properties = createNodeArray(properties);
62415 return node;
62416 }
62417 ts.createJsxAttributes = createJsxAttributes;
62418 function updateJsxAttributes(node, properties) {
62419 return node.properties !== properties
62420 ? updateNode(createJsxAttributes(properties), node)
62421 : node;
62422 }
62423 ts.updateJsxAttributes = updateJsxAttributes;
62424 function createJsxSpreadAttribute(expression) {
62425 var node = createSynthesizedNode(269 /* JsxSpreadAttribute */);
62426 node.expression = expression;
62427 return node;
62428 }
62429 ts.createJsxSpreadAttribute = createJsxSpreadAttribute;
62430 function updateJsxSpreadAttribute(node, expression) {
62431 return node.expression !== expression
62432 ? updateNode(createJsxSpreadAttribute(expression), node)
62433 : node;
62434 }
62435 ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute;
62436 function createJsxExpression(dotDotDotToken, expression) {
62437 var node = createSynthesizedNode(270 /* JsxExpression */);
62438 node.dotDotDotToken = dotDotDotToken;
62439 node.expression = expression;
62440 return node;
62441 }
62442 ts.createJsxExpression = createJsxExpression;
62443 function updateJsxExpression(node, expression) {
62444 return node.expression !== expression
62445 ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node)
62446 : node;
62447 }
62448 ts.updateJsxExpression = updateJsxExpression;
62449 // Clauses
62450 function createCaseClause(expression, statements) {
62451 var node = createSynthesizedNode(271 /* CaseClause */);
62452 node.expression = ts.parenthesizeExpressionForList(expression);
62453 node.statements = createNodeArray(statements);
62454 return node;
62455 }
62456 ts.createCaseClause = createCaseClause;
62457 function updateCaseClause(node, expression, statements) {
62458 return node.expression !== expression
62459 || node.statements !== statements
62460 ? updateNode(createCaseClause(expression, statements), node)
62461 : node;
62462 }
62463 ts.updateCaseClause = updateCaseClause;
62464 function createDefaultClause(statements) {
62465 var node = createSynthesizedNode(272 /* DefaultClause */);
62466 node.statements = createNodeArray(statements);
62467 return node;
62468 }
62469 ts.createDefaultClause = createDefaultClause;
62470 function updateDefaultClause(node, statements) {
62471 return node.statements !== statements
62472 ? updateNode(createDefaultClause(statements), node)
62473 : node;
62474 }
62475 ts.updateDefaultClause = updateDefaultClause;
62476 function createHeritageClause(token, types) {
62477 var node = createSynthesizedNode(273 /* HeritageClause */);
62478 node.token = token;
62479 node.types = createNodeArray(types);
62480 return node;
62481 }
62482 ts.createHeritageClause = createHeritageClause;
62483 function updateHeritageClause(node, types) {
62484 return node.types !== types
62485 ? updateNode(createHeritageClause(node.token, types), node)
62486 : node;
62487 }
62488 ts.updateHeritageClause = updateHeritageClause;
62489 function createCatchClause(variableDeclaration, block) {
62490 var node = createSynthesizedNode(274 /* CatchClause */);
62491 node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
62492 node.block = block;
62493 return node;
62494 }
62495 ts.createCatchClause = createCatchClause;
62496 function updateCatchClause(node, variableDeclaration, block) {
62497 return node.variableDeclaration !== variableDeclaration
62498 || node.block !== block
62499 ? updateNode(createCatchClause(variableDeclaration, block), node)
62500 : node;
62501 }
62502 ts.updateCatchClause = updateCatchClause;
62503 // Property assignments
62504 function createPropertyAssignment(name, initializer) {
62505 var node = createSynthesizedNode(275 /* PropertyAssignment */);
62506 node.name = asName(name);
62507 node.questionToken = undefined;
62508 node.initializer = ts.parenthesizeExpressionForList(initializer);
62509 return node;
62510 }
62511 ts.createPropertyAssignment = createPropertyAssignment;
62512 function updatePropertyAssignment(node, name, initializer) {
62513 return node.name !== name
62514 || node.initializer !== initializer
62515 ? updateNode(createPropertyAssignment(name, initializer), node)
62516 : node;
62517 }
62518 ts.updatePropertyAssignment = updatePropertyAssignment;
62519 function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
62520 var node = createSynthesizedNode(276 /* ShorthandPropertyAssignment */);
62521 node.name = asName(name);
62522 node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
62523 return node;
62524 }
62525 ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment;
62526 function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
62527 return node.name !== name
62528 || node.objectAssignmentInitializer !== objectAssignmentInitializer
62529 ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
62530 : node;
62531 }
62532 ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment;
62533 function createSpreadAssignment(expression) {
62534 var node = createSynthesizedNode(277 /* SpreadAssignment */);
62535 node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217
62536 return node;
62537 }
62538 ts.createSpreadAssignment = createSpreadAssignment;
62539 function updateSpreadAssignment(node, expression) {
62540 return node.expression !== expression
62541 ? updateNode(createSpreadAssignment(expression), node)
62542 : node;
62543 }
62544 ts.updateSpreadAssignment = updateSpreadAssignment;
62545 // Enum
62546 function createEnumMember(name, initializer) {
62547 var node = createSynthesizedNode(278 /* EnumMember */);
62548 node.name = asName(name);
62549 node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
62550 return node;
62551 }
62552 ts.createEnumMember = createEnumMember;
62553 function updateEnumMember(node, name, initializer) {
62554 return node.name !== name
62555 || node.initializer !== initializer
62556 ? updateNode(createEnumMember(name, initializer), node)
62557 : node;
62558 }
62559 ts.updateEnumMember = updateEnumMember;
62560 // Top-level nodes
62561 function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
62562 if (node.statements !== statements ||
62563 (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) ||
62564 (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) ||
62565 (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
62566 (libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
62567 (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
62568 var updated = createSynthesizedNode(284 /* SourceFile */);
62569 updated.flags |= node.flags;
62570 updated.statements = createNodeArray(statements);
62571 updated.endOfFileToken = node.endOfFileToken;
62572 updated.fileName = node.fileName;
62573 updated.path = node.path;
62574 updated.text = node.text;
62575 updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile;
62576 updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles;
62577 updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences;
62578 updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib;
62579 updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences;
62580 if (node.amdDependencies !== undefined)
62581 updated.amdDependencies = node.amdDependencies;
62582 if (node.moduleName !== undefined)
62583 updated.moduleName = node.moduleName;
62584 if (node.languageVariant !== undefined)
62585 updated.languageVariant = node.languageVariant;
62586 if (node.renamedDependencies !== undefined)
62587 updated.renamedDependencies = node.renamedDependencies;
62588 if (node.languageVersion !== undefined)
62589 updated.languageVersion = node.languageVersion;
62590 if (node.scriptKind !== undefined)
62591 updated.scriptKind = node.scriptKind;
62592 if (node.externalModuleIndicator !== undefined)
62593 updated.externalModuleIndicator = node.externalModuleIndicator;
62594 if (node.commonJsModuleIndicator !== undefined)
62595 updated.commonJsModuleIndicator = node.commonJsModuleIndicator;
62596 if (node.identifiers !== undefined)
62597 updated.identifiers = node.identifiers;
62598 if (node.nodeCount !== undefined)
62599 updated.nodeCount = node.nodeCount;
62600 if (node.identifierCount !== undefined)
62601 updated.identifierCount = node.identifierCount;
62602 if (node.symbolCount !== undefined)
62603 updated.symbolCount = node.symbolCount;
62604 if (node.parseDiagnostics !== undefined)
62605 updated.parseDiagnostics = node.parseDiagnostics;
62606 if (node.bindDiagnostics !== undefined)
62607 updated.bindDiagnostics = node.bindDiagnostics;
62608 if (node.bindSuggestionDiagnostics !== undefined)
62609 updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics;
62610 if (node.lineMap !== undefined)
62611 updated.lineMap = node.lineMap;
62612 if (node.classifiableNames !== undefined)
62613 updated.classifiableNames = node.classifiableNames;
62614 if (node.resolvedModules !== undefined)
62615 updated.resolvedModules = node.resolvedModules;
62616 if (node.resolvedTypeReferenceDirectiveNames !== undefined)
62617 updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames;
62618 if (node.imports !== undefined)
62619 updated.imports = node.imports;
62620 if (node.moduleAugmentations !== undefined)
62621 updated.moduleAugmentations = node.moduleAugmentations;
62622 if (node.pragmas !== undefined)
62623 updated.pragmas = node.pragmas;
62624 if (node.localJsxFactory !== undefined)
62625 updated.localJsxFactory = node.localJsxFactory;
62626 if (node.localJsxNamespace !== undefined)
62627 updated.localJsxNamespace = node.localJsxNamespace;
62628 return updateNode(updated, node);
62629 }
62630 return node;
62631 }
62632 ts.updateSourceFileNode = updateSourceFileNode;
62633 /**
62634 * Creates a shallow, memberwise clone of a node for mutation.
62635 */
62636 function getMutableClone(node) {
62637 var clone = getSynthesizedClone(node);
62638 clone.pos = node.pos;
62639 clone.end = node.end;
62640 clone.parent = node.parent;
62641 return clone;
62642 }
62643 ts.getMutableClone = getMutableClone;
62644 // Transformation nodes
62645 /**
62646 * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
62647 * order to preserve comments.
62648 *
62649 * @param original The original statement.
62650 */
62651 function createNotEmittedStatement(original) {
62652 var node = createSynthesizedNode(312 /* NotEmittedStatement */);
62653 node.original = original;
62654 setTextRange(node, original);
62655 return node;
62656 }
62657 ts.createNotEmittedStatement = createNotEmittedStatement;
62658 /**
62659 * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
62660 * order to properly emit exports.
62661 */
62662 /* @internal */
62663 function createEndOfDeclarationMarker(original) {
62664 var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
62665 node.emitNode = {};
62666 node.original = original;
62667 return node;
62668 }
62669 ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
62670 /**
62671 * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
62672 * order to properly emit exports.
62673 */
62674 /* @internal */
62675 function createMergeDeclarationMarker(original) {
62676 var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
62677 node.emitNode = {};
62678 node.original = original;
62679 return node;
62680 }
62681 ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
62682 /**
62683 * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
62684 * order to preserve comments or sourcemap positions.
62685 *
62686 * @param expression The inner expression to emit.
62687 * @param original The original outer expression.
62688 * @param location The location for the expression. Defaults to the positions from "original" if provided.
62689 */
62690 function createPartiallyEmittedExpression(expression, original) {
62691 var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
62692 node.expression = expression;
62693 node.original = original;
62694 setTextRange(node, original);
62695 return node;
62696 }
62697 ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression;
62698 function updatePartiallyEmittedExpression(node, expression) {
62699 if (node.expression !== expression) {
62700 return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
62701 }
62702 return node;
62703 }
62704 ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
62705 function flattenCommaElements(node) {
62706 if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
62707 if (node.kind === 314 /* CommaListExpression */) {
62708 return node.elements;
62709 }
62710 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
62711 return [node.left, node.right];
62712 }
62713 }
62714 return node;
62715 }
62716 function createCommaList(elements) {
62717 var node = createSynthesizedNode(314 /* CommaListExpression */);
62718 node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
62719 return node;
62720 }
62721 ts.createCommaList = createCommaList;
62722 function updateCommaList(node, elements) {
62723 return node.elements !== elements
62724 ? updateNode(createCommaList(elements), node)
62725 : node;
62726 }
62727 ts.updateCommaList = updateCommaList;
62728 function createBundle(sourceFiles, prepends) {
62729 if (prepends === void 0) { prepends = ts.emptyArray; }
62730 var node = ts.createNode(285 /* Bundle */);
62731 node.prepends = prepends;
62732 node.sourceFiles = sourceFiles;
62733 return node;
62734 }
62735 ts.createBundle = createBundle;
62736 var allUnscopedEmitHelpers;
62737 function getAllUnscopedEmitHelpers() {
62738 return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
62739 ts.valuesHelper,
62740 ts.readHelper,
62741 ts.spreadHelper,
62742 ts.restHelper,
62743 ts.decorateHelper,
62744 ts.metadataHelper,
62745 ts.paramHelper,
62746 ts.awaiterHelper,
62747 ts.assignHelper,
62748 ts.awaitHelper,
62749 ts.asyncGeneratorHelper,
62750 ts.asyncDelegator,
62751 ts.asyncValues,
62752 ts.extendsHelper,
62753 ts.templateObjectHelper,
62754 ts.generatorHelper,
62755 ts.importStarHelper,
62756 ts.importDefaultHelper
62757 ], function (helper) { return helper.name; }));
62758 }
62759 function createUnparsedSource() {
62760 var node = ts.createNode(286 /* UnparsedSource */);
62761 node.prologues = ts.emptyArray;
62762 node.referencedFiles = ts.emptyArray;
62763 node.libReferenceDirectives = ts.emptyArray;
62764 node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
62765 return node;
62766 }
62767 function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
62768 var node = createUnparsedSource();
62769 var stripInternal;
62770 var bundleFileInfo;
62771 if (!ts.isString(textOrInputFiles)) {
62772 ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
62773 node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
62774 node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
62775 Object.defineProperties(node, {
62776 text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
62777 sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
62778 });
62779 if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
62780 node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
62781 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
62782 stripInternal = mapTextOrStripInternal;
62783 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
62784 if (node.oldFileOfCurrentEmit) {
62785 parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
62786 return node;
62787 }
62788 }
62789 }
62790 else {
62791 node.fileName = "";
62792 node.text = textOrInputFiles;
62793 node.sourceMapPath = mapPathOrType;
62794 node.sourceMapText = mapTextOrStripInternal;
62795 }
62796 ts.Debug.assert(!node.oldFileOfCurrentEmit);
62797 parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
62798 return node;
62799 }
62800 ts.createUnparsedSourceFile = createUnparsedSourceFile;
62801 function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
62802 var prologues;
62803 var helpers;
62804 var referencedFiles;
62805 var typeReferenceDirectives;
62806 var libReferenceDirectives;
62807 var texts;
62808 for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
62809 var section = _a[_i];
62810 switch (section.kind) {
62811 case "prologue" /* Prologue */:
62812 (prologues || (prologues = [])).push(createUnparsedNode(section, node));
62813 break;
62814 case "emitHelpers" /* EmitHelpers */:
62815 (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
62816 break;
62817 case "no-default-lib" /* NoDefaultLib */:
62818 node.hasNoDefaultLib = true;
62819 break;
62820 case "reference" /* Reference */:
62821 (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
62822 break;
62823 case "type" /* Type */:
62824 (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
62825 break;
62826 case "lib" /* Lib */:
62827 (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
62828 break;
62829 case "prepend" /* Prepend */:
62830 var prependNode = createUnparsedNode(section, node);
62831 var prependTexts = void 0;
62832 for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
62833 var text = _c[_b];
62834 if (!stripInternal || text.kind !== "internal" /* Internal */) {
62835 (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
62836 }
62837 }
62838 prependNode.texts = prependTexts || ts.emptyArray;
62839 (texts || (texts = [])).push(prependNode);
62840 break;
62841 case "internal" /* Internal */:
62842 if (stripInternal)
62843 break;
62844 // falls through
62845 case "text" /* Text */:
62846 (texts || (texts = [])).push(createUnparsedNode(section, node));
62847 break;
62848 default:
62849 ts.Debug.assertNever(section);
62850 }
62851 }
62852 node.prologues = prologues || ts.emptyArray;
62853 node.helpers = helpers;
62854 node.referencedFiles = referencedFiles || ts.emptyArray;
62855 node.typeReferenceDirectives = typeReferenceDirectives;
62856 node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
62857 node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
62858 }
62859 function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
62860 ts.Debug.assert(!!node.oldFileOfCurrentEmit);
62861 var texts;
62862 var syntheticReferences;
62863 for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
62864 var section = _a[_i];
62865 switch (section.kind) {
62866 case "internal" /* Internal */:
62867 case "text" /* Text */:
62868 (texts || (texts = [])).push(createUnparsedNode(section, node));
62869 break;
62870 case "no-default-lib" /* NoDefaultLib */:
62871 case "reference" /* Reference */:
62872 case "type" /* Type */:
62873 case "lib" /* Lib */:
62874 (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
62875 break;
62876 // Ignore
62877 case "prologue" /* Prologue */:
62878 case "emitHelpers" /* EmitHelpers */:
62879 case "prepend" /* Prepend */:
62880 break;
62881 default:
62882 ts.Debug.assertNever(section);
62883 }
62884 }
62885 node.texts = texts || ts.emptyArray;
62886 node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
62887 node.syntheticReferences = syntheticReferences;
62888 return node;
62889 }
62890 function mapBundleFileSectionKindToSyntaxKind(kind) {
62891 switch (kind) {
62892 case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
62893 case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
62894 case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
62895 case "text" /* Text */: return 281 /* UnparsedText */;
62896 case "emitHelpers" /* EmitHelpers */:
62897 case "no-default-lib" /* NoDefaultLib */:
62898 case "reference" /* Reference */:
62899 case "type" /* Type */:
62900 case "lib" /* Lib */:
62901 return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
62902 default:
62903 return ts.Debug.assertNever(kind);
62904 }
62905 }
62906 function createUnparsedNode(section, parent) {
62907 var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
62908 node.parent = parent;
62909 node.data = section.data;
62910 return node;
62911 }
62912 function createUnparsedSyntheticReference(section, parent) {
62913 var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
62914 node.parent = parent;
62915 node.data = section.data;
62916 node.section = section;
62917 return node;
62918 }
62919 function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
62920 var node = ts.createNode(287 /* InputFiles */);
62921 if (!ts.isString(javascriptTextOrReadFileText)) {
62922 var cache_1 = ts.createMap();
62923 var textGetter_1 = function (path) {
62924 if (path === undefined)
62925 return undefined;
62926 var value = cache_1.get(path);
62927 if (value === undefined) {
62928 value = javascriptTextOrReadFileText(path);
62929 cache_1.set(path, value !== undefined ? value : false);
62930 }
62931 return value !== false ? value : undefined;
62932 };
62933 var definedTextGetter_1 = function (path) {
62934 var result = textGetter_1(path);
62935 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
62936 };
62937 var buildInfo_1;
62938 var getAndCacheBuildInfo_1 = function (getText) {
62939 if (buildInfo_1 === undefined) {
62940 var result = getText();
62941 buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
62942 }
62943 return buildInfo_1 || undefined;
62944 };
62945 node.javascriptPath = declarationTextOrJavascriptPath;
62946 node.javascriptMapPath = javascriptMapPath;
62947 node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
62948 node.declarationMapPath = declarationMapPath;
62949 node.buildInfoPath = declarationMapTextOrBuildInfoPath;
62950 Object.defineProperties(node, {
62951 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
62952 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
62953 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
62954 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
62955 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
62956 });
62957 }
62958 else {
62959 node.javascriptText = javascriptTextOrReadFileText;
62960 node.javascriptMapPath = javascriptMapPath;
62961 node.javascriptMapText = javascriptMapTextOrDeclarationPath;
62962 node.declarationText = declarationTextOrJavascriptPath;
62963 node.declarationMapPath = declarationMapPath;
62964 node.declarationMapText = declarationMapTextOrBuildInfoPath;
62965 node.javascriptPath = javascriptPath;
62966 node.declarationPath = declarationPath,
62967 node.buildInfoPath = buildInfoPath;
62968 node.buildInfo = buildInfo;
62969 node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
62970 }
62971 return node;
62972 }
62973 ts.createInputFiles = createInputFiles;
62974 function updateBundle(node, sourceFiles, prepends) {
62975 if (prepends === void 0) { prepends = ts.emptyArray; }
62976 if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
62977 return createBundle(sourceFiles, prepends);
62978 }
62979 return node;
62980 }
62981 ts.updateBundle = updateBundle;
62982 function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
62983 return createCall(createFunctionExpression(
62984 /*modifiers*/ undefined,
62985 /*asteriskToken*/ undefined,
62986 /*name*/ undefined,
62987 /*typeParameters*/ undefined,
62988 /*parameters*/ param ? [param] : [],
62989 /*type*/ undefined, createBlock(statements, /*multiLine*/ true)),
62990 /*typeArguments*/ undefined,
62991 /*argumentsArray*/ paramValue ? [paramValue] : []);
62992 }
62993 ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression;
62994 function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
62995 return createCall(createArrowFunction(
62996 /*modifiers*/ undefined,
62997 /*typeParameters*/ undefined,
62998 /*parameters*/ param ? [param] : [],
62999 /*type*/ undefined,
63000 /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)),
63001 /*typeArguments*/ undefined,
63002 /*argumentsArray*/ paramValue ? [paramValue] : []);
63003 }
63004 ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction;
63005 function createComma(left, right) {
63006 return createBinary(left, 27 /* CommaToken */, right);
63007 }
63008 ts.createComma = createComma;
63009 function createLessThan(left, right) {
63010 return createBinary(left, 28 /* LessThanToken */, right);
63011 }
63012 ts.createLessThan = createLessThan;
63013 function createAssignment(left, right) {
63014 return createBinary(left, 59 /* EqualsToken */, right);
63015 }
63016 ts.createAssignment = createAssignment;
63017 function createStrictEquality(left, right) {
63018 return createBinary(left, 35 /* EqualsEqualsEqualsToken */, right);
63019 }
63020 ts.createStrictEquality = createStrictEquality;
63021 function createStrictInequality(left, right) {
63022 return createBinary(left, 36 /* ExclamationEqualsEqualsToken */, right);
63023 }
63024 ts.createStrictInequality = createStrictInequality;
63025 function createAdd(left, right) {
63026 return createBinary(left, 38 /* PlusToken */, right);
63027 }
63028 ts.createAdd = createAdd;
63029 function createSubtract(left, right) {
63030 return createBinary(left, 39 /* MinusToken */, right);
63031 }
63032 ts.createSubtract = createSubtract;
63033 function createPostfixIncrement(operand) {
63034 return createPostfix(operand, 44 /* PlusPlusToken */);
63035 }
63036 ts.createPostfixIncrement = createPostfixIncrement;
63037 function createLogicalAnd(left, right) {
63038 return createBinary(left, 54 /* AmpersandAmpersandToken */, right);
63039 }
63040 ts.createLogicalAnd = createLogicalAnd;
63041 function createLogicalOr(left, right) {
63042 return createBinary(left, 55 /* BarBarToken */, right);
63043 }
63044 ts.createLogicalOr = createLogicalOr;
63045 function createLogicalNot(operand) {
63046 return createPrefix(52 /* ExclamationToken */, operand);
63047 }
63048 ts.createLogicalNot = createLogicalNot;
63049 function createVoidZero() {
63050 return createVoid(createLiteral(0));
63051 }
63052 ts.createVoidZero = createVoidZero;
63053 function createExportDefault(expression) {
63054 return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
63055 }
63056 ts.createExportDefault = createExportDefault;
63057 function createExternalModuleExport(exportName) {
63058 return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)]));
63059 }
63060 ts.createExternalModuleExport = createExternalModuleExport;
63061 // Utilities
63062 function asName(name) {
63063 return ts.isString(name) ? createIdentifier(name) : name;
63064 }
63065 function asExpression(value) {
63066 return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value;
63067 }
63068 function asNodeArray(array) {
63069 return array ? createNodeArray(array) : undefined;
63070 }
63071 function asToken(value) {
63072 return typeof value === "number" ? createToken(value) : value;
63073 }
63074 /**
63075 * Clears any EmitNode entries from parse-tree nodes.
63076 * @param sourceFile A source file.
63077 */
63078 function disposeEmitNodes(sourceFile) {
63079 // During transformation we may need to annotate a parse tree node with transient
63080 // transformation properties. As parse tree nodes live longer than transformation
63081 // nodes, we need to make sure we reclaim any memory allocated for custom ranges
63082 // from these nodes to ensure we do not hold onto entire subtrees just for position
63083 // information. We also need to reset these nodes to a pre-transformation state
63084 // for incremental parsing scenarios so that we do not impact later emit.
63085 sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
63086 var emitNode = sourceFile && sourceFile.emitNode;
63087 var annotatedNodes = emitNode && emitNode.annotatedNodes;
63088 if (annotatedNodes) {
63089 for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
63090 var node = annotatedNodes_1[_i];
63091 node.emitNode = undefined;
63092 }
63093 }
63094 }
63095 ts.disposeEmitNodes = disposeEmitNodes;
63096 /**
63097 * Associates a node with the current transformation, initializing
63098 * various transient transformation properties.
63099 */
63100 /* @internal */
63101 function getOrCreateEmitNode(node) {
63102 if (!node.emitNode) {
63103 if (ts.isParseTreeNode(node)) {
63104 // To avoid holding onto transformation artifacts, we keep track of any
63105 // parse tree node we are annotating. This allows us to clean them up after
63106 // all transformations have completed.
63107 if (node.kind === 284 /* SourceFile */) {
63108 return node.emitNode = { annotatedNodes: [node] };
63109 }
63110 var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
63111 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
63112 }
63113 node.emitNode = {};
63114 }
63115 return node.emitNode;
63116 }
63117 ts.getOrCreateEmitNode = getOrCreateEmitNode;
63118 function setTextRange(range, location) {
63119 if (location) {
63120 range.pos = location.pos;
63121 range.end = location.end;
63122 }
63123 return range;
63124 }
63125 ts.setTextRange = setTextRange;
63126 /**
63127 * Sets flags that control emit behavior of a node.
63128 */
63129 function setEmitFlags(node, emitFlags) {
63130 getOrCreateEmitNode(node).flags = emitFlags;
63131 return node;
63132 }
63133 ts.setEmitFlags = setEmitFlags;
63134 /**
63135 * Sets flags that control emit behavior of a node.
63136 */
63137 /* @internal */
63138 function addEmitFlags(node, emitFlags) {
63139 var emitNode = getOrCreateEmitNode(node);
63140 emitNode.flags = emitNode.flags | emitFlags;
63141 return node;
63142 }
63143 ts.addEmitFlags = addEmitFlags;
63144 /**
63145 * Gets a custom text range to use when emitting source maps.
63146 */
63147 function getSourceMapRange(node) {
63148 var emitNode = node.emitNode;
63149 return (emitNode && emitNode.sourceMapRange) || node;
63150 }
63151 ts.getSourceMapRange = getSourceMapRange;
63152 /**
63153 * Sets a custom text range to use when emitting source maps.
63154 */
63155 function setSourceMapRange(node, range) {
63156 getOrCreateEmitNode(node).sourceMapRange = range;
63157 return node;
63158 }
63159 ts.setSourceMapRange = setSourceMapRange;
63160 // tslint:disable-next-line variable-name
63161 var SourceMapSource;
63162 /**
63163 * Create an external source map source file reference
63164 */
63165 function createSourceMapSource(fileName, text, skipTrivia) {
63166 return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
63167 }
63168 ts.createSourceMapSource = createSourceMapSource;
63169 /**
63170 * Gets the TextRange to use for source maps for a token of a node.
63171 */
63172 function getTokenSourceMapRange(node, token) {
63173 var emitNode = node.emitNode;
63174 var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
63175 return tokenSourceMapRanges && tokenSourceMapRanges[token];
63176 }
63177 ts.getTokenSourceMapRange = getTokenSourceMapRange;
63178 /**
63179 * Sets the TextRange to use for source maps for a token of a node.
63180 */
63181 function setTokenSourceMapRange(node, token, range) {
63182 var emitNode = getOrCreateEmitNode(node);
63183 var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
63184 tokenSourceMapRanges[token] = range;
63185 return node;
63186 }
63187 ts.setTokenSourceMapRange = setTokenSourceMapRange;
63188 /**
63189 * Gets a custom text range to use when emitting comments.
63190 */
63191 /*@internal*/
63192 function getStartsOnNewLine(node) {
63193 var emitNode = node.emitNode;
63194 return emitNode && emitNode.startsOnNewLine;
63195 }
63196 ts.getStartsOnNewLine = getStartsOnNewLine;
63197 /**
63198 * Sets a custom text range to use when emitting comments.
63199 */
63200 /*@internal*/
63201 function setStartsOnNewLine(node, newLine) {
63202 getOrCreateEmitNode(node).startsOnNewLine = newLine;
63203 return node;
63204 }
63205 ts.setStartsOnNewLine = setStartsOnNewLine;
63206 /**
63207 * Gets a custom text range to use when emitting comments.
63208 */
63209 function getCommentRange(node) {
63210 var emitNode = node.emitNode;
63211 return (emitNode && emitNode.commentRange) || node;
63212 }
63213 ts.getCommentRange = getCommentRange;
63214 /**
63215 * Sets a custom text range to use when emitting comments.
63216 */
63217 function setCommentRange(node, range) {
63218 getOrCreateEmitNode(node).commentRange = range;
63219 return node;
63220 }
63221 ts.setCommentRange = setCommentRange;
63222 function getSyntheticLeadingComments(node) {
63223 var emitNode = node.emitNode;
63224 return emitNode && emitNode.leadingComments;
63225 }
63226 ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
63227 function setSyntheticLeadingComments(node, comments) {
63228 getOrCreateEmitNode(node).leadingComments = comments;
63229 return node;
63230 }
63231 ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
63232 function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
63233 return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
63234 }
63235 ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
63236 function getSyntheticTrailingComments(node) {
63237 var emitNode = node.emitNode;
63238 return emitNode && emitNode.trailingComments;
63239 }
63240 ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
63241 function setSyntheticTrailingComments(node, comments) {
63242 getOrCreateEmitNode(node).trailingComments = comments;
63243 return node;
63244 }
63245 ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
63246 function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
63247 return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
63248 }
63249 ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
63250 function moveSyntheticComments(node, original) {
63251 setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
63252 setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
63253 var emit = getOrCreateEmitNode(original);
63254 emit.leadingComments = undefined;
63255 emit.trailingComments = undefined;
63256 return node;
63257 }
63258 ts.moveSyntheticComments = moveSyntheticComments;
63259 /**
63260 * Gets the constant value to emit for an expression.
63261 */
63262 function getConstantValue(node) {
63263 var emitNode = node.emitNode;
63264 return emitNode && emitNode.constantValue;
63265 }
63266 ts.getConstantValue = getConstantValue;
63267 /**
63268 * Sets the constant value to emit for an expression.
63269 */
63270 function setConstantValue(node, value) {
63271 var emitNode = getOrCreateEmitNode(node);
63272 emitNode.constantValue = value;
63273 return node;
63274 }
63275 ts.setConstantValue = setConstantValue;
63276 /**
63277 * Adds an EmitHelper to a node.
63278 */
63279 function addEmitHelper(node, helper) {
63280 var emitNode = getOrCreateEmitNode(node);
63281 emitNode.helpers = ts.append(emitNode.helpers, helper);
63282 return node;
63283 }
63284 ts.addEmitHelper = addEmitHelper;
63285 /**
63286 * Add EmitHelpers to a node.
63287 */
63288 function addEmitHelpers(node, helpers) {
63289 if (ts.some(helpers)) {
63290 var emitNode = getOrCreateEmitNode(node);
63291 for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
63292 var helper = helpers_1[_i];
63293 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
63294 }
63295 }
63296 return node;
63297 }
63298 ts.addEmitHelpers = addEmitHelpers;
63299 /**
63300 * Removes an EmitHelper from a node.
63301 */
63302 function removeEmitHelper(node, helper) {
63303 var emitNode = node.emitNode;
63304 if (emitNode) {
63305 var helpers = emitNode.helpers;
63306 if (helpers) {
63307 return ts.orderedRemoveItem(helpers, helper);
63308 }
63309 }
63310 return false;
63311 }
63312 ts.removeEmitHelper = removeEmitHelper;
63313 /**
63314 * Gets the EmitHelpers of a node.
63315 */
63316 function getEmitHelpers(node) {
63317 var emitNode = node.emitNode;
63318 return emitNode && emitNode.helpers;
63319 }
63320 ts.getEmitHelpers = getEmitHelpers;
63321 /**
63322 * Moves matching emit helpers from a source node to a target node.
63323 */
63324 function moveEmitHelpers(source, target, predicate) {
63325 var sourceEmitNode = source.emitNode;
63326 var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
63327 if (!ts.some(sourceEmitHelpers))
63328 return;
63329 var targetEmitNode = getOrCreateEmitNode(target);
63330 var helpersRemoved = 0;
63331 for (var i = 0; i < sourceEmitHelpers.length; i++) {
63332 var helper = sourceEmitHelpers[i];
63333 if (predicate(helper)) {
63334 helpersRemoved++;
63335 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
63336 }
63337 else if (helpersRemoved > 0) {
63338 sourceEmitHelpers[i - helpersRemoved] = helper;
63339 }
63340 }
63341 if (helpersRemoved > 0) {
63342 sourceEmitHelpers.length -= helpersRemoved;
63343 }
63344 }
63345 ts.moveEmitHelpers = moveEmitHelpers;
63346 /* @internal */
63347 function compareEmitHelpers(x, y) {
63348 if (x === y)
63349 return 0 /* EqualTo */;
63350 if (x.priority === y.priority)
63351 return 0 /* EqualTo */;
63352 if (x.priority === undefined)
63353 return 1 /* GreaterThan */;
63354 if (y.priority === undefined)
63355 return -1 /* LessThan */;
63356 return ts.compareValues(x.priority, y.priority);
63357 }
63358 ts.compareEmitHelpers = compareEmitHelpers;
63359 function setOriginalNode(node, original) {
63360 node.original = original;
63361 if (original) {
63362 var emitNode = original.emitNode;
63363 if (emitNode)
63364 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
63365 }
63366 return node;
63367 }
63368 ts.setOriginalNode = setOriginalNode;
63369 function mergeEmitNode(sourceEmitNode, destEmitNode) {
63370 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;
63371 if (!destEmitNode)
63372 destEmitNode = {};
63373 // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
63374 if (leadingComments)
63375 destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
63376 if (trailingComments)
63377 destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
63378 if (flags)
63379 destEmitNode.flags = flags;
63380 if (commentRange)
63381 destEmitNode.commentRange = commentRange;
63382 if (sourceMapRange)
63383 destEmitNode.sourceMapRange = sourceMapRange;
63384 if (tokenSourceMapRanges)
63385 destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
63386 if (constantValue !== undefined)
63387 destEmitNode.constantValue = constantValue;
63388 if (helpers)
63389 destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
63390 if (startsOnNewLine !== undefined)
63391 destEmitNode.startsOnNewLine = startsOnNewLine;
63392 return destEmitNode;
63393 }
63394 function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
63395 if (!destRanges)
63396 destRanges = [];
63397 for (var key in sourceRanges) {
63398 destRanges[key] = sourceRanges[key];
63399 }
63400 return destRanges;
63401 }
63402})(ts || (ts = {}));
63403/* @internal */
63404(function (ts) {
63405 ts.nullTransformationContext = {
63406 enableEmitNotification: ts.noop,
63407 enableSubstitution: ts.noop,
63408 endLexicalEnvironment: ts.returnUndefined,
63409 getCompilerOptions: ts.notImplemented,
63410 getEmitHost: ts.notImplemented,
63411 getEmitResolver: ts.notImplemented,
63412 hoistFunctionDeclaration: ts.noop,
63413 hoistVariableDeclaration: ts.noop,
63414 isEmitNotificationEnabled: ts.notImplemented,
63415 isSubstitutionEnabled: ts.notImplemented,
63416 onEmitNode: ts.noop,
63417 onSubstituteNode: ts.notImplemented,
63418 readEmitHelpers: ts.notImplemented,
63419 requestEmitHelper: ts.noop,
63420 resumeLexicalEnvironment: ts.noop,
63421 startLexicalEnvironment: ts.noop,
63422 suspendLexicalEnvironment: ts.noop,
63423 addDiagnostic: ts.noop,
63424 };
63425 function createTypeCheck(value, tag) {
63426 return tag === "undefined"
63427 ? ts.createStrictEquality(value, ts.createVoidZero())
63428 : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
63429 }
63430 ts.createTypeCheck = createTypeCheck;
63431 function createMemberAccessForPropertyName(target, memberName, location) {
63432 if (ts.isComputedPropertyName(memberName)) {
63433 return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
63434 }
63435 else {
63436 var expression = ts.setTextRange(ts.isIdentifier(memberName)
63437 ? ts.createPropertyAccess(target, memberName)
63438 : ts.createElementAccess(target, memberName), memberName);
63439 ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
63440 return expression;
63441 }
63442 }
63443 ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
63444 function createFunctionCall(func, thisArg, argumentsList, location) {
63445 return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"),
63446 /*typeArguments*/ undefined, [
63447 thisArg
63448 ].concat(argumentsList)), location);
63449 }
63450 ts.createFunctionCall = createFunctionCall;
63451 function createFunctionApply(func, thisArg, argumentsExpression, location) {
63452 return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"),
63453 /*typeArguments*/ undefined, [
63454 thisArg,
63455 argumentsExpression
63456 ]), location);
63457 }
63458 ts.createFunctionApply = createFunctionApply;
63459 function createArraySlice(array, start) {
63460 var argumentsList = [];
63461 if (start !== undefined) {
63462 argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
63463 }
63464 return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
63465 }
63466 ts.createArraySlice = createArraySlice;
63467 function createArrayConcat(array, values) {
63468 return ts.createCall(ts.createPropertyAccess(array, "concat"),
63469 /*typeArguments*/ undefined, values);
63470 }
63471 ts.createArrayConcat = createArrayConcat;
63472 function createMathPow(left, right, location) {
63473 return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"),
63474 /*typeArguments*/ undefined, [left, right]), location);
63475 }
63476 ts.createMathPow = createMathPow;
63477 function createReactNamespace(reactNamespace, parent) {
63478 // To ensure the emit resolver can properly resolve the namespace, we need to
63479 // treat this identifier as if it were a source tree node by clearing the `Synthesized`
63480 // flag and setting a parent node.
63481 var react = ts.createIdentifier(reactNamespace || "React");
63482 react.flags &= ~8 /* Synthesized */;
63483 // Set the parent that is in parse tree
63484 // this makes sure that parent chain is intact for checker to traverse complete scope tree
63485 react.parent = ts.getParseTreeNode(parent);
63486 return react;
63487 }
63488 function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) {
63489 if (ts.isQualifiedName(jsxFactory)) {
63490 var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
63491 var right = ts.createIdentifier(ts.idText(jsxFactory.right));
63492 right.escapedText = jsxFactory.right.escapedText;
63493 return ts.createPropertyAccess(left, right);
63494 }
63495 else {
63496 return createReactNamespace(ts.idText(jsxFactory), parent);
63497 }
63498 }
63499 function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) {
63500 return jsxFactoryEntity ?
63501 createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
63502 ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
63503 }
63504 function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
63505 var argumentsList = [tagName];
63506 if (props) {
63507 argumentsList.push(props);
63508 }
63509 if (children && children.length > 0) {
63510 if (!props) {
63511 argumentsList.push(ts.createNull());
63512 }
63513 if (children.length > 1) {
63514 for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
63515 var child = children_1[_i];
63516 startOnNewLine(child);
63517 argumentsList.push(child);
63518 }
63519 }
63520 else {
63521 argumentsList.push(children[0]);
63522 }
63523 }
63524 return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement),
63525 /*typeArguments*/ undefined, argumentsList), location);
63526 }
63527 ts.createExpressionForJsxElement = createExpressionForJsxElement;
63528 function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) {
63529 var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment");
63530 var argumentsList = [tagName];
63531 argumentsList.push(ts.createNull());
63532 if (children && children.length > 0) {
63533 if (children.length > 1) {
63534 for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
63535 var child = children_2[_i];
63536 startOnNewLine(child);
63537 argumentsList.push(child);
63538 }
63539 }
63540 else {
63541 argumentsList.push(children[0]);
63542 }
63543 }
63544 return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement),
63545 /*typeArguments*/ undefined, argumentsList), location);
63546 }
63547 ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
63548 // Helpers
63549 function getHelperName(name) {
63550 return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
63551 }
63552 ts.getHelperName = getHelperName;
63553 ts.valuesHelper = {
63554 name: "typescript:values",
63555 scoped: false,
63556 text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
63557 };
63558 function createValuesHelper(context, expression, location) {
63559 context.requestEmitHelper(ts.valuesHelper);
63560 return ts.setTextRange(ts.createCall(getHelperName("__values"),
63561 /*typeArguments*/ undefined, [expression]), location);
63562 }
63563 ts.createValuesHelper = createValuesHelper;
63564 ts.readHelper = {
63565 name: "typescript:read",
63566 scoped: false,
63567 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 };"
63568 };
63569 function createReadHelper(context, iteratorRecord, count, location) {
63570 context.requestEmitHelper(ts.readHelper);
63571 return ts.setTextRange(ts.createCall(getHelperName("__read"),
63572 /*typeArguments*/ undefined, count !== undefined
63573 ? [iteratorRecord, ts.createLiteral(count)]
63574 : [iteratorRecord]), location);
63575 }
63576 ts.createReadHelper = createReadHelper;
63577 ts.spreadHelper = {
63578 name: "typescript:spread",
63579 scoped: false,
63580 text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
63581 };
63582 function createSpreadHelper(context, argumentList, location) {
63583 context.requestEmitHelper(ts.readHelper);
63584 context.requestEmitHelper(ts.spreadHelper);
63585 return ts.setTextRange(ts.createCall(getHelperName("__spread"),
63586 /*typeArguments*/ undefined, argumentList), location);
63587 }
63588 ts.createSpreadHelper = createSpreadHelper;
63589 // Utilities
63590 function createForOfBindingStatement(node, boundValue) {
63591 if (ts.isVariableDeclarationList(node)) {
63592 var firstDeclaration = ts.first(node.declarations);
63593 var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name,
63594 /*typeNode*/ undefined, boundValue);
63595 return ts.setTextRange(ts.createVariableStatement(
63596 /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])),
63597 /*location*/ node);
63598 }
63599 else {
63600 var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node);
63601 return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node);
63602 }
63603 }
63604 ts.createForOfBindingStatement = createForOfBindingStatement;
63605 function insertLeadingStatement(dest, source) {
63606 if (ts.isBlock(dest)) {
63607 return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray([source].concat(dest.statements)), dest.statements));
63608 }
63609 else {
63610 return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true);
63611 }
63612 }
63613 ts.insertLeadingStatement = insertLeadingStatement;
63614 function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
63615 if (!outermostLabeledStatement) {
63616 return node;
63617 }
63618 var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 233 /* LabeledStatement */
63619 ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
63620 : node);
63621 if (afterRestoreLabelCallback) {
63622 afterRestoreLabelCallback(outermostLabeledStatement);
63623 }
63624 return updated;
63625 }
63626 ts.restoreEnclosingLabel = restoreEnclosingLabel;
63627 function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
63628 var target = ts.skipParentheses(node);
63629 switch (target.kind) {
63630 case 72 /* Identifier */:
63631 return cacheIdentifiers;
63632 case 100 /* ThisKeyword */:
63633 case 8 /* NumericLiteral */:
63634 case 9 /* BigIntLiteral */:
63635 case 10 /* StringLiteral */:
63636 return false;
63637 case 187 /* ArrayLiteralExpression */:
63638 var elements = target.elements;
63639 if (elements.length === 0) {
63640 return false;
63641 }
63642 return true;
63643 case 188 /* ObjectLiteralExpression */:
63644 return target.properties.length > 0;
63645 default:
63646 return true;
63647 }
63648 }
63649 function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
63650 if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
63651 var callee = skipOuterExpressions(expression, 7 /* All */);
63652 var thisArg;
63653 var target;
63654 if (ts.isSuperProperty(callee)) {
63655 thisArg = ts.createThis();
63656 target = callee;
63657 }
63658 else if (callee.kind === 98 /* SuperKeyword */) {
63659 thisArg = ts.createThis();
63660 target = languageVersion < 2 /* ES2015 */
63661 ? ts.setTextRange(ts.createIdentifier("_super"), callee)
63662 : callee;
63663 }
63664 else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
63665 thisArg = ts.createVoidZero();
63666 target = parenthesizeForAccess(callee);
63667 }
63668 else {
63669 switch (callee.kind) {
63670 case 189 /* PropertyAccessExpression */: {
63671 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
63672 // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
63673 thisArg = ts.createTempVariable(recordTempVariable);
63674 target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
63675 ts.setTextRange(target, callee);
63676 }
63677 else {
63678 thisArg = callee.expression;
63679 target = callee;
63680 }
63681 break;
63682 }
63683 case 190 /* ElementAccessExpression */: {
63684 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
63685 // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
63686 thisArg = ts.createTempVariable(recordTempVariable);
63687 target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
63688 ts.setTextRange(target, callee);
63689 }
63690 else {
63691 thisArg = callee.expression;
63692 target = callee;
63693 }
63694 break;
63695 }
63696 default: {
63697 // for `a()` target is `a` and thisArg is `void 0`
63698 thisArg = ts.createVoidZero();
63699 target = parenthesizeForAccess(expression);
63700 break;
63701 }
63702 }
63703 }
63704 return { target: target, thisArg: thisArg };
63705 }
63706 ts.createCallBinding = createCallBinding;
63707 function inlineExpressions(expressions) {
63708 // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
63709 // stack size exceeded" errors.
63710 return expressions.length > 10
63711 ? ts.createCommaList(expressions)
63712 : ts.reduceLeft(expressions, ts.createComma);
63713 }
63714 ts.inlineExpressions = inlineExpressions;
63715 function createExpressionFromEntityName(node) {
63716 if (ts.isQualifiedName(node)) {
63717 var left = createExpressionFromEntityName(node.left);
63718 var right = ts.getMutableClone(node.right);
63719 return ts.setTextRange(ts.createPropertyAccess(left, right), node);
63720 }
63721 else {
63722 return ts.getMutableClone(node);
63723 }
63724 }
63725 ts.createExpressionFromEntityName = createExpressionFromEntityName;
63726 function createExpressionForPropertyName(memberName) {
63727 if (ts.isIdentifier(memberName)) {
63728 return ts.createLiteral(memberName);
63729 }
63730 else if (ts.isComputedPropertyName(memberName)) {
63731 return ts.getMutableClone(memberName.expression);
63732 }
63733 else {
63734 return ts.getMutableClone(memberName);
63735 }
63736 }
63737 ts.createExpressionForPropertyName = createExpressionForPropertyName;
63738 function createExpressionForObjectLiteralElementLike(node, property, receiver) {
63739 switch (property.kind) {
63740 case 158 /* GetAccessor */:
63741 case 159 /* SetAccessor */:
63742 return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine);
63743 case 275 /* PropertyAssignment */:
63744 return createExpressionForPropertyAssignment(property, receiver);
63745 case 276 /* ShorthandPropertyAssignment */:
63746 return createExpressionForShorthandPropertyAssignment(property, receiver);
63747 case 156 /* MethodDeclaration */:
63748 return createExpressionForMethodDeclaration(property, receiver);
63749 }
63750 }
63751 ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
63752 function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
63753 var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
63754 if (property === firstAccessor) {
63755 var properties_7 = [];
63756 if (getAccessor) {
63757 var getterFunction = ts.createFunctionExpression(getAccessor.modifiers,
63758 /*asteriskToken*/ undefined,
63759 /*name*/ undefined,
63760 /*typeParameters*/ undefined, getAccessor.parameters,
63761 /*type*/ undefined, getAccessor.body // TODO: GH#18217
63762 );
63763 ts.setTextRange(getterFunction, getAccessor);
63764 ts.setOriginalNode(getterFunction, getAccessor);
63765 var getter = ts.createPropertyAssignment("get", getterFunction);
63766 properties_7.push(getter);
63767 }
63768 if (setAccessor) {
63769 var setterFunction = ts.createFunctionExpression(setAccessor.modifiers,
63770 /*asteriskToken*/ undefined,
63771 /*name*/ undefined,
63772 /*typeParameters*/ undefined, setAccessor.parameters,
63773 /*type*/ undefined, setAccessor.body // TODO: GH#18217
63774 );
63775 ts.setTextRange(setterFunction, setAccessor);
63776 ts.setOriginalNode(setterFunction, setAccessor);
63777 var setter = ts.createPropertyAssignment("set", setterFunction);
63778 properties_7.push(setter);
63779 }
63780 properties_7.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
63781 properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
63782 var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
63783 /*typeArguments*/ undefined, [
63784 receiver,
63785 createExpressionForPropertyName(property.name),
63786 ts.createObjectLiteral(properties_7, multiLine)
63787 ]),
63788 /*location*/ firstAccessor);
63789 return ts.aggregateTransformFlags(expression);
63790 }
63791 return undefined;
63792 }
63793 function createExpressionForPropertyAssignment(property, receiver) {
63794 return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property));
63795 }
63796 function createExpressionForShorthandPropertyAssignment(property, receiver) {
63797 return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)),
63798 /*location*/ property),
63799 /*original*/ property));
63800 }
63801 function createExpressionForMethodDeclaration(method, receiver) {
63802 return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken,
63803 /*name*/ undefined,
63804 /*typeParameters*/ undefined, method.parameters,
63805 /*type*/ undefined, method.body // TODO: GH#18217
63806 ),
63807 /*location*/ method),
63808 /*original*/ method)),
63809 /*location*/ method),
63810 /*original*/ method));
63811 }
63812 /**
63813 * Gets the internal name of a declaration. This is primarily used for declarations that can be
63814 * referred to by name in the body of an ES5 class function body. An internal name will *never*
63815 * be prefixed with an module or namespace export modifier like "exports." when emitted as an
63816 * expression. An internal name will also *never* be renamed due to a collision with a block
63817 * scoped variable.
63818 *
63819 * @param node The declaration.
63820 * @param allowComments A value indicating whether comments may be emitted for the name.
63821 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
63822 */
63823 function getInternalName(node, allowComments, allowSourceMaps) {
63824 return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
63825 }
63826 ts.getInternalName = getInternalName;
63827 /**
63828 * Gets whether an identifier should only be referred to by its internal name.
63829 */
63830 function isInternalName(node) {
63831 return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
63832 }
63833 ts.isInternalName = isInternalName;
63834 /**
63835 * Gets the local name of a declaration. This is primarily used for declarations that can be
63836 * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
63837 * local name will *never* be prefixed with an module or namespace export modifier like
63838 * "exports." when emitted as an expression.
63839 *
63840 * @param node The declaration.
63841 * @param allowComments A value indicating whether comments may be emitted for the name.
63842 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
63843 */
63844 function getLocalName(node, allowComments, allowSourceMaps) {
63845 return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
63846 }
63847 ts.getLocalName = getLocalName;
63848 /**
63849 * Gets whether an identifier should only be referred to by its local name.
63850 */
63851 function isLocalName(node) {
63852 return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
63853 }
63854 ts.isLocalName = isLocalName;
63855 /**
63856 * Gets the export name of a declaration. This is primarily used for declarations that can be
63857 * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
63858 * export name will *always* be prefixed with an module or namespace export modifier like
63859 * `"exports."` when emitted as an expression if the name points to an exported symbol.
63860 *
63861 * @param node The declaration.
63862 * @param allowComments A value indicating whether comments may be emitted for the name.
63863 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
63864 */
63865 function getExportName(node, allowComments, allowSourceMaps) {
63866 return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
63867 }
63868 ts.getExportName = getExportName;
63869 /**
63870 * Gets whether an identifier should only be referred to by its export representation if the
63871 * name points to an exported symbol.
63872 */
63873 function isExportName(node) {
63874 return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
63875 }
63876 ts.isExportName = isExportName;
63877 /**
63878 * Gets the name of a declaration for use in declarations.
63879 *
63880 * @param node The declaration.
63881 * @param allowComments A value indicating whether comments may be emitted for the name.
63882 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
63883 */
63884 function getDeclarationName(node, allowComments, allowSourceMaps) {
63885 return getName(node, allowComments, allowSourceMaps);
63886 }
63887 ts.getDeclarationName = getDeclarationName;
63888 function getName(node, allowComments, allowSourceMaps, emitFlags) {
63889 if (emitFlags === void 0) { emitFlags = 0; }
63890 var nodeName = ts.getNameOfDeclaration(node);
63891 if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
63892 var name = ts.getMutableClone(nodeName);
63893 emitFlags |= ts.getEmitFlags(nodeName);
63894 if (!allowSourceMaps)
63895 emitFlags |= 48 /* NoSourceMap */;
63896 if (!allowComments)
63897 emitFlags |= 1536 /* NoComments */;
63898 if (emitFlags)
63899 ts.setEmitFlags(name, emitFlags);
63900 return name;
63901 }
63902 return ts.getGeneratedNameForNode(node);
63903 }
63904 /**
63905 * Gets the exported name of a declaration for use in expressions.
63906 *
63907 * An exported name will *always* be prefixed with an module or namespace export modifier like
63908 * "exports." if the name points to an exported symbol.
63909 *
63910 * @param ns The namespace identifier.
63911 * @param node The declaration.
63912 * @param allowComments A value indicating whether comments may be emitted for the name.
63913 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
63914 */
63915 function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
63916 if (ns && ts.hasModifier(node, 1 /* Export */)) {
63917 return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
63918 }
63919 return getExportName(node, allowComments, allowSourceMaps);
63920 }
63921 ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName;
63922 /**
63923 * Gets a namespace-qualified name for use in expressions.
63924 *
63925 * @param ns The namespace identifier.
63926 * @param name The name.
63927 * @param allowComments A value indicating whether comments may be emitted for the name.
63928 * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
63929 */
63930 function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
63931 var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
63932 ts.setTextRange(qualifiedName, name);
63933 var emitFlags = 0;
63934 if (!allowSourceMaps)
63935 emitFlags |= 48 /* NoSourceMap */;
63936 if (!allowComments)
63937 emitFlags |= 1536 /* NoComments */;
63938 if (emitFlags)
63939 ts.setEmitFlags(qualifiedName, emitFlags);
63940 return qualifiedName;
63941 }
63942 ts.getNamespaceMemberName = getNamespaceMemberName;
63943 function convertToFunctionBody(node, multiLine) {
63944 return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node);
63945 }
63946 ts.convertToFunctionBody = convertToFunctionBody;
63947 function convertFunctionDeclarationToExpression(node) {
63948 if (!node.body)
63949 return ts.Debug.fail();
63950 var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
63951 ts.setOriginalNode(updated, node);
63952 ts.setTextRange(updated, node);
63953 if (ts.getStartsOnNewLine(node)) {
63954 ts.setStartsOnNewLine(updated, /*newLine*/ true);
63955 }
63956 ts.aggregateTransformFlags(updated);
63957 return updated;
63958 }
63959 ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression;
63960 function isUseStrictPrologue(node) {
63961 return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
63962 }
63963 /**
63964 * Add any necessary prologue-directives into target statement-array.
63965 * The function needs to be called during each transformation step.
63966 * This function needs to be called whenever we transform the statement
63967 * list of a source file, namespace, or function-like body.
63968 *
63969 * @param target: result statements array
63970 * @param source: origin statements array
63971 * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
63972 * @param visitor: Optional callback used to visit any custom prologue directives.
63973 */
63974 function addPrologue(target, source, ensureUseStrict, visitor) {
63975 var offset = addStandardPrologue(target, source, ensureUseStrict);
63976 return addCustomPrologue(target, source, offset, visitor);
63977 }
63978 ts.addPrologue = addPrologue;
63979 /**
63980 * Add just the standard (string-expression) prologue-directives into target statement-array.
63981 * The function needs to be called during each transformation step.
63982 * This function needs to be called whenever we transform the statement
63983 * list of a source file, namespace, or function-like body.
63984 */
63985 function addStandardPrologue(target, source, ensureUseStrict) {
63986 ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
63987 var foundUseStrict = false;
63988 var statementOffset = 0;
63989 var numStatements = source.length;
63990 while (statementOffset < numStatements) {
63991 var statement = source[statementOffset];
63992 if (ts.isPrologueDirective(statement)) {
63993 if (isUseStrictPrologue(statement)) {
63994 foundUseStrict = true;
63995 }
63996 target.push(statement);
63997 }
63998 else {
63999 break;
64000 }
64001 statementOffset++;
64002 }
64003 if (ensureUseStrict && !foundUseStrict) {
64004 target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
64005 }
64006 return statementOffset;
64007 }
64008 ts.addStandardPrologue = addStandardPrologue;
64009 function addCustomPrologue(target, source, statementOffset, visitor) {
64010 var numStatements = source.length;
64011 while (statementOffset !== undefined && statementOffset < numStatements) {
64012 var statement = source[statementOffset];
64013 if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) {
64014 ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
64015 }
64016 else {
64017 break;
64018 }
64019 statementOffset++;
64020 }
64021 return statementOffset;
64022 }
64023 ts.addCustomPrologue = addCustomPrologue;
64024 function findUseStrictPrologue(statements) {
64025 for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
64026 var statement = statements_3[_i];
64027 if (ts.isPrologueDirective(statement)) {
64028 if (isUseStrictPrologue(statement)) {
64029 return statement;
64030 }
64031 }
64032 else {
64033 break;
64034 }
64035 }
64036 return undefined;
64037 }
64038 ts.findUseStrictPrologue = findUseStrictPrologue;
64039 function startsWithUseStrict(statements) {
64040 var firstStatement = ts.firstOrUndefined(statements);
64041 return firstStatement !== undefined
64042 && ts.isPrologueDirective(firstStatement)
64043 && isUseStrictPrologue(firstStatement);
64044 }
64045 ts.startsWithUseStrict = startsWithUseStrict;
64046 /**
64047 * Ensures "use strict" directive is added
64048 *
64049 * @param statements An array of statements
64050 */
64051 function ensureUseStrict(statements) {
64052 var foundUseStrict = findUseStrictPrologue(statements);
64053 if (!foundUseStrict) {
64054 return ts.setTextRange(ts.createNodeArray([
64055 startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
64056 ].concat(statements)), statements);
64057 }
64058 return statements;
64059 }
64060 ts.ensureUseStrict = ensureUseStrict;
64061 /**
64062 * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
64063 * order of operations.
64064 *
64065 * @param binaryOperator The operator for the BinaryExpression.
64066 * @param operand The operand for the BinaryExpression.
64067 * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
64068 * BinaryExpression.
64069 */
64070 function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
64071 var skipped = ts.skipPartiallyEmittedExpressions(operand);
64072 // If the resulting expression is already parenthesized, we do not need to do any further processing.
64073 if (skipped.kind === 195 /* ParenthesizedExpression */) {
64074 return operand;
64075 }
64076 return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
64077 ? ts.createParen(operand)
64078 : operand;
64079 }
64080 ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand;
64081 /**
64082 * Determines whether the operand to a BinaryExpression needs to be parenthesized.
64083 *
64084 * @param binaryOperator The operator for the BinaryExpression.
64085 * @param operand The operand for the BinaryExpression.
64086 * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
64087 * BinaryExpression.
64088 */
64089 function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
64090 // If the operand has lower precedence, then it needs to be parenthesized to preserve the
64091 // intent of the expression. For example, if the operand is `a + b` and the operator is
64092 // `*`, then we need to parenthesize the operand to preserve the intended order of
64093 // operations: `(a + b) * x`.
64094 //
64095 // If the operand has higher precedence, then it does not need to be parenthesized. For
64096 // example, if the operand is `a * b` and the operator is `+`, then we do not need to
64097 // parenthesize to preserve the intended order of operations: `a * b + x`.
64098 //
64099 // If the operand has the same precedence, then we need to check the associativity of
64100 // the operator based on whether this is the left or right operand of the expression.
64101 //
64102 // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
64103 // to preserve the intended order of operations: `x * (a / d)`
64104 //
64105 // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
64106 // the intended order of operations: `(a ** b) ** c`
64107 var binaryOperatorPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, binaryOperator);
64108 var binaryOperatorAssociativity = ts.getOperatorAssociativity(204 /* BinaryExpression */, binaryOperator);
64109 var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
64110 if (!isLeftSideOfBinary && operand.kind === 197 /* ArrowFunction */ && binaryOperatorPrecedence > 4) {
64111 // We need to parenthesize arrow functions on the right side to avoid it being
64112 // parsed as parenthesized expression: `a && (() => {})`
64113 return true;
64114 }
64115 var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
64116 switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
64117 case -1 /* LessThan */:
64118 // If the operand is the right side of a right-associative binary operation
64119 // and is a yield expression, then we do not need parentheses.
64120 if (!isLeftSideOfBinary
64121 && binaryOperatorAssociativity === 1 /* Right */
64122 && operand.kind === 207 /* YieldExpression */) {
64123 return false;
64124 }
64125 return true;
64126 case 1 /* GreaterThan */:
64127 return false;
64128 case 0 /* EqualTo */:
64129 if (isLeftSideOfBinary) {
64130 // No need to parenthesize the left operand when the binary operator is
64131 // left associative:
64132 // (a*b)/x -> a*b/x
64133 // (a**b)/x -> a**b/x
64134 //
64135 // Parentheses are needed for the left operand when the binary operator is
64136 // right associative:
64137 // (a/b)**x -> (a/b)**x
64138 // (a**b)**x -> (a**b)**x
64139 return binaryOperatorAssociativity === 1 /* Right */;
64140 }
64141 else {
64142 if (ts.isBinaryExpression(emittedOperand)
64143 && emittedOperand.operatorToken.kind === binaryOperator) {
64144 // No need to parenthesize the right operand when the binary operator and
64145 // operand are the same and one of the following:
64146 // x*(a*b) => x*a*b
64147 // x|(a|b) => x|a|b
64148 // x&(a&b) => x&a&b
64149 // x^(a^b) => x^a^b
64150 if (operatorHasAssociativeProperty(binaryOperator)) {
64151 return false;
64152 }
64153 // No need to parenthesize the right operand when the binary operator
64154 // is plus (+) if both the left and right operands consist solely of either
64155 // literals of the same kind or binary plus (+) expressions for literals of
64156 // the same kind (recursively).
64157 // "a"+(1+2) => "a"+(1+2)
64158 // "a"+("b"+"c") => "a"+"b"+"c"
64159 if (binaryOperator === 38 /* PlusToken */) {
64160 var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
64161 if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
64162 return false;
64163 }
64164 }
64165 }
64166 // No need to parenthesize the right operand when the operand is right
64167 // associative:
64168 // x/(a**b) -> x/a**b
64169 // x**(a**b) -> x**a**b
64170 //
64171 // Parentheses are needed for the right operand when the operand is left
64172 // associative:
64173 // x/(a*b) -> x/(a*b)
64174 // x**(a/b) -> x**(a/b)
64175 var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
64176 return operandAssociativity === 0 /* Left */;
64177 }
64178 }
64179 }
64180 /**
64181 * Determines whether a binary operator is mathematically associative.
64182 *
64183 * @param binaryOperator The binary operator.
64184 */
64185 function operatorHasAssociativeProperty(binaryOperator) {
64186 // The following operators are associative in JavaScript:
64187 // (a*b)*c -> a*(b*c) -> a*b*c
64188 // (a|b)|c -> a|(b|c) -> a|b|c
64189 // (a&b)&c -> a&(b&c) -> a&b&c
64190 // (a^b)^c -> a^(b^c) -> a^b^c
64191 //
64192 // While addition is associative in mathematics, JavaScript's `+` is not
64193 // guaranteed to be associative as it is overloaded with string concatenation.
64194 return binaryOperator === 40 /* AsteriskToken */
64195 || binaryOperator === 50 /* BarToken */
64196 || binaryOperator === 49 /* AmpersandToken */
64197 || binaryOperator === 51 /* CaretToken */;
64198 }
64199 /**
64200 * This function determines whether an expression consists of a homogeneous set of
64201 * literal expressions or binary plus expressions that all share the same literal kind.
64202 * It is used to determine whether the right-hand operand of a binary plus expression can be
64203 * emitted without parentheses.
64204 */
64205 function getLiteralKindOfBinaryPlusOperand(node) {
64206 node = ts.skipPartiallyEmittedExpressions(node);
64207 if (ts.isLiteralKind(node.kind)) {
64208 return node.kind;
64209 }
64210 if (node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 38 /* PlusToken */) {
64211 if (node.cachedLiteralKind !== undefined) {
64212 return node.cachedLiteralKind;
64213 }
64214 var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
64215 var literalKind = ts.isLiteralKind(leftKind)
64216 && leftKind === getLiteralKindOfBinaryPlusOperand(node.right)
64217 ? leftKind
64218 : 0 /* Unknown */;
64219 node.cachedLiteralKind = literalKind;
64220 return literalKind;
64221 }
64222 return 0 /* Unknown */;
64223 }
64224 function parenthesizeForConditionalHead(condition) {
64225 var conditionalPrecedence = ts.getOperatorPrecedence(205 /* ConditionalExpression */, 56 /* QuestionToken */);
64226 var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
64227 var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
64228 if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) {
64229 return ts.createParen(condition);
64230 }
64231 return condition;
64232 }
64233 ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead;
64234 function parenthesizeSubexpressionOfConditionalExpression(e) {
64235 // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
64236 // so in case when comma expression is introduced as a part of previous transformations
64237 // if should be wrapped in parens since comma operator has the lowest precedence
64238 var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
64239 return isCommaSequence(emittedExpression)
64240 ? ts.createParen(e)
64241 : e;
64242 }
64243 ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression;
64244 /**
64245 * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
64246 * has a lookahead restriction for `function`, `async function`, and `class`.
64247 *
64248 * Basically, that means we need to parenthesize in the following cases:
64249 *
64250 * - BinaryExpression of CommaToken
64251 * - CommaList (synthetic list of multiple comma expressions)
64252 * - FunctionExpression
64253 * - ClassExpression
64254 */
64255 function parenthesizeDefaultExpression(e) {
64256 var check = ts.skipPartiallyEmittedExpressions(e);
64257 var needsParens = isCommaSequence(check);
64258 if (!needsParens) {
64259 switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
64260 case 209 /* ClassExpression */:
64261 case 196 /* FunctionExpression */:
64262 needsParens = true;
64263 }
64264 }
64265 return needsParens ? ts.createParen(e) : e;
64266 }
64267 ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression;
64268 /**
64269 * Wraps an expression in parentheses if it is needed in order to use the expression
64270 * as the expression of a NewExpression node.
64271 *
64272 * @param expression The Expression node.
64273 */
64274 function parenthesizeForNew(expression) {
64275 var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
64276 switch (leftmostExpr.kind) {
64277 case 191 /* CallExpression */:
64278 return ts.createParen(expression);
64279 case 192 /* NewExpression */:
64280 return !leftmostExpr.arguments
64281 ? ts.createParen(expression)
64282 : expression;
64283 }
64284 return parenthesizeForAccess(expression);
64285 }
64286 ts.parenthesizeForNew = parenthesizeForNew;
64287 /**
64288 * Wraps an expression in parentheses if it is needed in order to use the expression for
64289 * property or element access.
64290 *
64291 * @param expr The expression node.
64292 */
64293 function parenthesizeForAccess(expression) {
64294 // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
64295 // to parenthesize the expression before a dot. The known exception is:
64296 //
64297 // NewExpression:
64298 // new C.x -> not the same as (new C).x
64299 //
64300 var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
64301 if (ts.isLeftHandSideExpression(emittedExpression)
64302 && (emittedExpression.kind !== 192 /* NewExpression */ || emittedExpression.arguments)) {
64303 return expression;
64304 }
64305 return ts.setTextRange(ts.createParen(expression), expression);
64306 }
64307 ts.parenthesizeForAccess = parenthesizeForAccess;
64308 function parenthesizePostfixOperand(operand) {
64309 return ts.isLeftHandSideExpression(operand)
64310 ? operand
64311 : ts.setTextRange(ts.createParen(operand), operand);
64312 }
64313 ts.parenthesizePostfixOperand = parenthesizePostfixOperand;
64314 function parenthesizePrefixOperand(operand) {
64315 return ts.isUnaryExpression(operand)
64316 ? operand
64317 : ts.setTextRange(ts.createParen(operand), operand);
64318 }
64319 ts.parenthesizePrefixOperand = parenthesizePrefixOperand;
64320 function parenthesizeListElements(elements) {
64321 var result;
64322 for (var i = 0; i < elements.length; i++) {
64323 var element = parenthesizeExpressionForList(elements[i]);
64324 if (result !== undefined || element !== elements[i]) {
64325 if (result === undefined) {
64326 result = elements.slice(0, i);
64327 }
64328 result.push(element);
64329 }
64330 }
64331 if (result !== undefined) {
64332 return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
64333 }
64334 return elements;
64335 }
64336 ts.parenthesizeListElements = parenthesizeListElements;
64337 function parenthesizeExpressionForList(expression) {
64338 var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
64339 var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
64340 var commaPrecedence = ts.getOperatorPrecedence(204 /* BinaryExpression */, 27 /* CommaToken */);
64341 return expressionPrecedence > commaPrecedence
64342 ? expression
64343 : ts.setTextRange(ts.createParen(expression), expression);
64344 }
64345 ts.parenthesizeExpressionForList = parenthesizeExpressionForList;
64346 function parenthesizeExpressionForExpressionStatement(expression) {
64347 var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
64348 if (ts.isCallExpression(emittedExpression)) {
64349 var callee = emittedExpression.expression;
64350 var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
64351 if (kind === 196 /* FunctionExpression */ || kind === 197 /* ArrowFunction */) {
64352 var mutableCall = ts.getMutableClone(emittedExpression);
64353 mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
64354 return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */);
64355 }
64356 }
64357 var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
64358 if (leftmostExpressionKind === 188 /* ObjectLiteralExpression */ || leftmostExpressionKind === 196 /* FunctionExpression */) {
64359 return ts.setTextRange(ts.createParen(expression), expression);
64360 }
64361 return expression;
64362 }
64363 ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement;
64364 function parenthesizeConditionalTypeMember(member) {
64365 return member.kind === 175 /* ConditionalType */ ? ts.createParenthesizedType(member) : member;
64366 }
64367 ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember;
64368 function parenthesizeElementTypeMember(member) {
64369 switch (member.kind) {
64370 case 173 /* UnionType */:
64371 case 174 /* IntersectionType */:
64372 case 165 /* FunctionType */:
64373 case 166 /* ConstructorType */:
64374 return ts.createParenthesizedType(member);
64375 }
64376 return parenthesizeConditionalTypeMember(member);
64377 }
64378 ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember;
64379 function parenthesizeArrayTypeMember(member) {
64380 switch (member.kind) {
64381 case 167 /* TypeQuery */:
64382 case 179 /* TypeOperator */:
64383 case 176 /* InferType */:
64384 return ts.createParenthesizedType(member);
64385 }
64386 return parenthesizeElementTypeMember(member);
64387 }
64388 ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember;
64389 function parenthesizeElementTypeMembers(members) {
64390 return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember));
64391 }
64392 ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers;
64393 function parenthesizeTypeParameters(typeParameters) {
64394 if (ts.some(typeParameters)) {
64395 var params = [];
64396 for (var i = 0; i < typeParameters.length; ++i) {
64397 var entry = typeParameters[i];
64398 params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ?
64399 ts.createParenthesizedType(entry) :
64400 entry);
64401 }
64402 return ts.createNodeArray(params);
64403 }
64404 }
64405 ts.parenthesizeTypeParameters = parenthesizeTypeParameters;
64406 function getLeftmostExpression(node, stopAtCallExpressions) {
64407 while (true) {
64408 switch (node.kind) {
64409 case 203 /* PostfixUnaryExpression */:
64410 node = node.operand;
64411 continue;
64412 case 204 /* BinaryExpression */:
64413 node = node.left;
64414 continue;
64415 case 205 /* ConditionalExpression */:
64416 node = node.condition;
64417 continue;
64418 case 193 /* TaggedTemplateExpression */:
64419 node = node.tag;
64420 continue;
64421 case 191 /* CallExpression */:
64422 if (stopAtCallExpressions) {
64423 return node;
64424 }
64425 // falls through
64426 case 212 /* AsExpression */:
64427 case 190 /* ElementAccessExpression */:
64428 case 189 /* PropertyAccessExpression */:
64429 case 213 /* NonNullExpression */:
64430 case 313 /* PartiallyEmittedExpression */:
64431 node = node.expression;
64432 continue;
64433 }
64434 return node;
64435 }
64436 }
64437 function parenthesizeConciseBody(body) {
64438 if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 188 /* ObjectLiteralExpression */)) {
64439 return ts.setTextRange(ts.createParen(body), body);
64440 }
64441 return body;
64442 }
64443 ts.parenthesizeConciseBody = parenthesizeConciseBody;
64444 function isCommaSequence(node) {
64445 return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
64446 node.kind === 314 /* CommaListExpression */;
64447 }
64448 ts.isCommaSequence = isCommaSequence;
64449 var OuterExpressionKinds;
64450 (function (OuterExpressionKinds) {
64451 OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
64452 OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions";
64453 OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions";
64454 OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All";
64455 })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
64456 function isOuterExpression(node, kinds) {
64457 if (kinds === void 0) { kinds = 7 /* All */; }
64458 switch (node.kind) {
64459 case 195 /* ParenthesizedExpression */:
64460 return (kinds & 1 /* Parentheses */) !== 0;
64461 case 194 /* TypeAssertionExpression */:
64462 case 212 /* AsExpression */:
64463 case 213 /* NonNullExpression */:
64464 return (kinds & 2 /* Assertions */) !== 0;
64465 case 313 /* PartiallyEmittedExpression */:
64466 return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
64467 }
64468 return false;
64469 }
64470 ts.isOuterExpression = isOuterExpression;
64471 function skipOuterExpressions(node, kinds) {
64472 if (kinds === void 0) { kinds = 7 /* All */; }
64473 var previousNode;
64474 do {
64475 previousNode = node;
64476 if (kinds & 1 /* Parentheses */) {
64477 node = ts.skipParentheses(node);
64478 }
64479 if (kinds & 2 /* Assertions */) {
64480 node = skipAssertions(node);
64481 }
64482 if (kinds & 4 /* PartiallyEmittedExpressions */) {
64483 node = ts.skipPartiallyEmittedExpressions(node);
64484 }
64485 } while (previousNode !== node);
64486 return node;
64487 }
64488 ts.skipOuterExpressions = skipOuterExpressions;
64489 function skipAssertions(node) {
64490 while (ts.isAssertionExpression(node) || node.kind === 213 /* NonNullExpression */) {
64491 node = node.expression;
64492 }
64493 return node;
64494 }
64495 ts.skipAssertions = skipAssertions;
64496 function updateOuterExpression(outerExpression, expression) {
64497 switch (outerExpression.kind) {
64498 case 195 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression);
64499 case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
64500 case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
64501 case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
64502 case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
64503 }
64504 }
64505 /**
64506 * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
64507 *
64508 * A parenthesized expression can be ignored when all of the following are true:
64509 *
64510 * - It's `pos` and `end` are not -1
64511 * - It does not have a custom source map range
64512 * - It does not have a custom comment range
64513 * - It does not have synthetic leading or trailing comments
64514 *
64515 * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
64516 * the expression to maintain precedence, a new parenthesized expression should be created automatically when
64517 * the containing expression is created/updated.
64518 */
64519 function isIgnorableParen(node) {
64520 return node.kind === 195 /* ParenthesizedExpression */
64521 && ts.nodeIsSynthesized(node)
64522 && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
64523 && ts.nodeIsSynthesized(ts.getCommentRange(node))
64524 && !ts.some(ts.getSyntheticLeadingComments(node))
64525 && !ts.some(ts.getSyntheticTrailingComments(node));
64526 }
64527 function recreateOuterExpressions(outerExpression, innerExpression, kinds) {
64528 if (kinds === void 0) { kinds = 7 /* All */; }
64529 if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
64530 return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression));
64531 }
64532 return innerExpression;
64533 }
64534 ts.recreateOuterExpressions = recreateOuterExpressions;
64535 function startOnNewLine(node) {
64536 return ts.setStartsOnNewLine(node, /*newLine*/ true);
64537 }
64538 ts.startOnNewLine = startOnNewLine;
64539 function getExternalHelpersModuleName(node) {
64540 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
64541 var emitNode = parseNode && parseNode.emitNode;
64542 return emitNode && emitNode.externalHelpersModuleName;
64543 }
64544 ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
64545 function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
64546 if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
64547 var externalHelpersModuleName = getExternalHelpersModuleName(node);
64548 if (externalHelpersModuleName) {
64549 return externalHelpersModuleName;
64550 }
64551 var moduleKind = ts.getEmitModuleKind(compilerOptions);
64552 var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
64553 && moduleKind !== ts.ModuleKind.System
64554 && moduleKind !== ts.ModuleKind.ES2015
64555 && moduleKind !== ts.ModuleKind.ESNext;
64556 if (!create) {
64557 var helpers = ts.getEmitHelpers(node);
64558 if (helpers) {
64559 for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
64560 var helper = helpers_2[_i];
64561 if (!helper.scoped) {
64562 create = true;
64563 break;
64564 }
64565 }
64566 }
64567 }
64568 if (create) {
64569 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
64570 var emitNode = ts.getOrCreateEmitNode(parseNode);
64571 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText));
64572 }
64573 }
64574 }
64575 ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
64576 /**
64577 * Get the name of that target module from an import or export declaration
64578 */
64579 function getLocalNameForExternalImport(node, sourceFile) {
64580 var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
64581 if (namespaceDeclaration && !ts.isDefaultImport(node)) {
64582 var name = namespaceDeclaration.name;
64583 return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
64584 }
64585 if (node.kind === 249 /* ImportDeclaration */ && node.importClause) {
64586 return ts.getGeneratedNameForNode(node);
64587 }
64588 if (node.kind === 255 /* ExportDeclaration */ && node.moduleSpecifier) {
64589 return ts.getGeneratedNameForNode(node);
64590 }
64591 return undefined;
64592 }
64593 ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
64594 /**
64595 * Get the name of a target module from an import/export declaration as should be written in the emitted output.
64596 * The emitted output name can be different from the input if:
64597 * 1. The module has a /// <amd-module name="<new name>" />
64598 * 2. --out or --outFile is used, making the name relative to the rootDir
64599 * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
64600 * Otherwise, a new StringLiteral node representing the module name will be returned.
64601 */
64602 function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) {
64603 var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
64604 if (moduleName.kind === 10 /* StringLiteral */) {
64605 return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
64606 || tryRenameExternalModule(moduleName, sourceFile)
64607 || ts.getSynthesizedClone(moduleName);
64608 }
64609 return undefined;
64610 }
64611 ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
64612 /**
64613 * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
64614 * Here we check if alternative name was provided for a given moduleName and return it if possible.
64615 */
64616 function tryRenameExternalModule(moduleName, sourceFile) {
64617 var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
64618 return rename && ts.createLiteral(rename);
64619 }
64620 /**
64621 * Get the name of a module as should be written in the emitted output.
64622 * The emitted output name can be different from the input if:
64623 * 1. The module has a /// <amd-module name="<new name>" />
64624 * 2. --out or --outFile is used, making the name relative to the rootDir
64625 * Otherwise, a new StringLiteral node representing the module name will be returned.
64626 */
64627 function tryGetModuleNameFromFile(file, host, options) {
64628 if (!file) {
64629 return undefined;
64630 }
64631 if (file.moduleName) {
64632 return ts.createLiteral(file.moduleName);
64633 }
64634 if (!file.isDeclarationFile && (options.out || options.outFile)) {
64635 return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
64636 }
64637 return undefined;
64638 }
64639 ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
64640 function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) {
64641 return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
64642 }
64643 /**
64644 * Gets the initializer of an BindingOrAssignmentElement.
64645 */
64646 function getInitializerOfBindingOrAssignmentElement(bindingElement) {
64647 if (ts.isDeclarationBindingElement(bindingElement)) {
64648 // `1` in `let { a = 1 } = ...`
64649 // `1` in `let { a: b = 1 } = ...`
64650 // `1` in `let { a: {b} = 1 } = ...`
64651 // `1` in `let { a: [b] = 1 } = ...`
64652 // `1` in `let [a = 1] = ...`
64653 // `1` in `let [{a} = 1] = ...`
64654 // `1` in `let [[a] = 1] = ...`
64655 return bindingElement.initializer;
64656 }
64657 if (ts.isPropertyAssignment(bindingElement)) {
64658 // `1` in `({ a: b = 1 } = ...)`
64659 // `1` in `({ a: {b} = 1 } = ...)`
64660 // `1` in `({ a: [b] = 1 } = ...)`
64661 var initializer = bindingElement.initializer;
64662 return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
64663 ? initializer.right
64664 : undefined;
64665 }
64666 if (ts.isShorthandPropertyAssignment(bindingElement)) {
64667 // `1` in `({ a = 1 } = ...)`
64668 return bindingElement.objectAssignmentInitializer;
64669 }
64670 if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
64671 // `1` in `[a = 1] = ...`
64672 // `1` in `[{a} = 1] = ...`
64673 // `1` in `[[a] = 1] = ...`
64674 return bindingElement.right;
64675 }
64676 if (ts.isSpreadElement(bindingElement)) {
64677 // Recovery consistent with existing emit.
64678 return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
64679 }
64680 }
64681 ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
64682 /**
64683 * Gets the name of an BindingOrAssignmentElement.
64684 */
64685 function getTargetOfBindingOrAssignmentElement(bindingElement) {
64686 if (ts.isDeclarationBindingElement(bindingElement)) {
64687 // `a` in `let { a } = ...`
64688 // `a` in `let { a = 1 } = ...`
64689 // `b` in `let { a: b } = ...`
64690 // `b` in `let { a: b = 1 } = ...`
64691 // `a` in `let { ...a } = ...`
64692 // `{b}` in `let { a: {b} } = ...`
64693 // `{b}` in `let { a: {b} = 1 } = ...`
64694 // `[b]` in `let { a: [b] } = ...`
64695 // `[b]` in `let { a: [b] = 1 } = ...`
64696 // `a` in `let [a] = ...`
64697 // `a` in `let [a = 1] = ...`
64698 // `a` in `let [...a] = ...`
64699 // `{a}` in `let [{a}] = ...`
64700 // `{a}` in `let [{a} = 1] = ...`
64701 // `[a]` in `let [[a]] = ...`
64702 // `[a]` in `let [[a] = 1] = ...`
64703 return bindingElement.name;
64704 }
64705 if (ts.isObjectLiteralElementLike(bindingElement)) {
64706 switch (bindingElement.kind) {
64707 case 275 /* PropertyAssignment */:
64708 // `b` in `({ a: b } = ...)`
64709 // `b` in `({ a: b = 1 } = ...)`
64710 // `{b}` in `({ a: {b} } = ...)`
64711 // `{b}` in `({ a: {b} = 1 } = ...)`
64712 // `[b]` in `({ a: [b] } = ...)`
64713 // `[b]` in `({ a: [b] = 1 } = ...)`
64714 // `b.c` in `({ a: b.c } = ...)`
64715 // `b.c` in `({ a: b.c = 1 } = ...)`
64716 // `b[0]` in `({ a: b[0] } = ...)`
64717 // `b[0]` in `({ a: b[0] = 1 } = ...)`
64718 return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
64719 case 276 /* ShorthandPropertyAssignment */:
64720 // `a` in `({ a } = ...)`
64721 // `a` in `({ a = 1 } = ...)`
64722 return bindingElement.name;
64723 case 277 /* SpreadAssignment */:
64724 // `a` in `({ ...a } = ...)`
64725 return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
64726 }
64727 // no target
64728 return undefined;
64729 }
64730 if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
64731 // `a` in `[a = 1] = ...`
64732 // `{a}` in `[{a} = 1] = ...`
64733 // `[a]` in `[[a] = 1] = ...`
64734 // `a.b` in `[a.b = 1] = ...`
64735 // `a[0]` in `[a[0] = 1] = ...`
64736 return getTargetOfBindingOrAssignmentElement(bindingElement.left);
64737 }
64738 if (ts.isSpreadElement(bindingElement)) {
64739 // `a` in `[...a] = ...`
64740 return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
64741 }
64742 // `a` in `[a] = ...`
64743 // `{a}` in `[{a}] = ...`
64744 // `[a]` in `[[a]] = ...`
64745 // `a.b` in `[a.b] = ...`
64746 // `a[0]` in `[a[0]] = ...`
64747 return bindingElement;
64748 }
64749 ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
64750 /**
64751 * Determines whether an BindingOrAssignmentElement is a rest element.
64752 */
64753 function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
64754 switch (bindingElement.kind) {
64755 case 151 /* Parameter */:
64756 case 186 /* BindingElement */:
64757 // `...` in `let [...a] = ...`
64758 return bindingElement.dotDotDotToken;
64759 case 208 /* SpreadElement */:
64760 case 277 /* SpreadAssignment */:
64761 // `...` in `[...a] = ...`
64762 return bindingElement;
64763 }
64764 return undefined;
64765 }
64766 ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
64767 /**
64768 * Gets the property name of a BindingOrAssignmentElement
64769 */
64770 function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
64771 switch (bindingElement.kind) {
64772 case 186 /* BindingElement */:
64773 // `a` in `let { a: b } = ...`
64774 // `[a]` in `let { [a]: b } = ...`
64775 // `"a"` in `let { "a": b } = ...`
64776 // `1` in `let { 1: b } = ...`
64777 if (bindingElement.propertyName) {
64778 var propertyName = bindingElement.propertyName;
64779 return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
64780 ? propertyName.expression
64781 : propertyName;
64782 }
64783 break;
64784 case 275 /* PropertyAssignment */:
64785 // `a` in `({ a: b } = ...)`
64786 // `[a]` in `({ [a]: b } = ...)`
64787 // `"a"` in `({ "a": b } = ...)`
64788 // `1` in `({ 1: b } = ...)`
64789 if (bindingElement.name) {
64790 var propertyName = bindingElement.name;
64791 return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
64792 ? propertyName.expression
64793 : propertyName;
64794 }
64795 break;
64796 case 277 /* SpreadAssignment */:
64797 // `a` in `({ ...a } = ...)`
64798 return bindingElement.name;
64799 }
64800 var target = getTargetOfBindingOrAssignmentElement(bindingElement);
64801 if (target && ts.isPropertyName(target)) {
64802 return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression)
64803 ? target.expression
64804 : target;
64805 }
64806 ts.Debug.fail("Invalid property name for binding element.");
64807 }
64808 ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
64809 function isStringOrNumericLiteral(node) {
64810 var kind = node.kind;
64811 return kind === 10 /* StringLiteral */
64812 || kind === 8 /* NumericLiteral */;
64813 }
64814 /**
64815 * Gets the elements of a BindingOrAssignmentPattern
64816 */
64817 function getElementsOfBindingOrAssignmentPattern(name) {
64818 switch (name.kind) {
64819 case 184 /* ObjectBindingPattern */:
64820 case 185 /* ArrayBindingPattern */:
64821 case 187 /* ArrayLiteralExpression */:
64822 // `a` in `{a}`
64823 // `a` in `[a]`
64824 return name.elements;
64825 case 188 /* ObjectLiteralExpression */:
64826 // `a` in `{a}`
64827 return name.properties;
64828 }
64829 }
64830 ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
64831 function convertToArrayAssignmentElement(element) {
64832 if (ts.isBindingElement(element)) {
64833 if (element.dotDotDotToken) {
64834 ts.Debug.assertNode(element.name, ts.isIdentifier);
64835 return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
64836 }
64837 var expression = convertToAssignmentElementTarget(element.name);
64838 return element.initializer
64839 ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
64840 : expression;
64841 }
64842 ts.Debug.assertNode(element, ts.isExpression);
64843 return element;
64844 }
64845 ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement;
64846 function convertToObjectAssignmentElement(element) {
64847 if (ts.isBindingElement(element)) {
64848 if (element.dotDotDotToken) {
64849 ts.Debug.assertNode(element.name, ts.isIdentifier);
64850 return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
64851 }
64852 if (element.propertyName) {
64853 var expression = convertToAssignmentElementTarget(element.name);
64854 return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element);
64855 }
64856 ts.Debug.assertNode(element.name, ts.isIdentifier);
64857 return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
64858 }
64859 ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
64860 return element;
64861 }
64862 ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement;
64863 function convertToAssignmentPattern(node) {
64864 switch (node.kind) {
64865 case 185 /* ArrayBindingPattern */:
64866 case 187 /* ArrayLiteralExpression */:
64867 return convertToArrayAssignmentPattern(node);
64868 case 184 /* ObjectBindingPattern */:
64869 case 188 /* ObjectLiteralExpression */:
64870 return convertToObjectAssignmentPattern(node);
64871 }
64872 }
64873 ts.convertToAssignmentPattern = convertToAssignmentPattern;
64874 function convertToObjectAssignmentPattern(node) {
64875 if (ts.isObjectBindingPattern(node)) {
64876 return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
64877 }
64878 ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
64879 return node;
64880 }
64881 ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern;
64882 function convertToArrayAssignmentPattern(node) {
64883 if (ts.isArrayBindingPattern(node)) {
64884 return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
64885 }
64886 ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
64887 return node;
64888 }
64889 ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern;
64890 function convertToAssignmentElementTarget(node) {
64891 if (ts.isBindingPattern(node)) {
64892 return convertToAssignmentPattern(node);
64893 }
64894 ts.Debug.assertNode(node, ts.isExpression);
64895 return node;
64896 }
64897 ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget;
64898})(ts || (ts = {}));
64899var ts;
64900(function (ts) {
64901 var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
64902 function visitNode(node, visitor, test, lift) {
64903 if (node === undefined || visitor === undefined) {
64904 return node;
64905 }
64906 ts.aggregateTransformFlags(node);
64907 var visited = visitor(node);
64908 if (visited === node) {
64909 return node;
64910 }
64911 var visitedNode;
64912 if (visited === undefined) {
64913 return undefined;
64914 }
64915 else if (ts.isArray(visited)) {
64916 visitedNode = (lift || extractSingleNode)(visited);
64917 }
64918 else {
64919 visitedNode = visited;
64920 }
64921 ts.Debug.assertNode(visitedNode, test);
64922 ts.aggregateTransformFlags(visitedNode);
64923 return visitedNode;
64924 }
64925 ts.visitNode = visitNode;
64926 /**
64927 * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
64928 *
64929 * @param nodes The NodeArray to visit.
64930 * @param visitor The callback used to visit a Node.
64931 * @param test A node test to execute for each node.
64932 * @param start An optional value indicating the starting offset at which to start visiting.
64933 * @param count An optional value indicating the maximum number of nodes to visit.
64934 */
64935 function visitNodes(nodes, visitor, test, start, count) {
64936 if (nodes === undefined || visitor === undefined) {
64937 return nodes;
64938 }
64939 var updated;
64940 // Ensure start and count have valid values
64941 var length = nodes.length;
64942 if (start === undefined || start < 0) {
64943 start = 0;
64944 }
64945 if (count === undefined || count > length - start) {
64946 count = length - start;
64947 }
64948 if (start > 0 || count < length) {
64949 // If we are not visiting all of the original nodes, we must always create a new array.
64950 // Since this is a fragment of a node array, we do not copy over the previous location
64951 // and will only copy over `hasTrailingComma` if we are including the last element.
64952 updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
64953 }
64954 // Visit each original node.
64955 for (var i = 0; i < count; i++) {
64956 var node = nodes[i + start];
64957 ts.aggregateTransformFlags(node);
64958 var visited = node !== undefined ? visitor(node) : undefined;
64959 if (updated !== undefined || visited === undefined || visited !== node) {
64960 if (updated === undefined) {
64961 // Ensure we have a copy of `nodes`, up to the current index.
64962 updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
64963 ts.setTextRange(updated, nodes);
64964 }
64965 if (visited) {
64966 if (ts.isArray(visited)) {
64967 for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
64968 var visitedNode = visited_1[_i];
64969 ts.Debug.assertNode(visitedNode, test);
64970 ts.aggregateTransformFlags(visitedNode);
64971 updated.push(visitedNode);
64972 }
64973 }
64974 else {
64975 ts.Debug.assertNode(visited, test);
64976 ts.aggregateTransformFlags(visited);
64977 updated.push(visited);
64978 }
64979 }
64980 }
64981 }
64982 return updated || nodes;
64983 }
64984 ts.visitNodes = visitNodes;
64985 /**
64986 * Starts a new lexical environment and visits a statement list, ending the lexical environment
64987 * and merging hoisted declarations upon completion.
64988 */
64989 function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
64990 context.startLexicalEnvironment();
64991 statements = visitNodes(statements, visitor, ts.isStatement, start);
64992 if (ensureUseStrict && !ts.startsWithUseStrict(statements)) {
64993 statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements);
64994 }
64995 var declarations = context.endLexicalEnvironment();
64996 return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements);
64997 }
64998 ts.visitLexicalEnvironment = visitLexicalEnvironment;
64999 /**
65000 * Starts a new lexical environment and visits a parameter list, suspending the lexical
65001 * environment upon completion.
65002 */
65003 function visitParameterList(nodes, visitor, context, nodesVisitor) {
65004 if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
65005 context.startLexicalEnvironment();
65006 var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
65007 context.suspendLexicalEnvironment();
65008 return updated;
65009 }
65010 ts.visitParameterList = visitParameterList;
65011 function visitFunctionBody(node, visitor, context) {
65012 context.resumeLexicalEnvironment();
65013 var updated = visitNode(node, visitor, ts.isConciseBody);
65014 var declarations = context.endLexicalEnvironment();
65015 if (ts.some(declarations)) {
65016 var block = ts.convertToFunctionBody(updated);
65017 var statements = ts.mergeLexicalEnvironment(block.statements, declarations);
65018 return ts.updateBlock(block, statements);
65019 }
65020 return updated;
65021 }
65022 ts.visitFunctionBody = visitFunctionBody;
65023 function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) {
65024 if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
65025 if (node === undefined) {
65026 return undefined;
65027 }
65028 var kind = node.kind;
65029 // No need to visit nodes with no children.
65030 if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */) || kind === 178 /* ThisType */) {
65031 return node;
65032 }
65033 switch (kind) {
65034 // Names
65035 case 72 /* Identifier */:
65036 return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
65037 case 148 /* QualifiedName */:
65038 return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier));
65039 case 149 /* ComputedPropertyName */:
65040 return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
65041 // Signature elements
65042 case 150 /* TypeParameter */:
65043 return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode));
65044 case 151 /* Parameter */:
65045 return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
65046 case 152 /* Decorator */:
65047 return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
65048 // Type elements
65049 case 153 /* PropertySignature */:
65050 return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
65051 case 154 /* PropertyDeclaration */:
65052 return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
65053 case 155 /* MethodSignature */:
65054 return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken));
65055 case 156 /* MethodDeclaration */:
65056 return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
65057 case 157 /* Constructor */:
65058 return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
65059 case 158 /* GetAccessor */:
65060 return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
65061 case 159 /* SetAccessor */:
65062 return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
65063 case 160 /* CallSignature */:
65064 return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
65065 case 161 /* ConstructSignature */:
65066 return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
65067 case 162 /* IndexSignature */:
65068 return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
65069 // Types
65070 case 163 /* TypePredicate */:
65071 return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode));
65072 case 164 /* TypeReference */:
65073 return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
65074 case 165 /* FunctionType */:
65075 return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
65076 case 166 /* ConstructorType */:
65077 return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
65078 case 167 /* TypeQuery */:
65079 return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName));
65080 case 168 /* TypeLiteral */:
65081 return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
65082 case 169 /* ArrayType */:
65083 return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode));
65084 case 170 /* TupleType */:
65085 return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode));
65086 case 171 /* OptionalType */:
65087 return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
65088 case 172 /* RestType */:
65089 return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
65090 case 173 /* UnionType */:
65091 return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
65092 case 174 /* IntersectionType */:
65093 return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
65094 case 175 /* ConditionalType */:
65095 return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode));
65096 case 176 /* InferType */:
65097 return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
65098 case 183 /* ImportType */:
65099 return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
65100 case 177 /* ParenthesizedType */:
65101 return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode));
65102 case 179 /* TypeOperator */:
65103 return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode));
65104 case 180 /* IndexedAccessType */:
65105 return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode));
65106 case 181 /* MappedType */:
65107 return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode));
65108 case 182 /* LiteralType */:
65109 return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression));
65110 // Binding patterns
65111 case 184 /* ObjectBindingPattern */:
65112 return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
65113 case 185 /* ArrayBindingPattern */:
65114 return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
65115 case 186 /* BindingElement */:
65116 return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression));
65117 // Expression
65118 case 187 /* ArrayLiteralExpression */:
65119 return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression));
65120 case 188 /* ObjectLiteralExpression */:
65121 return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
65122 case 189 /* PropertyAccessExpression */:
65123 return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier));
65124 case 190 /* ElementAccessExpression */:
65125 return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
65126 case 191 /* CallExpression */:
65127 return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
65128 case 192 /* NewExpression */:
65129 return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
65130 case 193 /* TaggedTemplateExpression */:
65131 return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
65132 case 194 /* TypeAssertionExpression */:
65133 return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
65134 case 195 /* ParenthesizedExpression */:
65135 return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
65136 case 196 /* FunctionExpression */:
65137 return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
65138 case 197 /* ArrowFunction */:
65139 return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context));
65140 case 198 /* DeleteExpression */:
65141 return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
65142 case 199 /* TypeOfExpression */:
65143 return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
65144 case 200 /* VoidExpression */:
65145 return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
65146 case 201 /* AwaitExpression */:
65147 return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
65148 case 202 /* PrefixUnaryExpression */:
65149 return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
65150 case 203 /* PostfixUnaryExpression */:
65151 return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
65152 case 204 /* BinaryExpression */:
65153 return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken));
65154 case 205 /* ConditionalExpression */:
65155 return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression));
65156 case 206 /* TemplateExpression */:
65157 return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
65158 case 207 /* YieldExpression */:
65159 return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression));
65160 case 208 /* SpreadElement */:
65161 return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
65162 case 209 /* ClassExpression */:
65163 return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
65164 case 211 /* ExpressionWithTypeArguments */:
65165 return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
65166 case 212 /* AsExpression */:
65167 return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode));
65168 case 213 /* NonNullExpression */:
65169 return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression));
65170 case 214 /* MetaProperty */:
65171 return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier));
65172 // Misc
65173 case 216 /* TemplateSpan */:
65174 return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
65175 // Element
65176 case 218 /* Block */:
65177 return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
65178 case 219 /* VariableStatement */:
65179 return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
65180 case 221 /* ExpressionStatement */:
65181 return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression));
65182 case 222 /* IfStatement */:
65183 return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock));
65184 case 223 /* DoStatement */:
65185 return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
65186 case 224 /* WhileStatement */:
65187 return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
65188 case 225 /* ForStatement */:
65189 return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
65190 case 226 /* ForInStatement */:
65191 return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
65192 case 227 /* ForOfStatement */:
65193 return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
65194 case 228 /* ContinueStatement */:
65195 return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier));
65196 case 229 /* BreakStatement */:
65197 return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier));
65198 case 230 /* ReturnStatement */:
65199 return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression));
65200 case 231 /* WithStatement */:
65201 return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
65202 case 232 /* SwitchStatement */:
65203 return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
65204 case 233 /* LabeledStatement */:
65205 return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
65206 case 234 /* ThrowStatement */:
65207 return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
65208 case 235 /* TryStatement */:
65209 return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock));
65210 case 237 /* VariableDeclaration */:
65211 return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
65212 case 238 /* VariableDeclarationList */:
65213 return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
65214 case 239 /* FunctionDeclaration */:
65215 return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
65216 case 240 /* ClassDeclaration */:
65217 return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
65218 case 241 /* InterfaceDeclaration */:
65219 return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement));
65220 case 242 /* TypeAliasDeclaration */:
65221 return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
65222 case 243 /* EnumDeclaration */:
65223 return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember));
65224 case 244 /* ModuleDeclaration */:
65225 return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody));
65226 case 245 /* ModuleBlock */:
65227 return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
65228 case 246 /* CaseBlock */:
65229 return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
65230 case 247 /* NamespaceExportDeclaration */:
65231 return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier));
65232 case 248 /* ImportEqualsDeclaration */:
65233 return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference));
65234 case 249 /* ImportDeclaration */:
65235 return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression));
65236 case 250 /* ImportClause */:
65237 return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings));
65238 case 251 /* NamespaceImport */:
65239 return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
65240 case 252 /* NamedImports */:
65241 return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
65242 case 253 /* ImportSpecifier */:
65243 return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
65244 case 254 /* ExportAssignment */:
65245 return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
65246 case 255 /* ExportDeclaration */:
65247 return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression));
65248 case 256 /* NamedExports */:
65249 return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
65250 case 257 /* ExportSpecifier */:
65251 return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
65252 // Module references
65253 case 259 /* ExternalModuleReference */:
65254 return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression));
65255 // JSX
65256 case 260 /* JsxElement */:
65257 return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
65258 case 261 /* JsxSelfClosingElement */:
65259 return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
65260 case 262 /* JsxOpeningElement */:
65261 return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
65262 case 263 /* JsxClosingElement */:
65263 return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
65264 case 264 /* JsxFragment */:
65265 return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment));
65266 case 267 /* JsxAttribute */:
65267 return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
65268 case 268 /* JsxAttributes */:
65269 return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
65270 case 269 /* JsxSpreadAttribute */:
65271 return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
65272 case 270 /* JsxExpression */:
65273 return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
65274 // Clauses
65275 case 271 /* CaseClause */:
65276 return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
65277 case 272 /* DefaultClause */:
65278 return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
65279 case 273 /* HeritageClause */:
65280 return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
65281 case 274 /* CatchClause */:
65282 return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
65283 // Property assignments
65284 case 275 /* PropertyAssignment */:
65285 return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
65286 case 276 /* ShorthandPropertyAssignment */:
65287 return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
65288 case 277 /* SpreadAssignment */:
65289 return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
65290 // Enum
65291 case 278 /* EnumMember */:
65292 return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
65293 // Top-level nodes
65294 case 284 /* SourceFile */:
65295 return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
65296 // Transformation nodes
65297 case 313 /* PartiallyEmittedExpression */:
65298 return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
65299 case 314 /* CommaListExpression */:
65300 return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
65301 default:
65302 // No need to visit nodes with no children.
65303 return node;
65304 }
65305 }
65306 ts.visitEachChild = visitEachChild;
65307 /**
65308 * Extracts the single node from a NodeArray.
65309 *
65310 * @param nodes The NodeArray.
65311 */
65312 function extractSingleNode(nodes) {
65313 ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
65314 return ts.singleOrUndefined(nodes);
65315 }
65316})(ts || (ts = {}));
65317/* @internal */
65318(function (ts) {
65319 function reduceNode(node, f, initial) {
65320 return node ? f(initial, node) : initial;
65321 }
65322 function reduceNodeArray(nodes, f, initial) {
65323 return nodes ? f(initial, nodes) : initial;
65324 }
65325 /**
65326 * Similar to `reduceLeft`, performs a reduction against each child of a node.
65327 * NOTE: Unlike `forEachChild`, this does *not* visit every node.
65328 *
65329 * @param node The node containing the children to reduce.
65330 * @param initial The initial value to supply to the reduction.
65331 * @param f The callback function
65332 */
65333 function reduceEachChild(node, initial, cbNode, cbNodeArray) {
65334 if (node === undefined) {
65335 return initial;
65336 }
65337 var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft;
65338 var cbNodes = cbNodeArray || cbNode;
65339 var kind = node.kind;
65340 // No need to visit nodes with no children.
65341 if ((kind > 0 /* FirstToken */ && kind <= 147 /* LastToken */)) {
65342 return initial;
65343 }
65344 // We do not yet support types.
65345 if ((kind >= 163 /* TypePredicate */ && kind <= 182 /* LiteralType */)) {
65346 return initial;
65347 }
65348 var result = initial;
65349 switch (node.kind) {
65350 // Leaf nodes
65351 case 217 /* SemicolonClassElement */:
65352 case 220 /* EmptyStatement */:
65353 case 210 /* OmittedExpression */:
65354 case 236 /* DebuggerStatement */:
65355 case 312 /* NotEmittedStatement */:
65356 // No need to visit nodes with no children.
65357 break;
65358 // Names
65359 case 148 /* QualifiedName */:
65360 result = reduceNode(node.left, cbNode, result);
65361 result = reduceNode(node.right, cbNode, result);
65362 break;
65363 case 149 /* ComputedPropertyName */:
65364 result = reduceNode(node.expression, cbNode, result);
65365 break;
65366 // Signature elements
65367 case 151 /* Parameter */:
65368 result = reduceNodes(node.decorators, cbNodes, result);
65369 result = reduceNodes(node.modifiers, cbNodes, result);
65370 result = reduceNode(node.name, cbNode, result);
65371 result = reduceNode(node.type, cbNode, result);
65372 result = reduceNode(node.initializer, cbNode, result);
65373 break;
65374 case 152 /* Decorator */:
65375 result = reduceNode(node.expression, cbNode, result);
65376 break;
65377 // Type member
65378 case 153 /* PropertySignature */:
65379 result = reduceNodes(node.modifiers, cbNodes, result);
65380 result = reduceNode(node.name, cbNode, result);
65381 result = reduceNode(node.questionToken, cbNode, result);
65382 result = reduceNode(node.type, cbNode, result);
65383 result = reduceNode(node.initializer, cbNode, result);
65384 break;
65385 case 154 /* PropertyDeclaration */:
65386 result = reduceNodes(node.decorators, cbNodes, result);
65387 result = reduceNodes(node.modifiers, cbNodes, result);
65388 result = reduceNode(node.name, cbNode, result);
65389 result = reduceNode(node.type, cbNode, result);
65390 result = reduceNode(node.initializer, cbNode, result);
65391 break;
65392 case 156 /* MethodDeclaration */:
65393 result = reduceNodes(node.decorators, cbNodes, result);
65394 result = reduceNodes(node.modifiers, cbNodes, result);
65395 result = reduceNode(node.name, cbNode, result);
65396 result = reduceNodes(node.typeParameters, cbNodes, result);
65397 result = reduceNodes(node.parameters, cbNodes, result);
65398 result = reduceNode(node.type, cbNode, result);
65399 result = reduceNode(node.body, cbNode, result);
65400 break;
65401 case 157 /* Constructor */:
65402 result = reduceNodes(node.modifiers, cbNodes, result);
65403 result = reduceNodes(node.parameters, cbNodes, result);
65404 result = reduceNode(node.body, cbNode, result);
65405 break;
65406 case 158 /* GetAccessor */:
65407 result = reduceNodes(node.decorators, cbNodes, result);
65408 result = reduceNodes(node.modifiers, cbNodes, result);
65409 result = reduceNode(node.name, cbNode, result);
65410 result = reduceNodes(node.parameters, cbNodes, result);
65411 result = reduceNode(node.type, cbNode, result);
65412 result = reduceNode(node.body, cbNode, result);
65413 break;
65414 case 159 /* SetAccessor */:
65415 result = reduceNodes(node.decorators, cbNodes, result);
65416 result = reduceNodes(node.modifiers, cbNodes, result);
65417 result = reduceNode(node.name, cbNode, result);
65418 result = reduceNodes(node.parameters, cbNodes, result);
65419 result = reduceNode(node.body, cbNode, result);
65420 break;
65421 // Binding patterns
65422 case 184 /* ObjectBindingPattern */:
65423 case 185 /* ArrayBindingPattern */:
65424 result = reduceNodes(node.elements, cbNodes, result);
65425 break;
65426 case 186 /* BindingElement */:
65427 result = reduceNode(node.propertyName, cbNode, result);
65428 result = reduceNode(node.name, cbNode, result);
65429 result = reduceNode(node.initializer, cbNode, result);
65430 break;
65431 // Expression
65432 case 187 /* ArrayLiteralExpression */:
65433 result = reduceNodes(node.elements, cbNodes, result);
65434 break;
65435 case 188 /* ObjectLiteralExpression */:
65436 result = reduceNodes(node.properties, cbNodes, result);
65437 break;
65438 case 189 /* PropertyAccessExpression */:
65439 result = reduceNode(node.expression, cbNode, result);
65440 result = reduceNode(node.name, cbNode, result);
65441 break;
65442 case 190 /* ElementAccessExpression */:
65443 result = reduceNode(node.expression, cbNode, result);
65444 result = reduceNode(node.argumentExpression, cbNode, result);
65445 break;
65446 case 191 /* CallExpression */:
65447 result = reduceNode(node.expression, cbNode, result);
65448 result = reduceNodes(node.typeArguments, cbNodes, result);
65449 result = reduceNodes(node.arguments, cbNodes, result);
65450 break;
65451 case 192 /* NewExpression */:
65452 result = reduceNode(node.expression, cbNode, result);
65453 result = reduceNodes(node.typeArguments, cbNodes, result);
65454 result = reduceNodes(node.arguments, cbNodes, result);
65455 break;
65456 case 193 /* TaggedTemplateExpression */:
65457 result = reduceNode(node.tag, cbNode, result);
65458 result = reduceNodes(node.typeArguments, cbNodes, result);
65459 result = reduceNode(node.template, cbNode, result);
65460 break;
65461 case 194 /* TypeAssertionExpression */:
65462 result = reduceNode(node.type, cbNode, result);
65463 result = reduceNode(node.expression, cbNode, result);
65464 break;
65465 case 196 /* FunctionExpression */:
65466 result = reduceNodes(node.modifiers, cbNodes, result);
65467 result = reduceNode(node.name, cbNode, result);
65468 result = reduceNodes(node.typeParameters, cbNodes, result);
65469 result = reduceNodes(node.parameters, cbNodes, result);
65470 result = reduceNode(node.type, cbNode, result);
65471 result = reduceNode(node.body, cbNode, result);
65472 break;
65473 case 197 /* ArrowFunction */:
65474 result = reduceNodes(node.modifiers, cbNodes, result);
65475 result = reduceNodes(node.typeParameters, cbNodes, result);
65476 result = reduceNodes(node.parameters, cbNodes, result);
65477 result = reduceNode(node.type, cbNode, result);
65478 result = reduceNode(node.body, cbNode, result);
65479 break;
65480 case 195 /* ParenthesizedExpression */:
65481 case 198 /* DeleteExpression */:
65482 case 199 /* TypeOfExpression */:
65483 case 200 /* VoidExpression */:
65484 case 201 /* AwaitExpression */:
65485 case 207 /* YieldExpression */:
65486 case 208 /* SpreadElement */:
65487 case 213 /* NonNullExpression */:
65488 result = reduceNode(node.expression, cbNode, result);
65489 break;
65490 case 202 /* PrefixUnaryExpression */:
65491 case 203 /* PostfixUnaryExpression */:
65492 result = reduceNode(node.operand, cbNode, result);
65493 break;
65494 case 204 /* BinaryExpression */:
65495 result = reduceNode(node.left, cbNode, result);
65496 result = reduceNode(node.right, cbNode, result);
65497 break;
65498 case 205 /* ConditionalExpression */:
65499 result = reduceNode(node.condition, cbNode, result);
65500 result = reduceNode(node.whenTrue, cbNode, result);
65501 result = reduceNode(node.whenFalse, cbNode, result);
65502 break;
65503 case 206 /* TemplateExpression */:
65504 result = reduceNode(node.head, cbNode, result);
65505 result = reduceNodes(node.templateSpans, cbNodes, result);
65506 break;
65507 case 209 /* ClassExpression */:
65508 result = reduceNodes(node.modifiers, cbNodes, result);
65509 result = reduceNode(node.name, cbNode, result);
65510 result = reduceNodes(node.typeParameters, cbNodes, result);
65511 result = reduceNodes(node.heritageClauses, cbNodes, result);
65512 result = reduceNodes(node.members, cbNodes, result);
65513 break;
65514 case 211 /* ExpressionWithTypeArguments */:
65515 result = reduceNode(node.expression, cbNode, result);
65516 result = reduceNodes(node.typeArguments, cbNodes, result);
65517 break;
65518 case 212 /* AsExpression */:
65519 result = reduceNode(node.expression, cbNode, result);
65520 result = reduceNode(node.type, cbNode, result);
65521 break;
65522 // Misc
65523 case 216 /* TemplateSpan */:
65524 result = reduceNode(node.expression, cbNode, result);
65525 result = reduceNode(node.literal, cbNode, result);
65526 break;
65527 // Element
65528 case 218 /* Block */:
65529 result = reduceNodes(node.statements, cbNodes, result);
65530 break;
65531 case 219 /* VariableStatement */:
65532 result = reduceNodes(node.modifiers, cbNodes, result);
65533 result = reduceNode(node.declarationList, cbNode, result);
65534 break;
65535 case 221 /* ExpressionStatement */:
65536 result = reduceNode(node.expression, cbNode, result);
65537 break;
65538 case 222 /* IfStatement */:
65539 result = reduceNode(node.expression, cbNode, result);
65540 result = reduceNode(node.thenStatement, cbNode, result);
65541 result = reduceNode(node.elseStatement, cbNode, result);
65542 break;
65543 case 223 /* DoStatement */:
65544 result = reduceNode(node.statement, cbNode, result);
65545 result = reduceNode(node.expression, cbNode, result);
65546 break;
65547 case 224 /* WhileStatement */:
65548 case 231 /* WithStatement */:
65549 result = reduceNode(node.expression, cbNode, result);
65550 result = reduceNode(node.statement, cbNode, result);
65551 break;
65552 case 225 /* ForStatement */:
65553 result = reduceNode(node.initializer, cbNode, result);
65554 result = reduceNode(node.condition, cbNode, result);
65555 result = reduceNode(node.incrementor, cbNode, result);
65556 result = reduceNode(node.statement, cbNode, result);
65557 break;
65558 case 226 /* ForInStatement */:
65559 case 227 /* ForOfStatement */:
65560 result = reduceNode(node.initializer, cbNode, result);
65561 result = reduceNode(node.expression, cbNode, result);
65562 result = reduceNode(node.statement, cbNode, result);
65563 break;
65564 case 230 /* ReturnStatement */:
65565 case 234 /* ThrowStatement */:
65566 result = reduceNode(node.expression, cbNode, result);
65567 break;
65568 case 232 /* SwitchStatement */:
65569 result = reduceNode(node.expression, cbNode, result);
65570 result = reduceNode(node.caseBlock, cbNode, result);
65571 break;
65572 case 233 /* LabeledStatement */:
65573 result = reduceNode(node.label, cbNode, result);
65574 result = reduceNode(node.statement, cbNode, result);
65575 break;
65576 case 235 /* TryStatement */:
65577 result = reduceNode(node.tryBlock, cbNode, result);
65578 result = reduceNode(node.catchClause, cbNode, result);
65579 result = reduceNode(node.finallyBlock, cbNode, result);
65580 break;
65581 case 237 /* VariableDeclaration */:
65582 result = reduceNode(node.name, cbNode, result);
65583 result = reduceNode(node.type, cbNode, result);
65584 result = reduceNode(node.initializer, cbNode, result);
65585 break;
65586 case 238 /* VariableDeclarationList */:
65587 result = reduceNodes(node.declarations, cbNodes, result);
65588 break;
65589 case 239 /* FunctionDeclaration */:
65590 result = reduceNodes(node.decorators, cbNodes, result);
65591 result = reduceNodes(node.modifiers, cbNodes, result);
65592 result = reduceNode(node.name, cbNode, result);
65593 result = reduceNodes(node.typeParameters, cbNodes, result);
65594 result = reduceNodes(node.parameters, cbNodes, result);
65595 result = reduceNode(node.type, cbNode, result);
65596 result = reduceNode(node.body, cbNode, result);
65597 break;
65598 case 240 /* ClassDeclaration */:
65599 result = reduceNodes(node.decorators, cbNodes, result);
65600 result = reduceNodes(node.modifiers, cbNodes, result);
65601 result = reduceNode(node.name, cbNode, result);
65602 result = reduceNodes(node.typeParameters, cbNodes, result);
65603 result = reduceNodes(node.heritageClauses, cbNodes, result);
65604 result = reduceNodes(node.members, cbNodes, result);
65605 break;
65606 case 243 /* EnumDeclaration */:
65607 result = reduceNodes(node.decorators, cbNodes, result);
65608 result = reduceNodes(node.modifiers, cbNodes, result);
65609 result = reduceNode(node.name, cbNode, result);
65610 result = reduceNodes(node.members, cbNodes, result);
65611 break;
65612 case 244 /* ModuleDeclaration */:
65613 result = reduceNodes(node.decorators, cbNodes, result);
65614 result = reduceNodes(node.modifiers, cbNodes, result);
65615 result = reduceNode(node.name, cbNode, result);
65616 result = reduceNode(node.body, cbNode, result);
65617 break;
65618 case 245 /* ModuleBlock */:
65619 result = reduceNodes(node.statements, cbNodes, result);
65620 break;
65621 case 246 /* CaseBlock */:
65622 result = reduceNodes(node.clauses, cbNodes, result);
65623 break;
65624 case 248 /* ImportEqualsDeclaration */:
65625 result = reduceNodes(node.decorators, cbNodes, result);
65626 result = reduceNodes(node.modifiers, cbNodes, result);
65627 result = reduceNode(node.name, cbNode, result);
65628 result = reduceNode(node.moduleReference, cbNode, result);
65629 break;
65630 case 249 /* ImportDeclaration */:
65631 result = reduceNodes(node.decorators, cbNodes, result);
65632 result = reduceNodes(node.modifiers, cbNodes, result);
65633 result = reduceNode(node.importClause, cbNode, result);
65634 result = reduceNode(node.moduleSpecifier, cbNode, result);
65635 break;
65636 case 250 /* ImportClause */:
65637 result = reduceNode(node.name, cbNode, result);
65638 result = reduceNode(node.namedBindings, cbNode, result);
65639 break;
65640 case 251 /* NamespaceImport */:
65641 result = reduceNode(node.name, cbNode, result);
65642 break;
65643 case 252 /* NamedImports */:
65644 case 256 /* NamedExports */:
65645 result = reduceNodes(node.elements, cbNodes, result);
65646 break;
65647 case 253 /* ImportSpecifier */:
65648 case 257 /* ExportSpecifier */:
65649 result = reduceNode(node.propertyName, cbNode, result);
65650 result = reduceNode(node.name, cbNode, result);
65651 break;
65652 case 254 /* ExportAssignment */:
65653 result = ts.reduceLeft(node.decorators, cbNode, result);
65654 result = ts.reduceLeft(node.modifiers, cbNode, result);
65655 result = reduceNode(node.expression, cbNode, result);
65656 break;
65657 case 255 /* ExportDeclaration */:
65658 result = ts.reduceLeft(node.decorators, cbNode, result);
65659 result = ts.reduceLeft(node.modifiers, cbNode, result);
65660 result = reduceNode(node.exportClause, cbNode, result);
65661 result = reduceNode(node.moduleSpecifier, cbNode, result);
65662 break;
65663 // Module references
65664 case 259 /* ExternalModuleReference */:
65665 result = reduceNode(node.expression, cbNode, result);
65666 break;
65667 // JSX
65668 case 260 /* JsxElement */:
65669 result = reduceNode(node.openingElement, cbNode, result);
65670 result = ts.reduceLeft(node.children, cbNode, result);
65671 result = reduceNode(node.closingElement, cbNode, result);
65672 break;
65673 case 264 /* JsxFragment */:
65674 result = reduceNode(node.openingFragment, cbNode, result);
65675 result = ts.reduceLeft(node.children, cbNode, result);
65676 result = reduceNode(node.closingFragment, cbNode, result);
65677 break;
65678 case 261 /* JsxSelfClosingElement */:
65679 case 262 /* JsxOpeningElement */:
65680 result = reduceNode(node.tagName, cbNode, result);
65681 result = reduceNodes(node.typeArguments, cbNode, result);
65682 result = reduceNode(node.attributes, cbNode, result);
65683 break;
65684 case 268 /* JsxAttributes */:
65685 result = reduceNodes(node.properties, cbNodes, result);
65686 break;
65687 case 263 /* JsxClosingElement */:
65688 result = reduceNode(node.tagName, cbNode, result);
65689 break;
65690 case 267 /* JsxAttribute */:
65691 result = reduceNode(node.name, cbNode, result);
65692 result = reduceNode(node.initializer, cbNode, result);
65693 break;
65694 case 269 /* JsxSpreadAttribute */:
65695 result = reduceNode(node.expression, cbNode, result);
65696 break;
65697 case 270 /* JsxExpression */:
65698 result = reduceNode(node.expression, cbNode, result);
65699 break;
65700 // Clauses
65701 case 271 /* CaseClause */:
65702 result = reduceNode(node.expression, cbNode, result);
65703 // falls through
65704 case 272 /* DefaultClause */:
65705 result = reduceNodes(node.statements, cbNodes, result);
65706 break;
65707 case 273 /* HeritageClause */:
65708 result = reduceNodes(node.types, cbNodes, result);
65709 break;
65710 case 274 /* CatchClause */:
65711 result = reduceNode(node.variableDeclaration, cbNode, result);
65712 result = reduceNode(node.block, cbNode, result);
65713 break;
65714 // Property assignments
65715 case 275 /* PropertyAssignment */:
65716 result = reduceNode(node.name, cbNode, result);
65717 result = reduceNode(node.initializer, cbNode, result);
65718 break;
65719 case 276 /* ShorthandPropertyAssignment */:
65720 result = reduceNode(node.name, cbNode, result);
65721 result = reduceNode(node.objectAssignmentInitializer, cbNode, result);
65722 break;
65723 case 277 /* SpreadAssignment */:
65724 result = reduceNode(node.expression, cbNode, result);
65725 break;
65726 // Enum
65727 case 278 /* EnumMember */:
65728 result = reduceNode(node.name, cbNode, result);
65729 result = reduceNode(node.initializer, cbNode, result);
65730 break;
65731 // Top-level nodes
65732 case 284 /* SourceFile */:
65733 result = reduceNodes(node.statements, cbNodes, result);
65734 break;
65735 // Transformation nodes
65736 case 313 /* PartiallyEmittedExpression */:
65737 result = reduceNode(node.expression, cbNode, result);
65738 break;
65739 case 314 /* CommaListExpression */:
65740 result = reduceNodes(node.elements, cbNodes, result);
65741 break;
65742 default:
65743 break;
65744 }
65745 return result;
65746 }
65747 ts.reduceEachChild = reduceEachChild;
65748 function mergeLexicalEnvironment(statements, declarations) {
65749 if (!ts.some(declarations)) {
65750 return statements;
65751 }
65752 return ts.isNodeArray(statements)
65753 ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements)
65754 : ts.insertStatementsAfterStandardPrologue(statements, declarations);
65755 }
65756 ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
65757 /**
65758 * Lifts a NodeArray containing only Statement nodes to a block.
65759 *
65760 * @param nodes The NodeArray.
65761 */
65762 function liftToBlock(nodes) {
65763 Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block.");
65764 return ts.singleOrUndefined(nodes) || ts.createBlock(nodes);
65765 }
65766 ts.liftToBlock = liftToBlock;
65767 /**
65768 * Aggregates the TransformFlags for a Node and its subtree.
65769 */
65770 function aggregateTransformFlags(node) {
65771 aggregateTransformFlagsForNode(node);
65772 return node;
65773 }
65774 ts.aggregateTransformFlags = aggregateTransformFlags;
65775 /**
65776 * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are
65777 * computed first, then the transform flags for the current node are computed from the subtree
65778 * flags and the state of the current node. Finally, the transform flags of the node are
65779 * returned, excluding any flags that should not be included in its parent node's subtree
65780 * flags.
65781 */
65782 function aggregateTransformFlagsForNode(node) {
65783 if (node === undefined) {
65784 return 0 /* None */;
65785 }
65786 if (node.transformFlags & 536870912 /* HasComputedFlags */) {
65787 return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind);
65788 }
65789 var subtreeFlags = aggregateTransformFlagsForSubtree(node);
65790 return ts.computeTransformFlagsForNode(node, subtreeFlags);
65791 }
65792 function aggregateTransformFlagsForNodeArray(nodes) {
65793 if (nodes === undefined) {
65794 return 0 /* None */;
65795 }
65796 var subtreeFlags = 0 /* None */;
65797 var nodeArrayFlags = 0 /* None */;
65798 for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) {
65799 var node = nodes_3[_i];
65800 subtreeFlags |= aggregateTransformFlagsForNode(node);
65801 nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
65802 }
65803 nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
65804 return subtreeFlags;
65805 }
65806 /**
65807 * Aggregates the transform flags for the subtree of a node.
65808 */
65809 function aggregateTransformFlagsForSubtree(node) {
65810 // We do not transform ambient declarations or types, so there is no need to
65811 // recursively aggregate transform flags.
65812 if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 211 /* ExpressionWithTypeArguments */)) {
65813 return 0 /* None */;
65814 }
65815 // Aggregate the transform flags of each child.
65816 return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
65817 }
65818 /**
65819 * Aggregates the TransformFlags of a child node with the TransformFlags of its
65820 * siblings.
65821 */
65822 function aggregateTransformFlagsForChildNode(transformFlags, node) {
65823 return transformFlags | aggregateTransformFlagsForNode(node);
65824 }
65825 function aggregateTransformFlagsForChildNodes(transformFlags, nodes) {
65826 return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
65827 }
65828 var Debug;
65829 (function (Debug) {
65830 var isDebugInfoEnabled = false;
65831 function failBadSyntaxKind(node, message) {
65832 return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind);
65833 }
65834 Debug.failBadSyntaxKind = failBadSyntaxKind;
65835 Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */)
65836 ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); }
65837 : ts.noop;
65838 Debug.assertNode = Debug.shouldAssert(1 /* Normal */)
65839 ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); }
65840 : ts.noop;
65841 Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */)
65842 ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); }
65843 : ts.noop;
65844 Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */)
65845 ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); }
65846 : ts.noop;
65847 Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */)
65848 ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); }
65849 : ts.noop;
65850 /**
65851 * Injects debug information into frequently used types.
65852 */
65853 function enableDebugInfo() {
65854 if (isDebugInfoEnabled)
65855 return;
65856 // Add additional properties in debug mode to assist with debugging.
65857 Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
65858 __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } }
65859 });
65860 Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
65861 __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } },
65862 __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } },
65863 __debugTypeToString: { value: function () { return this.checker.typeToString(this); } },
65864 });
65865 var nodeConstructors = [
65866 ts.objectAllocator.getNodeConstructor(),
65867 ts.objectAllocator.getIdentifierConstructor(),
65868 ts.objectAllocator.getTokenConstructor(),
65869 ts.objectAllocator.getSourceFileConstructor()
65870 ];
65871 for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
65872 var ctor = nodeConstructors_1[_i];
65873 if (!ctor.prototype.hasOwnProperty("__debugKind")) {
65874 Object.defineProperties(ctor.prototype, {
65875 __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } },
65876 __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } },
65877 __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } },
65878 __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } },
65879 __debugGetText: {
65880 value: function (includeTrivia) {
65881 if (ts.nodeIsSynthesized(this))
65882 return "";
65883 var parseNode = ts.getParseTreeNode(this);
65884 var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
65885 return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
65886 }
65887 }
65888 });
65889 }
65890 }
65891 isDebugInfoEnabled = true;
65892 }
65893 Debug.enableDebugInfo = enableDebugInfo;
65894 })(Debug = ts.Debug || (ts.Debug = {}));
65895})(ts || (ts = {}));
65896/* @internal */
65897var ts;
65898(function (ts) {
65899 function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
65900 var _a = generatorOptions.extendedDiagnostics
65901 ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
65902 : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
65903 // Current source map file and its index in the sources list
65904 var rawSources = [];
65905 var sources = [];
65906 var sourceToSourceIndexMap = ts.createMap();
65907 var sourcesContent;
65908 var names = [];
65909 var nameToNameIndexMap;
65910 var mappings = "";
65911 // Last recorded and encoded mappings
65912 var lastGeneratedLine = 0;
65913 var lastGeneratedCharacter = 0;
65914 var lastSourceIndex = 0;
65915 var lastSourceLine = 0;
65916 var lastSourceCharacter = 0;
65917 var lastNameIndex = 0;
65918 var hasLast = false;
65919 var pendingGeneratedLine = 0;
65920 var pendingGeneratedCharacter = 0;
65921 var pendingSourceIndex = 0;
65922 var pendingSourceLine = 0;
65923 var pendingSourceCharacter = 0;
65924 var pendingNameIndex = 0;
65925 var hasPending = false;
65926 var hasPendingSource = false;
65927 var hasPendingName = false;
65928 return {
65929 getSources: function () { return rawSources; },
65930 addSource: addSource,
65931 setSourceContent: setSourceContent,
65932 addName: addName,
65933 addMapping: addMapping,
65934 appendSourceMap: appendSourceMap,
65935 toJSON: toJSON,
65936 toString: function () { return JSON.stringify(toJSON()); }
65937 };
65938 function addSource(fileName) {
65939 enter();
65940 var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName,
65941 /*isAbsolutePathAnUrl*/ true);
65942 var sourceIndex = sourceToSourceIndexMap.get(source);
65943 if (sourceIndex === undefined) {
65944 sourceIndex = sources.length;
65945 sources.push(source);
65946 rawSources.push(fileName);
65947 sourceToSourceIndexMap.set(source, sourceIndex);
65948 }
65949 exit();
65950 return sourceIndex;
65951 }
65952 function setSourceContent(sourceIndex, content) {
65953 enter();
65954 if (content !== null) {
65955 if (!sourcesContent)
65956 sourcesContent = [];
65957 while (sourcesContent.length < sourceIndex) {
65958 // tslint:disable-next-line:no-null-keyword boolean-trivia
65959 sourcesContent.push(null);
65960 }
65961 sourcesContent[sourceIndex] = content;
65962 }
65963 exit();
65964 }
65965 function addName(name) {
65966 enter();
65967 if (!nameToNameIndexMap)
65968 nameToNameIndexMap = ts.createMap();
65969 var nameIndex = nameToNameIndexMap.get(name);
65970 if (nameIndex === undefined) {
65971 nameIndex = names.length;
65972 names.push(name);
65973 nameToNameIndexMap.set(name, nameIndex);
65974 }
65975 exit();
65976 return nameIndex;
65977 }
65978 function isNewGeneratedPosition(generatedLine, generatedCharacter) {
65979 return !hasPending
65980 || pendingGeneratedLine !== generatedLine
65981 || pendingGeneratedCharacter !== generatedCharacter;
65982 }
65983 function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
65984 return sourceIndex !== undefined
65985 && sourceLine !== undefined
65986 && sourceCharacter !== undefined
65987 && pendingSourceIndex === sourceIndex
65988 && (pendingSourceLine > sourceLine
65989 || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
65990 }
65991 function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
65992 ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
65993 ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
65994 ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
65995 ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
65996 ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
65997 enter();
65998 // If this location wasn't recorded or the location in source is going backwards, record the mapping
65999 if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
66000 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
66001 commitPendingMapping();
66002 pendingGeneratedLine = generatedLine;
66003 pendingGeneratedCharacter = generatedCharacter;
66004 hasPendingSource = false;
66005 hasPendingName = false;
66006 hasPending = true;
66007 }
66008 if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
66009 pendingSourceIndex = sourceIndex;
66010 pendingSourceLine = sourceLine;
66011 pendingSourceCharacter = sourceCharacter;
66012 hasPendingSource = true;
66013 if (nameIndex !== undefined) {
66014 pendingNameIndex = nameIndex;
66015 hasPendingName = true;
66016 }
66017 }
66018 exit();
66019 }
66020 function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
66021 var _a;
66022 ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
66023 ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
66024 enter();
66025 // First, decode the old component sourcemap
66026 var sourceIndexToNewSourceIndexMap = [];
66027 var nameIndexToNewNameIndexMap;
66028 var mappingIterator = decodeMappings(map.mappings);
66029 for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
66030 if (end && (raw.generatedLine > end.line ||
66031 (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
66032 break;
66033 }
66034 if (start && (raw.generatedLine < start.line ||
66035 (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
66036 continue;
66037 }
66038 // Then reencode all the updated mappings into the overall map
66039 var newSourceIndex = void 0;
66040 var newSourceLine = void 0;
66041 var newSourceCharacter = void 0;
66042 var newNameIndex = void 0;
66043 if (raw.sourceIndex !== undefined) {
66044 newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
66045 if (newSourceIndex === undefined) {
66046 // Apply offsets to each position and fixup source entries
66047 var rawPath = map.sources[raw.sourceIndex];
66048 var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
66049 var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
66050 sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
66051 if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
66052 setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
66053 }
66054 }
66055 newSourceLine = raw.sourceLine;
66056 newSourceCharacter = raw.sourceCharacter;
66057 if (map.names && raw.nameIndex !== undefined) {
66058 if (!nameIndexToNewNameIndexMap)
66059 nameIndexToNewNameIndexMap = [];
66060 newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
66061 if (newNameIndex === undefined) {
66062 nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
66063 }
66064 }
66065 }
66066 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
66067 var newGeneratedLine = rawGeneratedLine + generatedLine;
66068 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
66069 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
66070 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
66071 }
66072 exit();
66073 }
66074 function shouldCommitMapping() {
66075 return !hasLast
66076 || lastGeneratedLine !== pendingGeneratedLine
66077 || lastGeneratedCharacter !== pendingGeneratedCharacter
66078 || lastSourceIndex !== pendingSourceIndex
66079 || lastSourceLine !== pendingSourceLine
66080 || lastSourceCharacter !== pendingSourceCharacter
66081 || lastNameIndex !== pendingNameIndex;
66082 }
66083 function commitPendingMapping() {
66084 if (!hasPending || !shouldCommitMapping()) {
66085 return;
66086 }
66087 enter();
66088 // Line/Comma delimiters
66089 if (lastGeneratedLine < pendingGeneratedLine) {
66090 // Emit line delimiters
66091 do {
66092 mappings += ";";
66093 lastGeneratedLine++;
66094 lastGeneratedCharacter = 0;
66095 } while (lastGeneratedLine < pendingGeneratedLine);
66096 }
66097 else {
66098 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
66099 // Emit comma to separate the entry
66100 if (hasLast) {
66101 mappings += ",";
66102 }
66103 }
66104 // 1. Relative generated character
66105 mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
66106 lastGeneratedCharacter = pendingGeneratedCharacter;
66107 if (hasPendingSource) {
66108 // 2. Relative sourceIndex
66109 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
66110 lastSourceIndex = pendingSourceIndex;
66111 // 3. Relative source line
66112 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
66113 lastSourceLine = pendingSourceLine;
66114 // 4. Relative source character
66115 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
66116 lastSourceCharacter = pendingSourceCharacter;
66117 if (hasPendingName) {
66118 // 5. Relative nameIndex
66119 mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
66120 lastNameIndex = pendingNameIndex;
66121 }
66122 }
66123 hasLast = true;
66124 exit();
66125 }
66126 function toJSON() {
66127 commitPendingMapping();
66128 return {
66129 version: 3,
66130 file: file,
66131 sourceRoot: sourceRoot,
66132 sources: sources,
66133 names: names,
66134 mappings: mappings,
66135 sourcesContent: sourcesContent,
66136 };
66137 }
66138 }
66139 ts.createSourceMapGenerator = createSourceMapGenerator;
66140 // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
66141 var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
66142 var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
66143 function getLineInfo(text, lineStarts) {
66144 return {
66145 getLineCount: function () { return lineStarts.length; },
66146 getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
66147 };
66148 }
66149 ts.getLineInfo = getLineInfo;
66150 /**
66151 * Tries to find the sourceMappingURL comment at the end of a file.
66152 */
66153 function tryGetSourceMappingURL(lineInfo) {
66154 for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
66155 var line = lineInfo.getLineText(index);
66156 var comment = sourceMapCommentRegExp.exec(line);
66157 if (comment) {
66158 return comment[1];
66159 }
66160 // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
66161 else if (!line.match(whitespaceOrMapCommentRegExp)) {
66162 break;
66163 }
66164 }
66165 }
66166 ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
66167 function isStringOrNull(x) {
66168 // tslint:disable-next-line:no-null-keyword
66169 return typeof x === "string" || x === null;
66170 }
66171 function isRawSourceMap(x) {
66172 // tslint:disable-next-line:no-null-keyword
66173 return x !== null
66174 && typeof x === "object"
66175 && x.version === 3
66176 && typeof x.file === "string"
66177 && typeof x.mappings === "string"
66178 && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
66179 && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
66180 && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
66181 && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
66182 }
66183 ts.isRawSourceMap = isRawSourceMap;
66184 function tryParseRawSourceMap(text) {
66185 try {
66186 var parsed = JSON.parse(text);
66187 if (isRawSourceMap(parsed)) {
66188 return parsed;
66189 }
66190 }
66191 catch (_a) {
66192 // empty
66193 }
66194 return undefined;
66195 }
66196 ts.tryParseRawSourceMap = tryParseRawSourceMap;
66197 function decodeMappings(mappings) {
66198 var done = false;
66199 var pos = 0;
66200 var generatedLine = 0;
66201 var generatedCharacter = 0;
66202 var sourceIndex = 0;
66203 var sourceLine = 0;
66204 var sourceCharacter = 0;
66205 var nameIndex = 0;
66206 var error;
66207 return {
66208 get pos() { return pos; },
66209 get error() { return error; },
66210 get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
66211 next: function () {
66212 while (!done && pos < mappings.length) {
66213 var ch = mappings.charCodeAt(pos);
66214 if (ch === 59 /* semicolon */) {
66215 // new line
66216 generatedLine++;
66217 generatedCharacter = 0;
66218 pos++;
66219 continue;
66220 }
66221 if (ch === 44 /* comma */) {
66222 // Next entry is on same line - no action needed
66223 pos++;
66224 continue;
66225 }
66226 var hasSource = false;
66227 var hasName = false;
66228 generatedCharacter += base64VLQFormatDecode();
66229 if (hasReportedError())
66230 return stopIterating();
66231 if (generatedCharacter < 0)
66232 return setErrorAndStopIterating("Invalid generatedCharacter found");
66233 if (!isSourceMappingSegmentEnd()) {
66234 hasSource = true;
66235 sourceIndex += base64VLQFormatDecode();
66236 if (hasReportedError())
66237 return stopIterating();
66238 if (sourceIndex < 0)
66239 return setErrorAndStopIterating("Invalid sourceIndex found");
66240 if (isSourceMappingSegmentEnd())
66241 return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
66242 sourceLine += base64VLQFormatDecode();
66243 if (hasReportedError())
66244 return stopIterating();
66245 if (sourceLine < 0)
66246 return setErrorAndStopIterating("Invalid sourceLine found");
66247 if (isSourceMappingSegmentEnd())
66248 return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
66249 sourceCharacter += base64VLQFormatDecode();
66250 if (hasReportedError())
66251 return stopIterating();
66252 if (sourceCharacter < 0)
66253 return setErrorAndStopIterating("Invalid sourceCharacter found");
66254 if (!isSourceMappingSegmentEnd()) {
66255 hasName = true;
66256 nameIndex += base64VLQFormatDecode();
66257 if (hasReportedError())
66258 return stopIterating();
66259 if (nameIndex < 0)
66260 return setErrorAndStopIterating("Invalid nameIndex found");
66261 if (!isSourceMappingSegmentEnd())
66262 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
66263 }
66264 }
66265 return { value: captureMapping(hasSource, hasName), done: done };
66266 }
66267 return stopIterating();
66268 }
66269 };
66270 function captureMapping(hasSource, hasName) {
66271 return {
66272 generatedLine: generatedLine,
66273 generatedCharacter: generatedCharacter,
66274 sourceIndex: hasSource ? sourceIndex : undefined,
66275 sourceLine: hasSource ? sourceLine : undefined,
66276 sourceCharacter: hasSource ? sourceCharacter : undefined,
66277 nameIndex: hasName ? nameIndex : undefined
66278 };
66279 }
66280 function stopIterating() {
66281 done = true;
66282 return { value: undefined, done: true };
66283 }
66284 function setError(message) {
66285 if (error === undefined) {
66286 error = message;
66287 }
66288 }
66289 function setErrorAndStopIterating(message) {
66290 setError(message);
66291 return stopIterating();
66292 }
66293 function hasReportedError() {
66294 return error !== undefined;
66295 }
66296 function isSourceMappingSegmentEnd() {
66297 return (pos === mappings.length ||
66298 mappings.charCodeAt(pos) === 44 /* comma */ ||
66299 mappings.charCodeAt(pos) === 59 /* semicolon */);
66300 }
66301 function base64VLQFormatDecode() {
66302 var moreDigits = true;
66303 var shiftCount = 0;
66304 var value = 0;
66305 for (; moreDigits; pos++) {
66306 if (pos >= mappings.length)
66307 return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
66308 // 6 digit number
66309 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
66310 if (currentByte === -1)
66311 return setError("Invalid character in VLQ"), -1;
66312 // If msb is set, we still have more bits to continue
66313 moreDigits = (currentByte & 32) !== 0;
66314 // least significant 5 bits are the next msbs in the final value.
66315 value = value | ((currentByte & 31) << shiftCount);
66316 shiftCount += 5;
66317 }
66318 // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
66319 if ((value & 1) === 0) {
66320 // + number
66321 value = value >> 1;
66322 }
66323 else {
66324 // - number
66325 value = value >> 1;
66326 value = -value;
66327 }
66328 return value;
66329 }
66330 }
66331 ts.decodeMappings = decodeMappings;
66332 function sameMapping(left, right) {
66333 return left === right
66334 || left.generatedLine === right.generatedLine
66335 && left.generatedCharacter === right.generatedCharacter
66336 && left.sourceIndex === right.sourceIndex
66337 && left.sourceLine === right.sourceLine
66338 && left.sourceCharacter === right.sourceCharacter
66339 && left.nameIndex === right.nameIndex;
66340 }
66341 ts.sameMapping = sameMapping;
66342 function isSourceMapping(mapping) {
66343 return mapping.sourceIndex !== undefined
66344 && mapping.sourceLine !== undefined
66345 && mapping.sourceCharacter !== undefined;
66346 }
66347 ts.isSourceMapping = isSourceMapping;
66348 function base64FormatEncode(value) {
66349 return value >= 0 && value < 26 ? 65 /* A */ + value :
66350 value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
66351 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
66352 value === 62 ? 43 /* plus */ :
66353 value === 63 ? 47 /* slash */ :
66354 ts.Debug.fail(value + ": not a base64 value");
66355 }
66356 function base64FormatDecode(ch) {
66357 return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
66358 ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
66359 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
66360 ch === 43 /* plus */ ? 62 :
66361 ch === 47 /* slash */ ? 63 :
66362 -1;
66363 }
66364 function base64VLQFormatEncode(inValue) {
66365 // Add a new least significant bit that has the sign of the value.
66366 // if negative number the least significant bit that gets added to the number has value 1
66367 // else least significant bit value that gets added is 0
66368 // eg. -1 changes to binary : 01 [1] => 3
66369 // +1 changes to binary : 01 [0] => 2
66370 if (inValue < 0) {
66371 inValue = ((-inValue) << 1) + 1;
66372 }
66373 else {
66374 inValue = inValue << 1;
66375 }
66376 // Encode 5 bits at a time starting from least significant bits
66377 var encodedStr = "";
66378 do {
66379 var currentDigit = inValue & 31; // 11111
66380 inValue = inValue >> 5;
66381 if (inValue > 0) {
66382 // There are still more digits to decode, set the msb (6th bit)
66383 currentDigit = currentDigit | 32;
66384 }
66385 encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
66386 } while (inValue > 0);
66387 return encodedStr;
66388 }
66389 function isSourceMappedPosition(value) {
66390 return value.sourceIndex !== undefined
66391 && value.sourcePosition !== undefined;
66392 }
66393 function sameMappedPosition(left, right) {
66394 return left.generatedPosition === right.generatedPosition
66395 && left.sourceIndex === right.sourceIndex
66396 && left.sourcePosition === right.sourcePosition;
66397 }
66398 function compareSourcePositions(left, right) {
66399 // Compares sourcePosition without comparing sourceIndex
66400 // since the mappings are grouped by sourceIndex
66401 ts.Debug.assert(left.sourceIndex === right.sourceIndex);
66402 return ts.compareValues(left.sourcePosition, right.sourcePosition);
66403 }
66404 function compareGeneratedPositions(left, right) {
66405 return ts.compareValues(left.generatedPosition, right.generatedPosition);
66406 }
66407 function getSourcePositionOfMapping(value) {
66408 return value.sourcePosition;
66409 }
66410 function getGeneratedPositionOfMapping(value) {
66411 return value.generatedPosition;
66412 }
66413 function createDocumentPositionMapper(host, map, mapPath) {
66414 var mapDirectory = ts.getDirectoryPath(mapPath);
66415 var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
66416 var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
66417 var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
66418 var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
66419 var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
66420 var decodedMappings;
66421 var generatedMappings;
66422 var sourceMappings;
66423 return {
66424 getSourcePosition: getSourcePosition,
66425 getGeneratedPosition: getGeneratedPosition
66426 };
66427 function processMapping(mapping) {
66428 var generatedPosition = generatedFile !== undefined
66429 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
66430 : -1;
66431 var source;
66432 var sourcePosition;
66433 if (isSourceMapping(mapping)) {
66434 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
66435 source = map.sources[mapping.sourceIndex];
66436 sourcePosition = sourceFile !== undefined
66437 ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
66438 : -1;
66439 }
66440 return {
66441 generatedPosition: generatedPosition,
66442 source: source,
66443 sourceIndex: mapping.sourceIndex,
66444 sourcePosition: sourcePosition,
66445 nameIndex: mapping.nameIndex
66446 };
66447 }
66448 function getDecodedMappings() {
66449 if (decodedMappings === undefined) {
66450 var decoder = decodeMappings(map.mappings);
66451 var mappings = ts.arrayFrom(decoder, processMapping);
66452 if (decoder.error !== undefined) {
66453 if (host.log) {
66454 host.log("Encountered error while decoding sourcemap: " + decoder.error);
66455 }
66456 decodedMappings = ts.emptyArray;
66457 }
66458 else {
66459 decodedMappings = mappings;
66460 }
66461 }
66462 return decodedMappings;
66463 }
66464 function getSourceMappings(sourceIndex) {
66465 if (sourceMappings === undefined) {
66466 var lists = [];
66467 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
66468 var mapping = _a[_i];
66469 if (!isSourceMappedPosition(mapping))
66470 continue;
66471 var list = lists[mapping.sourceIndex];
66472 if (!list)
66473 lists[mapping.sourceIndex] = list = [];
66474 list.push(mapping);
66475 }
66476 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
66477 }
66478 return sourceMappings[sourceIndex];
66479 }
66480 function getGeneratedMappings() {
66481 if (generatedMappings === undefined) {
66482 var list = [];
66483 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
66484 var mapping = _a[_i];
66485 list.push(mapping);
66486 }
66487 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
66488 }
66489 return generatedMappings;
66490 }
66491 function getGeneratedPosition(loc) {
66492 var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
66493 if (sourceIndex === undefined)
66494 return loc;
66495 var sourceMappings = getSourceMappings(sourceIndex);
66496 if (!ts.some(sourceMappings))
66497 return loc;
66498 var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
66499 if (targetIndex < 0) {
66500 // if no exact match, closest is 2's complement of result
66501 targetIndex = ~targetIndex;
66502 }
66503 var mapping = sourceMappings[targetIndex];
66504 if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
66505 return loc;
66506 }
66507 return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
66508 }
66509 function getSourcePosition(loc) {
66510 var generatedMappings = getGeneratedMappings();
66511 if (!ts.some(generatedMappings))
66512 return loc;
66513 var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
66514 if (targetIndex < 0) {
66515 // if no exact match, closest is 2's complement of result
66516 targetIndex = ~targetIndex;
66517 }
66518 var mapping = generatedMappings[targetIndex];
66519 if (mapping === undefined || !isSourceMappedPosition(mapping)) {
66520 return loc;
66521 }
66522 return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
66523 }
66524 }
66525 ts.createDocumentPositionMapper = createDocumentPositionMapper;
66526 ts.identitySourceMapConsumer = {
66527 getSourcePosition: ts.identity,
66528 getGeneratedPosition: ts.identity
66529 };
66530})(ts || (ts = {}));
66531/* @internal */
66532var ts;
66533(function (ts) {
66534 function getOriginalNodeId(node) {
66535 node = ts.getOriginalNode(node);
66536 return node ? ts.getNodeId(node) : 0;
66537 }
66538 ts.getOriginalNodeId = getOriginalNodeId;
66539 function containsDefaultReference(node) {
66540 if (!node)
66541 return false;
66542 if (!ts.isNamedImports(node))
66543 return false;
66544 return ts.some(node.elements, isNamedDefaultReference);
66545 }
66546 function isNamedDefaultReference(e) {
66547 return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
66548 }
66549 function chainBundle(transformSourceFile) {
66550 return transformSourceFileOrBundle;
66551 function transformSourceFileOrBundle(node) {
66552 return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
66553 }
66554 function transformBundle(node) {
66555 return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
66556 }
66557 }
66558 ts.chainBundle = chainBundle;
66559 function getImportNeedsImportStarHelper(node) {
66560 if (!!ts.getNamespaceDeclarationNode(node)) {
66561 return true;
66562 }
66563 var bindings = node.importClause && node.importClause.namedBindings;
66564 if (!bindings) {
66565 return false;
66566 }
66567 if (!ts.isNamedImports(bindings))
66568 return false;
66569 var defaultRefCount = 0;
66570 for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
66571 var binding = _a[_i];
66572 if (isNamedDefaultReference(binding)) {
66573 defaultRefCount++;
66574 }
66575 }
66576 // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import
66577 return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
66578 }
66579 ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
66580 function getImportNeedsImportDefaultHelper(node) {
66581 // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested)
66582 return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
66583 }
66584 ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
66585 function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
66586 var externalImports = [];
66587 var exportSpecifiers = ts.createMultiMap();
66588 var exportedBindings = [];
66589 var uniqueExports = ts.createMap();
66590 var exportedNames;
66591 var hasExportDefault = false;
66592 var exportEquals;
66593 var hasExportStarsToExportValues = false;
66594 var hasImportStarOrImportDefault = false;
66595 for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
66596 var node = _a[_i];
66597 switch (node.kind) {
66598 case 249 /* ImportDeclaration */:
66599 // import "mod"
66600 // import x from "mod"
66601 // import * as x from "mod"
66602 // import { x, y } from "mod"
66603 externalImports.push(node);
66604 hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node);
66605 break;
66606 case 248 /* ImportEqualsDeclaration */:
66607 if (node.moduleReference.kind === 259 /* ExternalModuleReference */) {
66608 // import x = require("mod")
66609 externalImports.push(node);
66610 }
66611 break;
66612 case 255 /* ExportDeclaration */:
66613 if (node.moduleSpecifier) {
66614 if (!node.exportClause) {
66615 // export * from "mod"
66616 externalImports.push(node);
66617 hasExportStarsToExportValues = true;
66618 }
66619 else {
66620 // export { x, y } from "mod"
66621 externalImports.push(node);
66622 }
66623 }
66624 else {
66625 // export { x, y }
66626 for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) {
66627 var specifier = _c[_b];
66628 if (!uniqueExports.get(ts.idText(specifier.name))) {
66629 var name = specifier.propertyName || specifier.name;
66630 exportSpecifiers.add(ts.idText(name), specifier);
66631 var decl = resolver.getReferencedImportDeclaration(name)
66632 || resolver.getReferencedValueDeclaration(name);
66633 if (decl) {
66634 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
66635 }
66636 uniqueExports.set(ts.idText(specifier.name), true);
66637 exportedNames = ts.append(exportedNames, specifier.name);
66638 }
66639 }
66640 }
66641 break;
66642 case 254 /* ExportAssignment */:
66643 if (node.isExportEquals && !exportEquals) {
66644 // export = x
66645 exportEquals = node;
66646 }
66647 break;
66648 case 219 /* VariableStatement */:
66649 if (ts.hasModifier(node, 1 /* Export */)) {
66650 for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
66651 var decl = _e[_d];
66652 exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
66653 }
66654 }
66655 break;
66656 case 239 /* FunctionDeclaration */:
66657 if (ts.hasModifier(node, 1 /* Export */)) {
66658 if (ts.hasModifier(node, 512 /* Default */)) {
66659 // export default function() { }
66660 if (!hasExportDefault) {
66661 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
66662 hasExportDefault = true;
66663 }
66664 }
66665 else {
66666 // export function x() { }
66667 var name = node.name;
66668 if (!uniqueExports.get(ts.idText(name))) {
66669 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
66670 uniqueExports.set(ts.idText(name), true);
66671 exportedNames = ts.append(exportedNames, name);
66672 }
66673 }
66674 }
66675 break;
66676 case 240 /* ClassDeclaration */:
66677 if (ts.hasModifier(node, 1 /* Export */)) {
66678 if (ts.hasModifier(node, 512 /* Default */)) {
66679 // export default class { }
66680 if (!hasExportDefault) {
66681 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
66682 hasExportDefault = true;
66683 }
66684 }
66685 else {
66686 // export class x { }
66687 var name = node.name;
66688 if (name && !uniqueExports.get(ts.idText(name))) {
66689 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
66690 uniqueExports.set(ts.idText(name), true);
66691 exportedNames = ts.append(exportedNames, name);
66692 }
66693 }
66694 }
66695 break;
66696 }
66697 }
66698 var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault);
66699 var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(
66700 /*decorators*/ undefined,
66701 /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText));
66702 if (externalHelpersImportDeclaration) {
66703 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
66704 externalImports.unshift(externalHelpersImportDeclaration);
66705 }
66706 return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
66707 }
66708 ts.collectExternalModuleInfo = collectExternalModuleInfo;
66709 function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
66710 if (ts.isBindingPattern(decl.name)) {
66711 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
66712 var element = _a[_i];
66713 if (!ts.isOmittedExpression(element)) {
66714 exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
66715 }
66716 }
66717 }
66718 else if (!ts.isGeneratedIdentifier(decl.name)) {
66719 var text = ts.idText(decl.name);
66720 if (!uniqueExports.get(text)) {
66721 uniqueExports.set(text, true);
66722 exportedNames = ts.append(exportedNames, decl.name);
66723 }
66724 }
66725 return exportedNames;
66726 }
66727 /** Use a sparse array as a multi-map. */
66728 function multiMapSparseArrayAdd(map, key, value) {
66729 var values = map[key];
66730 if (values) {
66731 values.push(value);
66732 }
66733 else {
66734 map[key] = values = [value];
66735 }
66736 return values;
66737 }
66738 /**
66739 * Used in the module transformer to check if an expression is reasonably without sideeffect,
66740 * and thus better to copy into multiple places rather than to cache in a temporary variable
66741 * - this is mostly subjective beyond the requirement that the expression not be sideeffecting
66742 */
66743 function isSimpleCopiableExpression(expression) {
66744 return ts.isStringLiteralLike(expression) ||
66745 expression.kind === 8 /* NumericLiteral */ ||
66746 ts.isKeyword(expression.kind) ||
66747 ts.isIdentifier(expression);
66748 }
66749 ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
66750 /**
66751 * @param input Template string input strings
66752 * @param args Names which need to be made file-level unique
66753 */
66754 function helperString(input) {
66755 var args = [];
66756 for (var _i = 1; _i < arguments.length; _i++) {
66757 args[_i - 1] = arguments[_i];
66758 }
66759 return function (uniqueName) {
66760 var result = "";
66761 for (var i = 0; i < args.length; i++) {
66762 result += input[i];
66763 result += uniqueName(args[i]);
66764 }
66765 result += input[input.length - 1];
66766 return result;
66767 };
66768 }
66769 ts.helperString = helperString;
66770})(ts || (ts = {}));
66771/*@internal*/
66772var ts;
66773(function (ts) {
66774 var FlattenLevel;
66775 (function (FlattenLevel) {
66776 FlattenLevel[FlattenLevel["All"] = 0] = "All";
66777 FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
66778 })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
66779 /**
66780 * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
66781 *
66782 * @param node The node to flatten.
66783 * @param visitor An optional visitor used to visit initializers.
66784 * @param context The transformation context.
66785 * @param level Indicates the extent to which flattening should occur.
66786 * @param needsValue An optional value indicating whether the value from the right-hand-side of
66787 * the destructuring assignment is needed as part of a larger expression.
66788 * @param createAssignmentCallback An optional callback used to create the assignment expression.
66789 */
66790 function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
66791 var location = node;
66792 var value;
66793 if (ts.isDestructuringAssignment(node)) {
66794 value = node.right;
66795 while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
66796 if (ts.isDestructuringAssignment(value)) {
66797 location = node = value;
66798 value = node.right;
66799 }
66800 else {
66801 return ts.visitNode(value, visitor, ts.isExpression);
66802 }
66803 }
66804 }
66805 var expressions;
66806 var flattenContext = {
66807 context: context,
66808 level: level,
66809 downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
66810 hoistTempVariables: true,
66811 emitExpression: emitExpression,
66812 emitBindingOrAssignment: emitBindingOrAssignment,
66813 createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
66814 createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
66815 createArrayBindingOrAssignmentElement: makeAssignmentElement,
66816 visitor: visitor
66817 };
66818 if (value) {
66819 value = ts.visitNode(value, visitor, ts.isExpression);
66820 if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) {
66821 // If the right-hand value of the assignment is also an assignment target then
66822 // we need to cache the right-hand value.
66823 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
66824 }
66825 else if (needsValue) {
66826 // If the right-hand value of the destructuring assignment needs to be preserved (as
66827 // is the case when the destructuring assignment is part of a larger expression),
66828 // then we need to cache the right-hand value.
66829 //
66830 // The source map location for the assignment should point to the entire binary
66831 // expression.
66832 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
66833 }
66834 else if (ts.nodeIsSynthesized(node)) {
66835 // Generally, the source map location for a destructuring assignment is the root
66836 // expression.
66837 //
66838 // However, if the root expression is synthesized (as in the case
66839 // of the initializer when transforming a ForOfStatement), then the source map
66840 // location should point to the right-hand value of the expression.
66841 location = value;
66842 }
66843 }
66844 flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
66845 if (value && needsValue) {
66846 if (!ts.some(expressions)) {
66847 return value;
66848 }
66849 expressions.push(value);
66850 }
66851 return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression();
66852 function emitExpression(expression) {
66853 // NOTE: this completely disables source maps, but aligns with the behavior of
66854 // `emitAssignment` in the old emitter.
66855 ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */);
66856 ts.aggregateTransformFlags(expression);
66857 expressions = ts.append(expressions, expression);
66858 }
66859 function emitBindingOrAssignment(target, value, location, original) {
66860 ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
66861 var expression = createAssignmentCallback
66862 ? createAssignmentCallback(target, value, location)
66863 : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
66864 expression.original = original;
66865 emitExpression(expression);
66866 }
66867 }
66868 ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
66869 function bindingOrAssignmentElementAssignsToName(element, escapedName) {
66870 var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
66871 if (ts.isBindingOrAssignmentPattern(target)) {
66872 return bindingOrAssignmentPatternAssignsToName(target, escapedName);
66873 }
66874 else if (ts.isIdentifier(target)) {
66875 return target.escapedText === escapedName;
66876 }
66877 return false;
66878 }
66879 function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
66880 var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
66881 for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
66882 var element = elements_3[_i];
66883 if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
66884 return true;
66885 }
66886 }
66887 return false;
66888 }
66889 /**
66890 * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
66891 *
66892 * @param node The node to flatten.
66893 * @param visitor An optional visitor used to visit initializers.
66894 * @param context The transformation context.
66895 * @param boundValue The value bound to the declaration.
66896 * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
66897 * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
66898 * @param level Indicates the extent to which flattening should occur.
66899 */
66900 function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
66901 if (hoistTempVariables === void 0) { hoistTempVariables = false; }
66902 var pendingExpressions;
66903 var pendingDeclarations = [];
66904 var declarations = [];
66905 var flattenContext = {
66906 context: context,
66907 level: level,
66908 downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
66909 hoistTempVariables: hoistTempVariables,
66910 emitExpression: emitExpression,
66911 emitBindingOrAssignment: emitBindingOrAssignment,
66912 createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
66913 createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
66914 createArrayBindingOrAssignmentElement: makeBindingElement,
66915 visitor: visitor
66916 };
66917 if (ts.isVariableDeclaration(node)) {
66918 var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
66919 if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) {
66920 // If the right-hand value of the assignment is also an assignment target then
66921 // we need to cache the right-hand value.
66922 initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
66923 node = ts.updateVariableDeclaration(node, node.name, node.type, initializer);
66924 }
66925 }
66926 flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
66927 if (pendingExpressions) {
66928 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
66929 if (hoistTempVariables) {
66930 var value = ts.inlineExpressions(pendingExpressions);
66931 pendingExpressions = undefined;
66932 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
66933 }
66934 else {
66935 context.hoistVariableDeclaration(temp);
66936 var pendingDeclaration = ts.last(pendingDeclarations);
66937 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value));
66938 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
66939 pendingDeclaration.value = temp;
66940 }
66941 }
66942 for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
66943 var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
66944 var variable = ts.createVariableDeclaration(name,
66945 /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
66946 variable.original = original;
66947 ts.setTextRange(variable, location);
66948 if (ts.isIdentifier(name)) {
66949 ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */);
66950 }
66951 ts.aggregateTransformFlags(variable);
66952 declarations.push(variable);
66953 }
66954 return declarations;
66955 function emitExpression(value) {
66956 pendingExpressions = ts.append(pendingExpressions, value);
66957 }
66958 function emitBindingOrAssignment(target, value, location, original) {
66959 ts.Debug.assertNode(target, ts.isBindingName);
66960 if (pendingExpressions) {
66961 value = ts.inlineExpressions(ts.append(pendingExpressions, value));
66962 pendingExpressions = undefined;
66963 }
66964 pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
66965 }
66966 }
66967 ts.flattenDestructuringBinding = flattenDestructuringBinding;
66968 /**
66969 * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
66970 *
66971 * @param flattenContext Options used to control flattening.
66972 * @param element The element to flatten.
66973 * @param value The current RHS value to assign to the element.
66974 * @param location The location to use for source maps and comments.
66975 * @param skipInitializer An optional value indicating whether to include the initializer
66976 * for the element.
66977 */
66978 function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
66979 if (!skipInitializer) {
66980 var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
66981 if (initializer) {
66982 // Combine value and initializer
66983 value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
66984 }
66985 else if (!value) {
66986 // Use 'void 0' in absence of value and initializer
66987 value = ts.createVoidZero();
66988 }
66989 }
66990 var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
66991 if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
66992 flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
66993 }
66994 else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
66995 flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
66996 }
66997 else {
66998 flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
66999 }
67000 }
67001 /**
67002 * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
67003 *
67004 * @param flattenContext Options used to control flattening.
67005 * @param parent The parent element of the pattern.
67006 * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
67007 * @param value The current RHS value to assign to the element.
67008 * @param location The location to use for source maps and comments.
67009 */
67010 function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
67011 var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
67012 var numElements = elements.length;
67013 if (numElements !== 1) {
67014 // For anything other than a single-element destructuring we need to generate a temporary
67015 // to ensure value is evaluated exactly once. Additionally, if we have zero elements
67016 // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
67017 // so in that case, we'll intentionally create that temporary.
67018 var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
67019 value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
67020 }
67021 var bindingElements;
67022 var computedTempVariables;
67023 for (var i = 0; i < numElements; i++) {
67024 var element = elements[i];
67025 if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
67026 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
67027 if (flattenContext.level >= 1 /* ObjectRest */
67028 && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
67029 && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
67030 && !ts.isComputedPropertyName(propertyName)) {
67031 bindingElements = ts.append(bindingElements, element);
67032 }
67033 else {
67034 if (bindingElements) {
67035 flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
67036 bindingElements = undefined;
67037 }
67038 var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
67039 if (ts.isComputedPropertyName(propertyName)) {
67040 computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
67041 }
67042 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
67043 }
67044 }
67045 else if (i === numElements - 1) {
67046 if (bindingElements) {
67047 flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
67048 bindingElements = undefined;
67049 }
67050 var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217
67051 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
67052 }
67053 }
67054 if (bindingElements) {
67055 flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
67056 }
67057 }
67058 /**
67059 * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
67060 *
67061 * @param flattenContext Options used to control flattening.
67062 * @param parent The parent element of the pattern.
67063 * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
67064 * @param value The current RHS value to assign to the element.
67065 * @param location The location to use for source maps and comments.
67066 */
67067 function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
67068 var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
67069 var numElements = elements.length;
67070 if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
67071 // Read the elements of the iterable into an array
67072 value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
67073 ? undefined
67074 : numElements, location),
67075 /*reuseIdentifierExpressions*/ false, location);
67076 }
67077 else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
67078 || ts.every(elements, ts.isOmittedExpression)) {
67079 // For anything other than a single-element destructuring we need to generate a temporary
67080 // to ensure value is evaluated exactly once. Additionally, if we have zero elements
67081 // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
67082 // so in that case, we'll intentionally create that temporary.
67083 // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
67084 // then we will create temporary variable.
67085 var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
67086 value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
67087 }
67088 var bindingElements;
67089 var restContainingElements;
67090 for (var i = 0; i < numElements; i++) {
67091 var element = elements[i];
67092 if (flattenContext.level >= 1 /* ObjectRest */) {
67093 // If an array pattern contains an ObjectRest, we must cache the result so that we
67094 // can perform the ObjectRest destructuring in a different declaration
67095 if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
67096 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
67097 if (flattenContext.hoistTempVariables) {
67098 flattenContext.context.hoistVariableDeclaration(temp);
67099 }
67100 restContainingElements = ts.append(restContainingElements, [temp, element]);
67101 bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
67102 }
67103 else {
67104 bindingElements = ts.append(bindingElements, element);
67105 }
67106 }
67107 else if (ts.isOmittedExpression(element)) {
67108 continue;
67109 }
67110 else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
67111 var rhsValue = ts.createElementAccess(value, i);
67112 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
67113 }
67114 else if (i === numElements - 1) {
67115 var rhsValue = ts.createArraySlice(value, i);
67116 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
67117 }
67118 }
67119 if (bindingElements) {
67120 flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
67121 }
67122 if (restContainingElements) {
67123 for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
67124 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
67125 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
67126 }
67127 }
67128 }
67129 /**
67130 * Creates an expression used to provide a default value if a value is `undefined` at runtime.
67131 *
67132 * @param flattenContext Options used to control flattening.
67133 * @param value The RHS value to test.
67134 * @param defaultValue The default value to use if `value` is `undefined` at runtime.
67135 * @param location The location to use for source maps and comments.
67136 */
67137 function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
67138 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
67139 return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value);
67140 }
67141 /**
67142 * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
67143 * right-hand side of a transformed destructuring assignment.
67144 *
67145 * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
67146 *
67147 * @param flattenContext Options used to control flattening.
67148 * @param value The RHS value that is the source of the property.
67149 * @param propertyName The destructuring property name.
67150 */
67151 function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
67152 if (ts.isComputedPropertyName(propertyName)) {
67153 var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
67154 return ts.createElementAccess(value, argumentExpression);
67155 }
67156 else if (ts.isStringOrNumericLiteralLike(propertyName)) {
67157 var argumentExpression = ts.getSynthesizedClone(propertyName);
67158 argumentExpression.text = argumentExpression.text;
67159 return ts.createElementAccess(value, argumentExpression);
67160 }
67161 else {
67162 var name = ts.createIdentifier(ts.idText(propertyName));
67163 return ts.createPropertyAccess(value, name);
67164 }
67165 }
67166 /**
67167 * Ensures that there exists a declared identifier whose value holds the given expression.
67168 * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
67169 * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
67170 *
67171 * @param flattenContext Options used to control flattening.
67172 * @param value the expression whose value needs to be bound.
67173 * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
67174 * false if it is necessary to always emit an identifier.
67175 * @param location The location to use for source maps and comments.
67176 */
67177 function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
67178 if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
67179 return value;
67180 }
67181 else {
67182 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
67183 if (flattenContext.hoistTempVariables) {
67184 flattenContext.context.hoistVariableDeclaration(temp);
67185 flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location));
67186 }
67187 else {
67188 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
67189 }
67190 return temp;
67191 }
67192 }
67193 function makeArrayBindingPattern(elements) {
67194 ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
67195 return ts.createArrayBindingPattern(elements);
67196 }
67197 function makeArrayAssignmentPattern(elements) {
67198 return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement));
67199 }
67200 function makeObjectBindingPattern(elements) {
67201 ts.Debug.assertEachNode(elements, ts.isBindingElement);
67202 return ts.createObjectBindingPattern(elements);
67203 }
67204 function makeObjectAssignmentPattern(elements) {
67205 return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement));
67206 }
67207 function makeBindingElement(name) {
67208 return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
67209 }
67210 function makeAssignmentElement(name) {
67211 return name;
67212 }
67213 ts.restHelper = {
67214 name: "typescript:rest",
67215 scoped: false,
67216 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++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
67217 };
67218 /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
67219 * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
67220 */
67221 function createRestCall(context, value, elements, computedTempVariables, location) {
67222 context.requestEmitHelper(ts.restHelper);
67223 var propertyNames = [];
67224 var computedTempVariableOffset = 0;
67225 for (var i = 0; i < elements.length - 1; i++) {
67226 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
67227 if (propertyName) {
67228 if (ts.isComputedPropertyName(propertyName)) {
67229 var temp = computedTempVariables[computedTempVariableOffset];
67230 computedTempVariableOffset++;
67231 // typeof _tmp === "symbol" ? _tmp : _tmp + ""
67232 propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral(""))));
67233 }
67234 else {
67235 propertyNames.push(ts.createLiteral(propertyName));
67236 }
67237 }
67238 }
67239 return ts.createCall(ts.getHelperName("__rest"),
67240 /*typeArguments*/ undefined, [
67241 value,
67242 ts.setTextRange(ts.createArrayLiteral(propertyNames), location)
67243 ]);
67244 }
67245})(ts || (ts = {}));
67246/*@internal*/
67247var ts;
67248(function (ts) {
67249 /**
67250 * Indicates whether to emit type metadata in the new format.
67251 */
67252 var USE_NEW_TYPE_METADATA_FORMAT = false;
67253 var TypeScriptSubstitutionFlags;
67254 (function (TypeScriptSubstitutionFlags) {
67255 /** Enables substitutions for decorated classes. */
67256 TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
67257 /** Enables substitutions for namespace exports. */
67258 TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
67259 /* Enables substitutions for unqualified enum members */
67260 TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
67261 })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
67262 var ClassFacts;
67263 (function (ClassFacts) {
67264 ClassFacts[ClassFacts["None"] = 0] = "None";
67265 ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
67266 ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
67267 ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
67268 ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
67269 ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
67270 ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
67271 ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
67272 ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
67273 ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
67274 ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
67275 ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
67276 ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
67277 })(ClassFacts || (ClassFacts = {}));
67278 function transformTypeScript(context) {
67279 var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
67280 var resolver = context.getEmitResolver();
67281 var compilerOptions = context.getCompilerOptions();
67282 var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
67283 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
67284 var moduleKind = ts.getEmitModuleKind(compilerOptions);
67285 // Save the previous transformation hooks.
67286 var previousOnEmitNode = context.onEmitNode;
67287 var previousOnSubstituteNode = context.onSubstituteNode;
67288 // Set new transformation hooks.
67289 context.onEmitNode = onEmitNode;
67290 context.onSubstituteNode = onSubstituteNode;
67291 // Enable substitution for property/element access to emit const enum values.
67292 context.enableSubstitution(189 /* PropertyAccessExpression */);
67293 context.enableSubstitution(190 /* ElementAccessExpression */);
67294 // These variables contain state that changes as we descend into the tree.
67295 var currentSourceFile;
67296 var currentNamespace;
67297 var currentNamespaceContainerName;
67298 var currentLexicalScope;
67299 var currentNameScope;
67300 var currentScopeFirstDeclarationsOfName;
67301 /**
67302 * Keeps track of whether expression substitution has been enabled for specific edge cases.
67303 * They are persisted between each SourceFile transformation and should not be reset.
67304 */
67305 var enabledSubstitutions;
67306 /**
67307 * A map that keeps track of aliases created for classes with decorators to avoid issues
67308 * with the double-binding behavior of classes.
67309 */
67310 var classAliases;
67311 /**
67312 * Keeps track of whether we are within any containing namespaces when performing
67313 * just-in-time substitution while printing an expression identifier.
67314 */
67315 var applicableSubstitutions;
67316 /**
67317 * Tracks what computed name expressions originating from elided names must be inlined
67318 * at the next execution site, in document order
67319 */
67320 var pendingExpressions;
67321 return transformSourceFileOrBundle;
67322 function transformSourceFileOrBundle(node) {
67323 if (node.kind === 285 /* Bundle */) {
67324 return transformBundle(node);
67325 }
67326 return transformSourceFile(node);
67327 }
67328 function transformBundle(node) {
67329 return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
67330 if (prepend.kind === 287 /* InputFiles */) {
67331 return ts.createUnparsedSourceFile(prepend, "js");
67332 }
67333 return prepend;
67334 }));
67335 }
67336 /**
67337 * Transform TypeScript-specific syntax in a SourceFile.
67338 *
67339 * @param node A SourceFile node.
67340 */
67341 function transformSourceFile(node) {
67342 if (node.isDeclarationFile) {
67343 return node;
67344 }
67345 currentSourceFile = node;
67346 var visited = saveStateAndInvoke(node, visitSourceFile);
67347 ts.addEmitHelpers(visited, context.readEmitHelpers());
67348 currentSourceFile = undefined;
67349 return visited;
67350 }
67351 /**
67352 * Visits a node, saving and restoring state variables on the stack.
67353 *
67354 * @param node The node to visit.
67355 */
67356 function saveStateAndInvoke(node, f) {
67357 // Save state
67358 var savedCurrentScope = currentLexicalScope;
67359 var savedCurrentNameScope = currentNameScope;
67360 var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
67361 // Handle state changes before visiting a node.
67362 onBeforeVisitNode(node);
67363 var visited = f(node);
67364 // Restore state
67365 if (currentLexicalScope !== savedCurrentScope) {
67366 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
67367 }
67368 currentLexicalScope = savedCurrentScope;
67369 currentNameScope = savedCurrentNameScope;
67370 return visited;
67371 }
67372 /**
67373 * Performs actions that should always occur immediately before visiting a node.
67374 *
67375 * @param node The node to visit.
67376 */
67377 function onBeforeVisitNode(node) {
67378 switch (node.kind) {
67379 case 284 /* SourceFile */:
67380 case 246 /* CaseBlock */:
67381 case 245 /* ModuleBlock */:
67382 case 218 /* Block */:
67383 currentLexicalScope = node;
67384 currentNameScope = undefined;
67385 currentScopeFirstDeclarationsOfName = undefined;
67386 break;
67387 case 240 /* ClassDeclaration */:
67388 case 239 /* FunctionDeclaration */:
67389 if (ts.hasModifier(node, 2 /* Ambient */)) {
67390 break;
67391 }
67392 // Record these declarations provided that they have a name.
67393 if (node.name) {
67394 recordEmittedDeclarationInScope(node);
67395 }
67396 else {
67397 // These nodes should always have names unless they are default-exports;
67398 // however, class declaration parsing allows for undefined names, so syntactically invalid
67399 // programs may also have an undefined name.
67400 ts.Debug.assert(node.kind === 240 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */));
67401 }
67402 if (ts.isClassDeclaration(node)) {
67403 // XXX: should probably also cover interfaces and type aliases that can have type variables?
67404 currentNameScope = node;
67405 }
67406 break;
67407 }
67408 }
67409 /**
67410 * General-purpose node visitor.
67411 *
67412 * @param node The node to visit.
67413 */
67414 function visitor(node) {
67415 return saveStateAndInvoke(node, visitorWorker);
67416 }
67417 /**
67418 * Visits and possibly transforms any node.
67419 *
67420 * @param node The node to visit.
67421 */
67422 function visitorWorker(node) {
67423 if (node.transformFlags & 1 /* ContainsTypeScript */) {
67424 return visitTypeScript(node);
67425 }
67426 return node;
67427 }
67428 /**
67429 * Specialized visitor that visits the immediate children of a SourceFile.
67430 *
67431 * @param node The node to visit.
67432 */
67433 function sourceElementVisitor(node) {
67434 return saveStateAndInvoke(node, sourceElementVisitorWorker);
67435 }
67436 /**
67437 * Specialized visitor that visits the immediate children of a SourceFile.
67438 *
67439 * @param node The node to visit.
67440 */
67441 function sourceElementVisitorWorker(node) {
67442 switch (node.kind) {
67443 case 249 /* ImportDeclaration */:
67444 case 248 /* ImportEqualsDeclaration */:
67445 case 254 /* ExportAssignment */:
67446 case 255 /* ExportDeclaration */:
67447 return visitEllidableStatement(node);
67448 default:
67449 return visitorWorker(node);
67450 }
67451 }
67452 function visitEllidableStatement(node) {
67453 var parsed = ts.getParseTreeNode(node);
67454 if (parsed !== node) {
67455 // If the node has been transformed by a `before` transformer, perform no ellision on it
67456 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
67457 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
67458 // and will trigger debug failures when debug verbosity is turned up
67459 if (node.transformFlags & 1 /* ContainsTypeScript */) {
67460 // This node contains TypeScript, so we should visit its children.
67461 return ts.visitEachChild(node, visitor, context);
67462 }
67463 // Otherwise, we can just return the node
67464 return node;
67465 }
67466 switch (node.kind) {
67467 case 249 /* ImportDeclaration */:
67468 return visitImportDeclaration(node);
67469 case 248 /* ImportEqualsDeclaration */:
67470 return visitImportEqualsDeclaration(node);
67471 case 254 /* ExportAssignment */:
67472 return visitExportAssignment(node);
67473 case 255 /* ExportDeclaration */:
67474 return visitExportDeclaration(node);
67475 default:
67476 ts.Debug.fail("Unhandled ellided statement");
67477 }
67478 }
67479 /**
67480 * Specialized visitor that visits the immediate children of a namespace.
67481 *
67482 * @param node The node to visit.
67483 */
67484 function namespaceElementVisitor(node) {
67485 return saveStateAndInvoke(node, namespaceElementVisitorWorker);
67486 }
67487 /**
67488 * Specialized visitor that visits the immediate children of a namespace.
67489 *
67490 * @param node The node to visit.
67491 */
67492 function namespaceElementVisitorWorker(node) {
67493 if (node.kind === 255 /* ExportDeclaration */ ||
67494 node.kind === 249 /* ImportDeclaration */ ||
67495 node.kind === 250 /* ImportClause */ ||
67496 (node.kind === 248 /* ImportEqualsDeclaration */ &&
67497 node.moduleReference.kind === 259 /* ExternalModuleReference */)) {
67498 // do not emit ES6 imports and exports since they are illegal inside a namespace
67499 return undefined;
67500 }
67501 else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
67502 return visitTypeScript(node);
67503 }
67504 return node;
67505 }
67506 /**
67507 * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
67508 *
67509 * @param node The node to visit.
67510 */
67511 function classElementVisitor(node) {
67512 return saveStateAndInvoke(node, classElementVisitorWorker);
67513 }
67514 /**
67515 * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
67516 *
67517 * @param node The node to visit.
67518 */
67519 function classElementVisitorWorker(node) {
67520 switch (node.kind) {
67521 case 157 /* Constructor */:
67522 // TypeScript constructors are transformed in `visitClassDeclaration`.
67523 // We elide them here as `visitorWorker` checks transform flags, which could
67524 // erronously include an ES6 constructor without TypeScript syntax.
67525 return undefined;
67526 case 154 /* PropertyDeclaration */:
67527 case 162 /* IndexSignature */:
67528 case 158 /* GetAccessor */:
67529 case 159 /* SetAccessor */:
67530 case 156 /* MethodDeclaration */:
67531 // Fallback to the default visit behavior.
67532 return visitorWorker(node);
67533 case 217 /* SemicolonClassElement */:
67534 return node;
67535 default:
67536 return ts.Debug.failBadSyntaxKind(node);
67537 }
67538 }
67539 function modifierVisitor(node) {
67540 if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
67541 return undefined;
67542 }
67543 else if (currentNamespace && node.kind === 85 /* ExportKeyword */) {
67544 return undefined;
67545 }
67546 return node;
67547 }
67548 /**
67549 * Branching visitor, visits a TypeScript syntax node.
67550 *
67551 * @param node The node to visit.
67552 */
67553 function visitTypeScript(node) {
67554 if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
67555 // TypeScript ambient declarations are elided, but some comments may be preserved.
67556 // See the implementation of `getLeadingComments` in comments.ts for more details.
67557 return ts.createNotEmittedStatement(node);
67558 }
67559 switch (node.kind) {
67560 case 85 /* ExportKeyword */:
67561 case 80 /* DefaultKeyword */:
67562 // ES6 export and default modifiers are elided when inside a namespace.
67563 return currentNamespace ? undefined : node;
67564 case 115 /* PublicKeyword */:
67565 case 113 /* PrivateKeyword */:
67566 case 114 /* ProtectedKeyword */:
67567 case 118 /* AbstractKeyword */:
67568 case 77 /* ConstKeyword */:
67569 case 125 /* DeclareKeyword */:
67570 case 133 /* ReadonlyKeyword */:
67571 // TypeScript accessibility and readonly modifiers are elided.
67572 case 169 /* ArrayType */:
67573 case 170 /* TupleType */:
67574 case 171 /* OptionalType */:
67575 case 172 /* RestType */:
67576 case 168 /* TypeLiteral */:
67577 case 163 /* TypePredicate */:
67578 case 150 /* TypeParameter */:
67579 case 120 /* AnyKeyword */:
67580 case 143 /* UnknownKeyword */:
67581 case 123 /* BooleanKeyword */:
67582 case 138 /* StringKeyword */:
67583 case 135 /* NumberKeyword */:
67584 case 132 /* NeverKeyword */:
67585 case 106 /* VoidKeyword */:
67586 case 139 /* SymbolKeyword */:
67587 case 166 /* ConstructorType */:
67588 case 165 /* FunctionType */:
67589 case 167 /* TypeQuery */:
67590 case 164 /* TypeReference */:
67591 case 173 /* UnionType */:
67592 case 174 /* IntersectionType */:
67593 case 175 /* ConditionalType */:
67594 case 177 /* ParenthesizedType */:
67595 case 178 /* ThisType */:
67596 case 179 /* TypeOperator */:
67597 case 180 /* IndexedAccessType */:
67598 case 181 /* MappedType */:
67599 case 182 /* LiteralType */:
67600 // TypeScript type nodes are elided.
67601 case 162 /* IndexSignature */:
67602 // TypeScript index signatures are elided.
67603 case 152 /* Decorator */:
67604 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
67605 case 242 /* TypeAliasDeclaration */:
67606 // TypeScript type-only declarations are elided.
67607 return undefined;
67608 case 154 /* PropertyDeclaration */:
67609 // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
67610 return visitPropertyDeclaration(node);
67611 case 247 /* NamespaceExportDeclaration */:
67612 // TypeScript namespace export declarations are elided.
67613 return undefined;
67614 case 157 /* Constructor */:
67615 return visitConstructor(node);
67616 case 241 /* InterfaceDeclaration */:
67617 // TypeScript interfaces are elided, but some comments may be preserved.
67618 // See the implementation of `getLeadingComments` in comments.ts for more details.
67619 return ts.createNotEmittedStatement(node);
67620 case 240 /* ClassDeclaration */:
67621 // This may be a class declaration with TypeScript syntax extensions.
67622 //
67623 // TypeScript class syntax extensions include:
67624 // - decorators
67625 // - optional `implements` heritage clause
67626 // - parameter property assignments in the constructor
67627 // - property declarations
67628 // - index signatures
67629 // - method overload signatures
67630 return visitClassDeclaration(node);
67631 case 209 /* ClassExpression */:
67632 // This may be a class expression with TypeScript syntax extensions.
67633 //
67634 // TypeScript class syntax extensions include:
67635 // - decorators
67636 // - optional `implements` heritage clause
67637 // - parameter property assignments in the constructor
67638 // - property declarations
67639 // - index signatures
67640 // - method overload signatures
67641 return visitClassExpression(node);
67642 case 273 /* HeritageClause */:
67643 // This may be a heritage clause with TypeScript syntax extensions.
67644 //
67645 // TypeScript heritage clause extensions include:
67646 // - `implements` clause
67647 return visitHeritageClause(node);
67648 case 211 /* ExpressionWithTypeArguments */:
67649 // TypeScript supports type arguments on an expression in an `extends` heritage clause.
67650 return visitExpressionWithTypeArguments(node);
67651 case 156 /* MethodDeclaration */:
67652 // TypeScript method declarations may have decorators, modifiers
67653 // or type annotations.
67654 return visitMethodDeclaration(node);
67655 case 158 /* GetAccessor */:
67656 // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
67657 return visitGetAccessor(node);
67658 case 159 /* SetAccessor */:
67659 // Set Accessors can have TypeScript modifiers and type annotations.
67660 return visitSetAccessor(node);
67661 case 239 /* FunctionDeclaration */:
67662 // Typescript function declarations can have modifiers, decorators, and type annotations.
67663 return visitFunctionDeclaration(node);
67664 case 196 /* FunctionExpression */:
67665 // TypeScript function expressions can have modifiers and type annotations.
67666 return visitFunctionExpression(node);
67667 case 197 /* ArrowFunction */:
67668 // TypeScript arrow functions can have modifiers and type annotations.
67669 return visitArrowFunction(node);
67670 case 151 /* Parameter */:
67671 // This may be a parameter declaration with TypeScript syntax extensions.
67672 //
67673 // TypeScript parameter declaration syntax extensions include:
67674 // - decorators
67675 // - accessibility modifiers
67676 // - the question mark (?) token for optional parameters
67677 // - type annotations
67678 // - this parameters
67679 return visitParameter(node);
67680 case 195 /* ParenthesizedExpression */:
67681 // ParenthesizedExpressions are TypeScript if their expression is a
67682 // TypeAssertion or AsExpression
67683 return visitParenthesizedExpression(node);
67684 case 194 /* TypeAssertionExpression */:
67685 case 212 /* AsExpression */:
67686 // TypeScript type assertions are removed, but their subtrees are preserved.
67687 return visitAssertionExpression(node);
67688 case 191 /* CallExpression */:
67689 return visitCallExpression(node);
67690 case 192 /* NewExpression */:
67691 return visitNewExpression(node);
67692 case 193 /* TaggedTemplateExpression */:
67693 return visitTaggedTemplateExpression(node);
67694 case 213 /* NonNullExpression */:
67695 // TypeScript non-null expressions are removed, but their subtrees are preserved.
67696 return visitNonNullExpression(node);
67697 case 243 /* EnumDeclaration */:
67698 // TypeScript enum declarations do not exist in ES6 and must be rewritten.
67699 return visitEnumDeclaration(node);
67700 case 219 /* VariableStatement */:
67701 // TypeScript namespace exports for variable statements must be transformed.
67702 return visitVariableStatement(node);
67703 case 237 /* VariableDeclaration */:
67704 return visitVariableDeclaration(node);
67705 case 244 /* ModuleDeclaration */:
67706 // TypeScript namespace declarations must be transformed.
67707 return visitModuleDeclaration(node);
67708 case 248 /* ImportEqualsDeclaration */:
67709 // TypeScript namespace or external module import.
67710 return visitImportEqualsDeclaration(node);
67711 default:
67712 // node contains some other TypeScript syntax
67713 return ts.visitEachChild(node, visitor, context);
67714 }
67715 }
67716 function visitSourceFile(node) {
67717 var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
67718 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
67719 !ts.isJsonSourceFile(node);
67720 return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
67721 }
67722 /**
67723 * Tests whether we should emit a __decorate call for a class declaration.
67724 */
67725 function shouldEmitDecorateCallForClass(node) {
67726 if (node.decorators && node.decorators.length > 0) {
67727 return true;
67728 }
67729 var constructor = ts.getFirstConstructorWithBody(node);
67730 if (constructor) {
67731 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
67732 }
67733 return false;
67734 }
67735 /**
67736 * Tests whether we should emit a __decorate call for a parameter declaration.
67737 */
67738 function shouldEmitDecorateCallForParameter(parameter) {
67739 return parameter.decorators !== undefined && parameter.decorators.length > 0;
67740 }
67741 function getClassFacts(node, staticProperties) {
67742 var facts = 0 /* None */;
67743 if (ts.some(staticProperties))
67744 facts |= 1 /* HasStaticInitializedProperties */;
67745 var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
67746 if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */)
67747 facts |= 64 /* IsDerivedClass */;
67748 if (shouldEmitDecorateCallForClass(node))
67749 facts |= 2 /* HasConstructorDecorators */;
67750 if (ts.childIsDecorated(node))
67751 facts |= 4 /* HasMemberDecorators */;
67752 if (isExportOfNamespace(node))
67753 facts |= 8 /* IsExportOfNamespace */;
67754 else if (isDefaultExternalModuleExport(node))
67755 facts |= 32 /* IsDefaultExternalExport */;
67756 else if (isNamedExternalModuleExport(node))
67757 facts |= 16 /* IsNamedExternalExport */;
67758 if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
67759 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
67760 return facts;
67761 }
67762 function hasTypeScriptClassSyntax(node) {
67763 return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */);
67764 }
67765 function isClassLikeDeclarationWithTypeScriptSyntax(node) {
67766 return ts.some(node.decorators)
67767 || ts.some(node.typeParameters)
67768 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
67769 || ts.some(node.members, hasTypeScriptClassSyntax);
67770 }
67771 function visitClassDeclaration(node) {
67772 if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
67773 return ts.visitEachChild(node, visitor, context);
67774 }
67775 var savedPendingExpressions = pendingExpressions;
67776 pendingExpressions = undefined;
67777 var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
67778 var facts = getClassFacts(node, staticProperties);
67779 if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
67780 context.startLexicalEnvironment();
67781 }
67782 var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined);
67783 var classStatement = facts & 2 /* HasConstructorDecorators */
67784 ? createClassDeclarationHeadWithDecorators(node, name, facts)
67785 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
67786 var statements = [classStatement];
67787 // Write any pending expressions from elided or moved computed property names
67788 if (ts.some(pendingExpressions)) {
67789 statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
67790 }
67791 pendingExpressions = savedPendingExpressions;
67792 // Emit static property assignment. Because classDeclaration is lexically evaluated,
67793 // it is safe to emit static property assignment after classDeclaration
67794 // From ES6 specification:
67795 // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
67796 // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
67797 if (facts & 1 /* HasStaticInitializedProperties */) {
67798 addInitializedPropertyStatements(statements, staticProperties, facts & 128 /* UseImmediatelyInvokedFunctionExpression */ ? ts.getInternalName(node) : ts.getLocalName(node));
67799 }
67800 // Write any decorators of the node.
67801 addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
67802 addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
67803 addConstructorDecorationStatement(statements, node);
67804 if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
67805 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
67806 // 'es2015' transformer can properly nest static initializers and decorators. The result
67807 // looks something like:
67808 //
67809 // var C = function () {
67810 // class C {
67811 // }
67812 // C.static_prop = 1;
67813 // return C;
67814 // }();
67815 //
67816 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
67817 var localName = ts.getInternalName(node);
67818 // The following partially-emitted expression exists purely to align our sourcemap
67819 // emit with the original emitter.
67820 var outer = ts.createPartiallyEmittedExpression(localName);
67821 outer.end = closingBraceLocation.end;
67822 ts.setEmitFlags(outer, 1536 /* NoComments */);
67823 var statement = ts.createReturn(outer);
67824 statement.pos = closingBraceLocation.pos;
67825 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
67826 statements.push(statement);
67827 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
67828 var iife = ts.createImmediatelyInvokedArrowFunction(statements);
67829 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
67830 var varStatement = ts.createVariableStatement(
67831 /*modifiers*/ undefined, ts.createVariableDeclarationList([
67832 ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false),
67833 /*type*/ undefined, iife)
67834 ]));
67835 ts.setOriginalNode(varStatement, node);
67836 ts.setCommentRange(varStatement, node);
67837 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
67838 ts.startOnNewLine(varStatement);
67839 statements = [varStatement];
67840 }
67841 // If the class is exported as part of a TypeScript namespace, emit the namespace export.
67842 // Otherwise, if the class was exported at the top level and was decorated, emit an export
67843 // declaration or export default for the class.
67844 if (facts & 8 /* IsExportOfNamespace */) {
67845 addExportMemberAssignment(statements, node);
67846 }
67847 else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
67848 if (facts & 32 /* IsDefaultExternalExport */) {
67849 statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
67850 }
67851 else if (facts & 16 /* IsNamedExternalExport */) {
67852 statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
67853 }
67854 }
67855 if (statements.length > 1) {
67856 // Add a DeclarationMarker as a marker for the end of the declaration
67857 statements.push(ts.createEndOfDeclarationMarker(node));
67858 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
67859 }
67860 return ts.singleOrMany(statements);
67861 }
67862 /**
67863 * Transforms a non-decorated class declaration and appends the resulting statements.
67864 *
67865 * @param node A ClassDeclaration node.
67866 * @param name The name of the class.
67867 * @param facts Precomputed facts about the class.
67868 */
67869 function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
67870 // ${modifiers} class ${name} ${heritageClauses} {
67871 // ${members}
67872 // }
67873 // we do not emit modifiers on the declaration if we are emitting an IIFE
67874 var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
67875 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
67876 : undefined;
67877 var classDeclaration = ts.createClassDeclaration(
67878 /*decorators*/ undefined, modifiers, name,
67879 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0));
67880 // To better align with the old emitter, we should not emit a trailing source map
67881 // entry if the class has static properties.
67882 var emitFlags = ts.getEmitFlags(node);
67883 if (facts & 1 /* HasStaticInitializedProperties */) {
67884 emitFlags |= 32 /* NoTrailingSourceMap */;
67885 }
67886 ts.setTextRange(classDeclaration, node);
67887 ts.setOriginalNode(classDeclaration, node);
67888 ts.setEmitFlags(classDeclaration, emitFlags);
67889 return classDeclaration;
67890 }
67891 /**
67892 * Transforms a decorated class declaration and appends the resulting statements. If
67893 * the class requires an alias to avoid issues with double-binding, the alias is returned.
67894 */
67895 function createClassDeclarationHeadWithDecorators(node, name, facts) {
67896 // When we emit an ES6 class that has a class decorator, we must tailor the
67897 // emit to certain specific cases.
67898 //
67899 // In the simplest case, we emit the class declaration as a let declaration, and
67900 // evaluate decorators after the close of the class body:
67901 //
67902 // [Example 1]
67903 // ---------------------------------------------------------------------
67904 // TypeScript | Javascript
67905 // ---------------------------------------------------------------------
67906 // @dec | let C = class C {
67907 // class C { | }
67908 // } | C = __decorate([dec], C);
67909 // ---------------------------------------------------------------------
67910 // @dec | let C = class C {
67911 // export class C { | }
67912 // } | C = __decorate([dec], C);
67913 // | export { C };
67914 // ---------------------------------------------------------------------
67915 //
67916 // If a class declaration contains a reference to itself *inside* of the class body,
67917 // this introduces two bindings to the class: One outside of the class body, and one
67918 // inside of the class body. If we apply decorators as in [Example 1] above, there
67919 // is the possibility that the decorator `dec` will return a new value for the
67920 // constructor, which would result in the binding inside of the class no longer
67921 // pointing to the same reference as the binding outside of the class.
67922 //
67923 // As a result, we must instead rewrite all references to the class *inside* of the
67924 // class body to instead point to a local temporary alias for the class:
67925 //
67926 // [Example 2]
67927 // ---------------------------------------------------------------------
67928 // TypeScript | Javascript
67929 // ---------------------------------------------------------------------
67930 // @dec | let C = C_1 = class C {
67931 // class C { | static x() { return C_1.y; }
67932 // static x() { return C.y; } | }
67933 // static y = 1; | C.y = 1;
67934 // } | C = C_1 = __decorate([dec], C);
67935 // | var C_1;
67936 // ---------------------------------------------------------------------
67937 // @dec | let C = class C {
67938 // export class C { | static x() { return C_1.y; }
67939 // static x() { return C.y; } | }
67940 // static y = 1; | C.y = 1;
67941 // } | C = C_1 = __decorate([dec], C);
67942 // | export { C };
67943 // | var C_1;
67944 // ---------------------------------------------------------------------
67945 //
67946 // If a class declaration is the default export of a module, we instead emit
67947 // the export after the decorated declaration:
67948 //
67949 // [Example 3]
67950 // ---------------------------------------------------------------------
67951 // TypeScript | Javascript
67952 // ---------------------------------------------------------------------
67953 // @dec | let default_1 = class {
67954 // export default class { | }
67955 // } | default_1 = __decorate([dec], default_1);
67956 // | export default default_1;
67957 // ---------------------------------------------------------------------
67958 // @dec | let C = class C {
67959 // export default class C { | }
67960 // } | C = __decorate([dec], C);
67961 // | export default C;
67962 // ---------------------------------------------------------------------
67963 //
67964 // If the class declaration is the default export and a reference to itself
67965 // inside of the class body, we must emit both an alias for the class *and*
67966 // move the export after the declaration:
67967 //
67968 // [Example 4]
67969 // ---------------------------------------------------------------------
67970 // TypeScript | Javascript
67971 // ---------------------------------------------------------------------
67972 // @dec | let C = class C {
67973 // export default class C { | static x() { return C_1.y; }
67974 // static x() { return C.y; } | }
67975 // static y = 1; | C.y = 1;
67976 // } | C = C_1 = __decorate([dec], C);
67977 // | export default C;
67978 // | var C_1;
67979 // ---------------------------------------------------------------------
67980 //
67981 var location = ts.moveRangePastDecorators(node);
67982 var classAlias = getClassAliasIfNeeded(node);
67983 var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
67984 // ... = class ${name} ${heritageClauses} {
67985 // ${members}
67986 // }
67987 var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
67988 var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0);
67989 var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
67990 ts.setOriginalNode(classExpression, node);
67991 ts.setTextRange(classExpression, location);
67992 // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
67993 // or decoratedClassAlias if the class contain self-reference.
67994 var statement = ts.createVariableStatement(
67995 /*modifiers*/ undefined, ts.createVariableDeclarationList([
67996 ts.createVariableDeclaration(declName,
67997 /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression)
67998 ], 1 /* Let */));
67999 ts.setOriginalNode(statement, node);
68000 ts.setTextRange(statement, location);
68001 ts.setCommentRange(statement, node);
68002 return statement;
68003 }
68004 function visitClassExpression(node) {
68005 if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
68006 return ts.visitEachChild(node, visitor, context);
68007 }
68008 var savedPendingExpressions = pendingExpressions;
68009 pendingExpressions = undefined;
68010 var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
68011 var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
68012 var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 86 /* ExtendsKeyword */; }));
68013 var classExpression = ts.createClassExpression(
68014 /*modifiers*/ undefined, node.name,
68015 /*typeParameters*/ undefined, heritageClauses, members);
68016 ts.setOriginalNode(classExpression, node);
68017 ts.setTextRange(classExpression, node);
68018 if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
68019 var expressions = [];
68020 var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
68021 var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
68022 if (isClassWithConstructorReference) {
68023 // record an alias as the class name is not in scope for statics.
68024 enableSubstitutionForClassAliases();
68025 var alias = ts.getSynthesizedClone(temp);
68026 alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
68027 classAliases[ts.getOriginalNodeId(node)] = alias;
68028 }
68029 // To preserve the behavior of the old emitter, we explicitly indent
68030 // the body of a class with static initializers.
68031 ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
68032 expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression)));
68033 // Add any pending expressions leftover from elided or relocated computed property names
68034 ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
68035 pendingExpressions = savedPendingExpressions;
68036 ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
68037 expressions.push(ts.startOnNewLine(temp));
68038 return ts.inlineExpressions(expressions);
68039 }
68040 pendingExpressions = savedPendingExpressions;
68041 return classExpression;
68042 }
68043 /**
68044 * Transforms the members of a class.
68045 *
68046 * @param node The current class.
68047 * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'.
68048 */
68049 function transformClassMembers(node, isDerivedClass) {
68050 var members = [];
68051 var constructor = transformConstructor(node, isDerivedClass);
68052 if (constructor) {
68053 members.push(constructor);
68054 }
68055 ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
68056 return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
68057 }
68058 /**
68059 * Transforms (or creates) a constructor for a class.
68060 *
68061 * @param node The current class.
68062 * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'.
68063 */
68064 function transformConstructor(node, isDerivedClass) {
68065 // Check if we have property assignment inside class declaration.
68066 // If there is a property assignment, we need to emit constructor whether users define it or not
68067 // If there is no property assignment, we can omit constructor if users do not define it
68068 var constructor = ts.getFirstConstructorWithBody(node);
68069 var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty);
68070 var hasParameterPropertyAssignments = constructor &&
68071 constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ &&
68072 ts.forEach(constructor.parameters, isParameterWithPropertyAssignment);
68073 // If the class does not contain nodes that require a synthesized constructor,
68074 // accept the current constructor if it exists.
68075 if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) {
68076 return ts.visitEachChild(constructor, visitor, context);
68077 }
68078 var parameters = transformConstructorParameters(constructor);
68079 var body = transformConstructorBody(node, constructor, isDerivedClass);
68080 // constructor(${parameters}) {
68081 // ${body}
68082 // }
68083 return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(
68084 /*decorators*/ undefined,
68085 /*modifiers*/ undefined, parameters, body), constructor || node), constructor));
68086 }
68087 /**
68088 * Transforms (or creates) the parameters for the constructor of a class with
68089 * parameter property assignments or instance property initializers.
68090 *
68091 * @param constructor The constructor declaration.
68092 */
68093 function transformConstructorParameters(constructor) {
68094 // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation:
68095 // If constructor is empty, then
68096 // If ClassHeritag_eopt is present and protoParent is not null, then
68097 // Let constructor be the result of parsing the source text
68098 // constructor(...args) { super (...args);}
68099 // using the syntactic grammar with the goal symbol MethodDefinition[~Yield].
68100 // Else,
68101 // Let constructor be the result of parsing the source text
68102 // constructor( ){ }
68103 // using the syntactic grammar with the goal symbol MethodDefinition[~Yield].
68104 //
68105 // While we could emit the '...args' rest parameter, certain later tools in the pipeline might
68106 // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array.
68107 // Instead, we'll avoid using a rest parameter and spread into the super call as
68108 // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody".
68109 return ts.visitParameterList(constructor && constructor.parameters, visitor, context)
68110 || [];
68111 }
68112 /**
68113 * Transforms (or creates) a constructor body for a class with parameter property
68114 * assignments or instance property initializers.
68115 *
68116 * @param node The current class.
68117 * @param constructor The current class constructor.
68118 * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'.
68119 */
68120 function transformConstructorBody(node, constructor, isDerivedClass) {
68121 var statements = [];
68122 var indexOfFirstStatement = 0;
68123 resumeLexicalEnvironment();
68124 if (constructor) {
68125 indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements);
68126 // Add parameters with property assignments. Transforms this:
68127 //
68128 // constructor (public x, public y) {
68129 // }
68130 //
68131 // Into this:
68132 //
68133 // constructor (x, y) {
68134 // this.x = x;
68135 // this.y = y;
68136 // }
68137 //
68138 var propertyAssignments = getParametersWithPropertyAssignments(constructor);
68139 ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment));
68140 }
68141 else if (isDerivedClass) {
68142 // Add a synthetic `super` call:
68143 //
68144 // super(...arguments);
68145 //
68146 statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(),
68147 /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))])));
68148 }
68149 // Add the property initializers. Transforms this:
68150 //
68151 // public x = 1;
68152 //
68153 // Into this:
68154 //
68155 // constructor() {
68156 // this.x = 1;
68157 // }
68158 //
68159 var properties = getInitializedProperties(node, /*isStatic*/ false);
68160 addInitializedPropertyStatements(statements, properties, ts.createThis());
68161 if (constructor) {
68162 // The class already had a constructor, so we should add the existing statements, skipping the initial super call.
68163 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
68164 }
68165 // End the lexical environment.
68166 statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
68167 return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
68168 /*location*/ constructor ? constructor.body.statements : node.members),
68169 /*multiLine*/ true),
68170 /*location*/ constructor ? constructor.body : undefined);
68171 }
68172 /**
68173 * Adds super call and preceding prologue directives into the list of statements.
68174 *
68175 * @param ctor The constructor node.
68176 * @returns index of the statement that follows super call
68177 */
68178 function addPrologueDirectivesAndInitialSuperCall(ctor, result) {
68179 if (ctor.body) {
68180 var statements = ctor.body.statements;
68181 // add prologue directives to the list (if any)
68182 var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
68183 if (index === statements.length) {
68184 // list contains nothing but prologue directives (or empty) - exit
68185 return index;
68186 }
68187 var statement = statements[index];
68188 if (statement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
68189 result.push(ts.visitNode(statement, visitor, ts.isStatement));
68190 return index + 1;
68191 }
68192 return index;
68193 }
68194 return 0;
68195 }
68196 /**
68197 * Gets all parameters of a constructor that should be transformed into property assignments.
68198 *
68199 * @param node The constructor node.
68200 */
68201 function getParametersWithPropertyAssignments(node) {
68202 return ts.filter(node.parameters, isParameterWithPropertyAssignment);
68203 }
68204 /**
68205 * Determines whether a parameter should be transformed into a property assignment.
68206 *
68207 * @param parameter The parameter node.
68208 */
68209 function isParameterWithPropertyAssignment(parameter) {
68210 return ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */)
68211 && ts.isIdentifier(parameter.name);
68212 }
68213 /**
68214 * Transforms a parameter into a property assignment statement.
68215 *
68216 * @param node The parameter declaration.
68217 */
68218 function transformParameterWithPropertyAssignment(node) {
68219 ts.Debug.assert(ts.isIdentifier(node.name));
68220 var name = node.name;
68221 var propertyName = ts.getMutableClone(name);
68222 ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
68223 var localName = ts.getMutableClone(name);
68224 ts.setEmitFlags(localName, 1536 /* NoComments */);
68225 return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */));
68226 }
68227 /**
68228 * Gets all property declarations with initializers on either the static or instance side of a class.
68229 *
68230 * @param node The class node.
68231 * @param isStatic A value indicating whether to get properties from the static or instance side of the class.
68232 */
68233 function getInitializedProperties(node, isStatic) {
68234 return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty);
68235 }
68236 /**
68237 * Gets a value indicating whether a class element is a static property declaration with an initializer.
68238 *
68239 * @param member The class element node.
68240 */
68241 function isStaticInitializedProperty(member) {
68242 return isInitializedProperty(member, /*isStatic*/ true);
68243 }
68244 /**
68245 * Gets a value indicating whether a class element is an instance property declaration with an initializer.
68246 *
68247 * @param member The class element node.
68248 */
68249 function isInstanceInitializedProperty(member) {
68250 return isInitializedProperty(member, /*isStatic*/ false);
68251 }
68252 /**
68253 * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
68254 *
68255 * @param member The class element node.
68256 * @param isStatic A value indicating whether the member should be a static or instance member.
68257 */
68258 function isInitializedProperty(member, isStatic) {
68259 return member.kind === 154 /* PropertyDeclaration */
68260 && isStatic === ts.hasModifier(member, 32 /* Static */)
68261 && member.initializer !== undefined;
68262 }
68263 /**
68264 * Generates assignment statements for property initializers.
68265 *
68266 * @param properties An array of property declarations to transform.
68267 * @param receiver The receiver on which each property should be assigned.
68268 */
68269 function addInitializedPropertyStatements(statements, properties, receiver) {
68270 for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
68271 var property = properties_8[_i];
68272 var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver));
68273 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
68274 ts.setCommentRange(statement, property);
68275 ts.setOriginalNode(statement, property);
68276 statements.push(statement);
68277 }
68278 }
68279 /**
68280 * Generates assignment expressions for property initializers.
68281 *
68282 * @param properties An array of property declarations to transform.
68283 * @param receiver The receiver on which each property should be assigned.
68284 */
68285 function generateInitializedPropertyExpressions(properties, receiver) {
68286 var expressions = [];
68287 for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
68288 var property = properties_9[_i];
68289 var expression = transformInitializedProperty(property, receiver);
68290 ts.startOnNewLine(expression);
68291 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
68292 ts.setCommentRange(expression, property);
68293 ts.setOriginalNode(expression, property);
68294 expressions.push(expression);
68295 }
68296 return expressions;
68297 }
68298 /**
68299 * Transforms a property initializer into an assignment statement.
68300 *
68301 * @param property The property declaration.
68302 * @param receiver The object receiving the property assignment.
68303 */
68304 function transformInitializedProperty(property, receiver) {
68305 // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
68306 var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression)
68307 ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
68308 : property.name;
68309 var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression);
68310 var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
68311 return ts.createAssignment(memberAccess, initializer);
68312 }
68313 /**
68314 * Gets either the static or instance members of a class that are decorated, or have
68315 * parameters that are decorated.
68316 *
68317 * @param node The class containing the member.
68318 * @param isStatic A value indicating whether to retrieve static or instance members of
68319 * the class.
68320 */
68321 function getDecoratedClassElements(node, isStatic) {
68322 return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
68323 }
68324 /**
68325 * Determines whether a class member is a static member of a class that is decorated, or
68326 * has parameters that are decorated.
68327 *
68328 * @param member The class member.
68329 */
68330 function isStaticDecoratedClassElement(member, parent) {
68331 return isDecoratedClassElement(member, /*isStatic*/ true, parent);
68332 }
68333 /**
68334 * Determines whether a class member is an instance member of a class that is decorated,
68335 * or has parameters that are decorated.
68336 *
68337 * @param member The class member.
68338 */
68339 function isInstanceDecoratedClassElement(member, parent) {
68340 return isDecoratedClassElement(member, /*isStatic*/ false, parent);
68341 }
68342 /**
68343 * Determines whether a class member is either a static or an instance member of a class
68344 * that is decorated, or has parameters that are decorated.
68345 *
68346 * @param member The class member.
68347 */
68348 function isDecoratedClassElement(member, isStatic, parent) {
68349 return ts.nodeOrChildIsDecorated(member, parent)
68350 && isStatic === ts.hasModifier(member, 32 /* Static */);
68351 }
68352 /**
68353 * Gets an array of arrays of decorators for the parameters of a function-like node.
68354 * The offset into the result array should correspond to the offset of the parameter.
68355 *
68356 * @param node The function-like node.
68357 */
68358 function getDecoratorsOfParameters(node) {
68359 var decorators;
68360 if (node) {
68361 var parameters = node.parameters;
68362 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
68363 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
68364 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
68365 for (var i = 0; i < numParameters; i++) {
68366 var parameter = parameters[i + firstParameterOffset];
68367 if (decorators || parameter.decorators) {
68368 if (!decorators) {
68369 decorators = new Array(numParameters);
68370 }
68371 decorators[i] = parameter.decorators;
68372 }
68373 }
68374 }
68375 return decorators;
68376 }
68377 /**
68378 * Gets an AllDecorators object containing the decorators for the class and the decorators for the
68379 * parameters of the constructor of the class.
68380 *
68381 * @param node The class node.
68382 */
68383 function getAllDecoratorsOfConstructor(node) {
68384 var decorators = node.decorators;
68385 var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
68386 if (!decorators && !parameters) {
68387 return undefined;
68388 }
68389 return {
68390 decorators: decorators,
68391 parameters: parameters
68392 };
68393 }
68394 /**
68395 * Gets an AllDecorators object containing the decorators for the member and its parameters.
68396 *
68397 * @param node The class node that contains the member.
68398 * @param member The class member.
68399 */
68400 function getAllDecoratorsOfClassElement(node, member) {
68401 switch (member.kind) {
68402 case 158 /* GetAccessor */:
68403 case 159 /* SetAccessor */:
68404 return getAllDecoratorsOfAccessors(node, member);
68405 case 156 /* MethodDeclaration */:
68406 return getAllDecoratorsOfMethod(member);
68407 case 154 /* PropertyDeclaration */:
68408 return getAllDecoratorsOfProperty(member);
68409 default:
68410 return undefined;
68411 }
68412 }
68413 /**
68414 * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
68415 *
68416 * @param node The class node that contains the accessor.
68417 * @param accessor The class accessor member.
68418 */
68419 function getAllDecoratorsOfAccessors(node, accessor) {
68420 if (!accessor.body) {
68421 return undefined;
68422 }
68423 var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
68424 var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
68425 if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
68426 return undefined;
68427 }
68428 var decorators = firstAccessorWithDecorators.decorators;
68429 var parameters = getDecoratorsOfParameters(setAccessor);
68430 if (!decorators && !parameters) {
68431 return undefined;
68432 }
68433 return { decorators: decorators, parameters: parameters };
68434 }
68435 /**
68436 * Gets an AllDecorators object containing the decorators for the method and its parameters.
68437 *
68438 * @param method The class method member.
68439 */
68440 function getAllDecoratorsOfMethod(method) {
68441 if (!method.body) {
68442 return undefined;
68443 }
68444 var decorators = method.decorators;
68445 var parameters = getDecoratorsOfParameters(method);
68446 if (!decorators && !parameters) {
68447 return undefined;
68448 }
68449 return { decorators: decorators, parameters: parameters };
68450 }
68451 /**
68452 * Gets an AllDecorators object containing the decorators for the property.
68453 *
68454 * @param property The class property member.
68455 */
68456 function getAllDecoratorsOfProperty(property) {
68457 var decorators = property.decorators;
68458 if (!decorators) {
68459 return undefined;
68460 }
68461 return { decorators: decorators };
68462 }
68463 /**
68464 * Transforms all of the decorators for a declaration into an array of expressions.
68465 *
68466 * @param node The declaration node.
68467 * @param allDecorators An object containing all of the decorators for the declaration.
68468 */
68469 function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
68470 if (!allDecorators) {
68471 return undefined;
68472 }
68473 var decoratorExpressions = [];
68474 ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
68475 ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
68476 addTypeMetadata(node, container, decoratorExpressions);
68477 return decoratorExpressions;
68478 }
68479 /**
68480 * Generates statements used to apply decorators to either the static or instance members
68481 * of a class.
68482 *
68483 * @param node The class node.
68484 * @param isStatic A value indicating whether to generate statements for static or
68485 * instance members.
68486 */
68487 function addClassElementDecorationStatements(statements, node, isStatic) {
68488 ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
68489 }
68490 /**
68491 * Generates expressions used to apply decorators to either the static or instance members
68492 * of a class.
68493 *
68494 * @param node The class node.
68495 * @param isStatic A value indicating whether to generate expressions for static or
68496 * instance members.
68497 */
68498 function generateClassElementDecorationExpressions(node, isStatic) {
68499 var members = getDecoratedClassElements(node, isStatic);
68500 var expressions;
68501 for (var _i = 0, members_5 = members; _i < members_5.length; _i++) {
68502 var member = members_5[_i];
68503 var expression = generateClassElementDecorationExpression(node, member);
68504 if (expression) {
68505 if (!expressions) {
68506 expressions = [expression];
68507 }
68508 else {
68509 expressions.push(expression);
68510 }
68511 }
68512 }
68513 return expressions;
68514 }
68515 /**
68516 * Generates an expression used to evaluate class element decorators at runtime.
68517 *
68518 * @param node The class node that contains the member.
68519 * @param member The class member.
68520 */
68521 function generateClassElementDecorationExpression(node, member) {
68522 var allDecorators = getAllDecoratorsOfClassElement(node, member);
68523 var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
68524 if (!decoratorExpressions) {
68525 return undefined;
68526 }
68527 // Emit the call to __decorate. Given the following:
68528 //
68529 // class C {
68530 // @dec method(@dec2 x) {}
68531 // @dec get accessor() {}
68532 // @dec prop;
68533 // }
68534 //
68535 // The emit for a method is:
68536 //
68537 // __decorate([
68538 // dec,
68539 // __param(0, dec2),
68540 // __metadata("design:type", Function),
68541 // __metadata("design:paramtypes", [Object]),
68542 // __metadata("design:returntype", void 0)
68543 // ], C.prototype, "method", null);
68544 //
68545 // The emit for an accessor is:
68546 //
68547 // __decorate([
68548 // dec
68549 // ], C.prototype, "accessor", null);
68550 //
68551 // The emit for a property is:
68552 //
68553 // __decorate([
68554 // dec
68555 // ], C.prototype, "prop");
68556 //
68557 var prefix = getClassMemberPrefix(node, member);
68558 var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
68559 var descriptor = languageVersion > 0 /* ES3 */
68560 ? member.kind === 154 /* PropertyDeclaration */
68561 // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
68562 // should not invoke `Object.getOwnPropertyDescriptor`.
68563 ? ts.createVoidZero()
68564 // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
68565 // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
68566 : ts.createNull()
68567 : undefined;
68568 var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member));
68569 ts.setEmitFlags(helper, 1536 /* NoComments */);
68570 return helper;
68571 }
68572 /**
68573 * Generates a __decorate helper call for a class constructor.
68574 *
68575 * @param node The class node.
68576 */
68577 function addConstructorDecorationStatement(statements, node) {
68578 var expression = generateConstructorDecorationExpression(node);
68579 if (expression) {
68580 statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node));
68581 }
68582 }
68583 /**
68584 * Generates a __decorate helper call for a class constructor.
68585 *
68586 * @param node The class node.
68587 */
68588 function generateConstructorDecorationExpression(node) {
68589 var allDecorators = getAllDecoratorsOfConstructor(node);
68590 var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
68591 if (!decoratorExpressions) {
68592 return undefined;
68593 }
68594 var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
68595 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
68596 var decorate = createDecorateHelper(context, decoratorExpressions, localName);
68597 var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate);
68598 ts.setEmitFlags(expression, 1536 /* NoComments */);
68599 ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
68600 return expression;
68601 }
68602 /**
68603 * Transforms a decorator into an expression.
68604 *
68605 * @param decorator The decorator node.
68606 */
68607 function transformDecorator(decorator) {
68608 return ts.visitNode(decorator.expression, visitor, ts.isExpression);
68609 }
68610 /**
68611 * Transforms the decorators of a parameter.
68612 *
68613 * @param decorators The decorators for the parameter at the provided offset.
68614 * @param parameterOffset The offset of the parameter.
68615 */
68616 function transformDecoratorsOfParameter(decorators, parameterOffset) {
68617 var expressions;
68618 if (decorators) {
68619 expressions = [];
68620 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
68621 var decorator = decorators_1[_i];
68622 var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset,
68623 /*location*/ decorator.expression);
68624 ts.setEmitFlags(helper, 1536 /* NoComments */);
68625 expressions.push(helper);
68626 }
68627 }
68628 return expressions;
68629 }
68630 /**
68631 * Adds optional type metadata for a declaration.
68632 *
68633 * @param node The declaration node.
68634 * @param decoratorExpressions The destination array to which to add new decorator expressions.
68635 */
68636 function addTypeMetadata(node, container, decoratorExpressions) {
68637 if (USE_NEW_TYPE_METADATA_FORMAT) {
68638 addNewTypeMetadata(node, container, decoratorExpressions);
68639 }
68640 else {
68641 addOldTypeMetadata(node, container, decoratorExpressions);
68642 }
68643 }
68644 function addOldTypeMetadata(node, container, decoratorExpressions) {
68645 if (compilerOptions.emitDecoratorMetadata) {
68646 if (shouldAddTypeMetadata(node)) {
68647 decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
68648 }
68649 if (shouldAddParamTypesMetadata(node)) {
68650 decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container)));
68651 }
68652 if (shouldAddReturnTypeMetadata(node)) {
68653 decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
68654 }
68655 }
68656 }
68657 function addNewTypeMetadata(node, container, decoratorExpressions) {
68658 if (compilerOptions.emitDecoratorMetadata) {
68659 var properties = void 0;
68660 if (shouldAddTypeMetadata(node)) {
68661 (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
68662 }
68663 if (shouldAddParamTypesMetadata(node)) {
68664 (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
68665 }
68666 if (shouldAddReturnTypeMetadata(node)) {
68667 (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(37 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
68668 }
68669 if (properties) {
68670 decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true)));
68671 }
68672 }
68673 }
68674 /**
68675 * Determines whether to emit the "design:type" metadata based on the node's kind.
68676 * The caller should have already tested whether the node has decorators and whether the
68677 * emitDecoratorMetadata compiler option is set.
68678 *
68679 * @param node The node to test.
68680 */
68681 function shouldAddTypeMetadata(node) {
68682 var kind = node.kind;
68683 return kind === 156 /* MethodDeclaration */
68684 || kind === 158 /* GetAccessor */
68685 || kind === 159 /* SetAccessor */
68686 || kind === 154 /* PropertyDeclaration */;
68687 }
68688 /**
68689 * Determines whether to emit the "design:returntype" metadata based on the node's kind.
68690 * The caller should have already tested whether the node has decorators and whether the
68691 * emitDecoratorMetadata compiler option is set.
68692 *
68693 * @param node The node to test.
68694 */
68695 function shouldAddReturnTypeMetadata(node) {
68696 return node.kind === 156 /* MethodDeclaration */;
68697 }
68698 /**
68699 * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
68700 * The caller should have already tested whether the node has decorators and whether the
68701 * emitDecoratorMetadata compiler option is set.
68702 *
68703 * @param node The node to test.
68704 */
68705 function shouldAddParamTypesMetadata(node) {
68706 switch (node.kind) {
68707 case 240 /* ClassDeclaration */:
68708 case 209 /* ClassExpression */:
68709 return ts.getFirstConstructorWithBody(node) !== undefined;
68710 case 156 /* MethodDeclaration */:
68711 case 158 /* GetAccessor */:
68712 case 159 /* SetAccessor */:
68713 return true;
68714 }
68715 return false;
68716 }
68717 function getAccessorTypeNode(node) {
68718 var accessors = resolver.getAllAccessorDeclarations(node);
68719 return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
68720 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
68721 }
68722 /**
68723 * Serializes the type of a node for use with decorator type metadata.
68724 *
68725 * @param node The node that should have its type serialized.
68726 */
68727 function serializeTypeOfNode(node) {
68728 switch (node.kind) {
68729 case 154 /* PropertyDeclaration */:
68730 case 151 /* Parameter */:
68731 return serializeTypeNode(node.type);
68732 case 159 /* SetAccessor */:
68733 case 158 /* GetAccessor */:
68734 return serializeTypeNode(getAccessorTypeNode(node));
68735 case 240 /* ClassDeclaration */:
68736 case 209 /* ClassExpression */:
68737 case 156 /* MethodDeclaration */:
68738 return ts.createIdentifier("Function");
68739 default:
68740 return ts.createVoidZero();
68741 }
68742 }
68743 /**
68744 * Serializes the types of the parameters of a node for use with decorator type metadata.
68745 *
68746 * @param node The node that should have its parameter types serialized.
68747 */
68748 function serializeParameterTypesOfNode(node, container) {
68749 var valueDeclaration = ts.isClassLike(node)
68750 ? ts.getFirstConstructorWithBody(node)
68751 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
68752 ? node
68753 : undefined;
68754 var expressions = [];
68755 if (valueDeclaration) {
68756 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
68757 var numParameters = parameters.length;
68758 for (var i = 0; i < numParameters; i++) {
68759 var parameter = parameters[i];
68760 if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
68761 continue;
68762 }
68763 if (parameter.dotDotDotToken) {
68764 expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
68765 }
68766 else {
68767 expressions.push(serializeTypeOfNode(parameter));
68768 }
68769 }
68770 }
68771 return ts.createArrayLiteral(expressions);
68772 }
68773 function getParametersOfDecoratedDeclaration(node, container) {
68774 if (container && node.kind === 158 /* GetAccessor */) {
68775 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
68776 if (setAccessor) {
68777 return setAccessor.parameters;
68778 }
68779 }
68780 return node.parameters;
68781 }
68782 /**
68783 * Serializes the return type of a node for use with decorator type metadata.
68784 *
68785 * @param node The node that should have its return type serialized.
68786 */
68787 function serializeReturnTypeOfNode(node) {
68788 if (ts.isFunctionLike(node) && node.type) {
68789 return serializeTypeNode(node.type);
68790 }
68791 else if (ts.isAsyncFunction(node)) {
68792 return ts.createIdentifier("Promise");
68793 }
68794 return ts.createVoidZero();
68795 }
68796 /**
68797 * Serializes a type node for use with decorator type metadata.
68798 *
68799 * Types are serialized in the following fashion:
68800 * - Void types point to "undefined" (e.g. "void 0")
68801 * - Function and Constructor types point to the global "Function" constructor.
68802 * - Interface types with a call or construct signature types point to the global
68803 * "Function" constructor.
68804 * - Array and Tuple types point to the global "Array" constructor.
68805 * - Type predicates and booleans point to the global "Boolean" constructor.
68806 * - String literal types and strings point to the global "String" constructor.
68807 * - Enum and number types point to the global "Number" constructor.
68808 * - Symbol types point to the global "Symbol" constructor.
68809 * - Type references to classes (or class-like variables) point to the constructor for the class.
68810 * - Anything else points to the global "Object" constructor.
68811 *
68812 * @param node The type node to serialize.
68813 */
68814 function serializeTypeNode(node) {
68815 if (node === undefined) {
68816 return ts.createIdentifier("Object");
68817 }
68818 switch (node.kind) {
68819 case 106 /* VoidKeyword */:
68820 case 141 /* UndefinedKeyword */:
68821 case 96 /* NullKeyword */:
68822 case 132 /* NeverKeyword */:
68823 return ts.createVoidZero();
68824 case 177 /* ParenthesizedType */:
68825 return serializeTypeNode(node.type);
68826 case 165 /* FunctionType */:
68827 case 166 /* ConstructorType */:
68828 return ts.createIdentifier("Function");
68829 case 169 /* ArrayType */:
68830 case 170 /* TupleType */:
68831 return ts.createIdentifier("Array");
68832 case 163 /* TypePredicate */:
68833 case 123 /* BooleanKeyword */:
68834 return ts.createIdentifier("Boolean");
68835 case 138 /* StringKeyword */:
68836 return ts.createIdentifier("String");
68837 case 136 /* ObjectKeyword */:
68838 return ts.createIdentifier("Object");
68839 case 182 /* LiteralType */:
68840 switch (node.literal.kind) {
68841 case 10 /* StringLiteral */:
68842 return ts.createIdentifier("String");
68843 case 202 /* PrefixUnaryExpression */:
68844 case 8 /* NumericLiteral */:
68845 return ts.createIdentifier("Number");
68846 case 9 /* BigIntLiteral */:
68847 return getGlobalBigIntNameWithFallback();
68848 case 102 /* TrueKeyword */:
68849 case 87 /* FalseKeyword */:
68850 return ts.createIdentifier("Boolean");
68851 default:
68852 return ts.Debug.failBadSyntaxKind(node.literal);
68853 }
68854 case 135 /* NumberKeyword */:
68855 return ts.createIdentifier("Number");
68856 case 146 /* BigIntKeyword */:
68857 return getGlobalBigIntNameWithFallback();
68858 case 139 /* SymbolKeyword */:
68859 return languageVersion < 2 /* ES2015 */
68860 ? getGlobalSymbolNameWithFallback()
68861 : ts.createIdentifier("Symbol");
68862 case 164 /* TypeReference */:
68863 return serializeTypeReferenceNode(node);
68864 case 174 /* IntersectionType */:
68865 case 173 /* UnionType */:
68866 return serializeTypeList(node.types);
68867 case 175 /* ConditionalType */:
68868 return serializeTypeList([node.trueType, node.falseType]);
68869 case 179 /* TypeOperator */:
68870 if (node.operator === 133 /* ReadonlyKeyword */) {
68871 return serializeTypeNode(node.type);
68872 }
68873 break;
68874 case 167 /* TypeQuery */:
68875 case 180 /* IndexedAccessType */:
68876 case 181 /* MappedType */:
68877 case 168 /* TypeLiteral */:
68878 case 120 /* AnyKeyword */:
68879 case 143 /* UnknownKeyword */:
68880 case 178 /* ThisType */:
68881 case 183 /* ImportType */:
68882 break;
68883 default:
68884 return ts.Debug.failBadSyntaxKind(node);
68885 }
68886 return ts.createIdentifier("Object");
68887 }
68888 function serializeTypeList(types) {
68889 // Note when updating logic here also update getEntityNameForDecoratorMetadata
68890 // so that aliases can be marked as referenced
68891 var serializedUnion;
68892 for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
68893 var typeNode = types_18[_i];
68894 while (typeNode.kind === 177 /* ParenthesizedType */) {
68895 typeNode = typeNode.type; // Skip parens if need be
68896 }
68897 if (typeNode.kind === 132 /* NeverKeyword */) {
68898 continue; // Always elide `never` from the union/intersection if possible
68899 }
68900 if (!strictNullChecks && (typeNode.kind === 96 /* NullKeyword */ || typeNode.kind === 141 /* UndefinedKeyword */)) {
68901 continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
68902 }
68903 var serializedIndividual = serializeTypeNode(typeNode);
68904 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
68905 // One of the individual is global object, return immediately
68906 return serializedIndividual;
68907 }
68908 // If there exists union that is not void 0 expression, check if the the common type is identifier.
68909 // anything more complex and we will just default to Object
68910 else if (serializedUnion) {
68911 // Different types
68912 if (!ts.isIdentifier(serializedUnion) ||
68913 !ts.isIdentifier(serializedIndividual) ||
68914 serializedUnion.escapedText !== serializedIndividual.escapedText) {
68915 return ts.createIdentifier("Object");
68916 }
68917 }
68918 else {
68919 // Initialize the union type
68920 serializedUnion = serializedIndividual;
68921 }
68922 }
68923 // If we were able to find common type, use it
68924 return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
68925 }
68926 /**
68927 * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
68928 * decorator type metadata.
68929 *
68930 * @param node The type reference node.
68931 */
68932 function serializeTypeReferenceNode(node) {
68933 var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
68934 switch (kind) {
68935 case ts.TypeReferenceSerializationKind.Unknown:
68936 // From conditional type type reference that cannot be resolved is Similar to any or unknown
68937 if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
68938 return ts.createIdentifier("Object");
68939 }
68940 var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
68941 var temp = ts.createTempVariable(hoistVariableDeclaration);
68942 return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object"));
68943 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
68944 return serializeEntityNameAsExpression(node.typeName);
68945 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
68946 return ts.createVoidZero();
68947 case ts.TypeReferenceSerializationKind.BigIntLikeType:
68948 return getGlobalBigIntNameWithFallback();
68949 case ts.TypeReferenceSerializationKind.BooleanType:
68950 return ts.createIdentifier("Boolean");
68951 case ts.TypeReferenceSerializationKind.NumberLikeType:
68952 return ts.createIdentifier("Number");
68953 case ts.TypeReferenceSerializationKind.StringLikeType:
68954 return ts.createIdentifier("String");
68955 case ts.TypeReferenceSerializationKind.ArrayLikeType:
68956 return ts.createIdentifier("Array");
68957 case ts.TypeReferenceSerializationKind.ESSymbolType:
68958 return languageVersion < 2 /* ES2015 */
68959 ? getGlobalSymbolNameWithFallback()
68960 : ts.createIdentifier("Symbol");
68961 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
68962 return ts.createIdentifier("Function");
68963 case ts.TypeReferenceSerializationKind.Promise:
68964 return ts.createIdentifier("Promise");
68965 case ts.TypeReferenceSerializationKind.ObjectType:
68966 return ts.createIdentifier("Object");
68967 default:
68968 return ts.Debug.assertNever(kind);
68969 }
68970 }
68971 function createCheckedValue(left, right) {
68972 return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right);
68973 }
68974 /**
68975 * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
68976 *
68977 * @param node The entity name to serialize.
68978 */
68979 function serializeEntityNameAsExpressionFallback(node) {
68980 if (node.kind === 72 /* Identifier */) {
68981 // A -> typeof A !== undefined && A
68982 var copied = serializeEntityNameAsExpression(node);
68983 return createCheckedValue(copied, copied);
68984 }
68985 if (node.left.kind === 72 /* Identifier */) {
68986 // A.B -> typeof A !== undefined && A.B
68987 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
68988 }
68989 // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
68990 var left = serializeEntityNameAsExpressionFallback(node.left);
68991 var temp = ts.createTempVariable(hoistVariableDeclaration);
68992 return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right));
68993 }
68994 /**
68995 * Serializes an entity name as an expression for decorator type metadata.
68996 *
68997 * @param node The entity name to serialize.
68998 */
68999 function serializeEntityNameAsExpression(node) {
69000 switch (node.kind) {
69001 case 72 /* Identifier */:
69002 // Create a clone of the name with a new parent, and treat it as if it were
69003 // a source tree node for the purposes of the checker.
69004 var name = ts.getMutableClone(node);
69005 name.flags &= ~8 /* Synthesized */;
69006 name.original = undefined;
69007 name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node.
69008 return name;
69009 case 148 /* QualifiedName */:
69010 return serializeQualifiedNameAsExpression(node);
69011 }
69012 }
69013 /**
69014 * Serializes an qualified name as an expression for decorator type metadata.
69015 *
69016 * @param node The qualified name to serialize.
69017 * @param useFallback A value indicating whether to use logical operators to test for the
69018 * qualified name at runtime.
69019 */
69020 function serializeQualifiedNameAsExpression(node) {
69021 return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right);
69022 }
69023 /**
69024 * Gets an expression that points to the global "Symbol" constructor at runtime if it is
69025 * available.
69026 */
69027 function getGlobalSymbolNameWithFallback() {
69028 return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object"));
69029 }
69030 /**
69031 * Gets an expression that points to the global "BigInt" constructor at runtime if it is
69032 * available.
69033 */
69034 function getGlobalBigIntNameWithFallback() {
69035 return languageVersion < 7 /* ESNext */
69036 ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
69037 : ts.createIdentifier("BigInt");
69038 }
69039 /**
69040 * A simple inlinable expression is an expression which can be copied into multiple locations
69041 * without risk of repeating any sideeffects and whose value could not possibly change between
69042 * any such locations
69043 */
69044 function isSimpleInlineableExpression(expression) {
69045 return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) ||
69046 ts.isWellKnownSymbolSyntactically(expression);
69047 }
69048 /**
69049 * Gets an expression that represents a property name. For a computed property, a
69050 * name is generated for the node.
69051 *
69052 * @param member The member whose name should be converted into an expression.
69053 */
69054 function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
69055 var name = member.name;
69056 if (ts.isComputedPropertyName(name)) {
69057 return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression)
69058 ? ts.getGeneratedNameForNode(name)
69059 : name.expression;
69060 }
69061 else if (ts.isIdentifier(name)) {
69062 return ts.createLiteral(ts.idText(name));
69063 }
69064 else {
69065 return ts.getSynthesizedClone(name);
69066 }
69067 }
69068 /**
69069 * If the name is a computed property, this function transforms it, then either returns an expression which caches the
69070 * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
69071 * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
69072 * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal)
69073 */
69074 function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) {
69075 if (ts.isComputedPropertyName(name)) {
69076 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
69077 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
69078 var inlinable = isSimpleInlineableExpression(innerExpression);
69079 if (!inlinable && shouldHoist) {
69080 var generatedName = ts.getGeneratedNameForNode(name);
69081 hoistVariableDeclaration(generatedName);
69082 return ts.createAssignment(generatedName, expression);
69083 }
69084 return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression;
69085 }
69086 }
69087 /**
69088 * Visits the property name of a class element, for use when emitting property
69089 * initializers. For a computed property on a node with decorators, a temporary
69090 * value is stored for later use.
69091 *
69092 * @param member The member whose name should be visited.
69093 */
69094 function visitPropertyNameOfClassElement(member) {
69095 var name = member.name;
69096 var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false);
69097 if (expr) { // expr only exists if `name` is a computed property name
69098 // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order
69099 if (ts.some(pendingExpressions)) {
69100 expr = ts.inlineExpressions(pendingExpressions.concat([expr]));
69101 pendingExpressions.length = 0;
69102 }
69103 return ts.updateComputedPropertyName(name, expr);
69104 }
69105 else {
69106 return name;
69107 }
69108 }
69109 /**
69110 * Transforms a HeritageClause with TypeScript syntax.
69111 *
69112 * This function will only be called when one of the following conditions are met:
69113 * - The node is a non-`extends` heritage clause that should be elided.
69114 * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
69115 *
69116 * @param node The HeritageClause to transform.
69117 */
69118 function visitHeritageClause(node) {
69119 if (node.token === 109 /* ImplementsKeyword */) {
69120 // implements clauses are elided
69121 return undefined;
69122 }
69123 return ts.visitEachChild(node, visitor, context);
69124 }
69125 /**
69126 * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
69127 *
69128 * This function will only be called when one of the following conditions are met:
69129 * - The node contains type arguments that should be elided.
69130 *
69131 * @param node The ExpressionWithTypeArguments to transform.
69132 */
69133 function visitExpressionWithTypeArguments(node) {
69134 return ts.updateExpressionWithTypeArguments(node,
69135 /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
69136 }
69137 /**
69138 * Determines whether to emit a function-like declaration. We should not emit the
69139 * declaration if it does not have a body.
69140 *
69141 * @param node The declaration node.
69142 */
69143 function shouldEmitFunctionLikeDeclaration(node) {
69144 return !ts.nodeIsMissing(node.body);
69145 }
69146 function visitPropertyDeclaration(node) {
69147 var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, /*omitSimple*/ true);
69148 if (expr && !isSimpleInlineableExpression(expr)) {
69149 (pendingExpressions || (pendingExpressions = [])).push(expr);
69150 }
69151 return undefined;
69152 }
69153 function visitConstructor(node) {
69154 if (!shouldEmitFunctionLikeDeclaration(node)) {
69155 return undefined;
69156 }
69157 return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context));
69158 }
69159 function visitMethodDeclaration(node) {
69160 if (!shouldEmitFunctionLikeDeclaration(node)) {
69161 return undefined;
69162 }
69163 var updated = ts.updateMethod(node,
69164 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node),
69165 /*questionToken*/ undefined,
69166 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
69167 /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
69168 if (updated !== node) {
69169 // While we emit the source map for the node after skipping decorators and modifiers,
69170 // we need to emit the comments for the original range.
69171 ts.setCommentRange(updated, node);
69172 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
69173 }
69174 return updated;
69175 }
69176 /**
69177 * Determines whether to emit an accessor declaration. We should not emit the
69178 * declaration if it does not have a body and is abstract.
69179 *
69180 * @param node The declaration node.
69181 */
69182 function shouldEmitAccessorDeclaration(node) {
69183 return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
69184 }
69185 function visitGetAccessor(node) {
69186 if (!shouldEmitAccessorDeclaration(node)) {
69187 return undefined;
69188 }
69189 var updated = ts.updateGetAccessor(node,
69190 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context),
69191 /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
69192 if (updated !== node) {
69193 // While we emit the source map for the node after skipping decorators and modifiers,
69194 // we need to emit the comments for the original range.
69195 ts.setCommentRange(updated, node);
69196 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
69197 }
69198 return updated;
69199 }
69200 function visitSetAccessor(node) {
69201 if (!shouldEmitAccessorDeclaration(node)) {
69202 return undefined;
69203 }
69204 var updated = ts.updateSetAccessor(node,
69205 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
69206 if (updated !== node) {
69207 // While we emit the source map for the node after skipping decorators and modifiers,
69208 // we need to emit the comments for the original range.
69209 ts.setCommentRange(updated, node);
69210 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
69211 }
69212 return updated;
69213 }
69214 function visitFunctionDeclaration(node) {
69215 if (!shouldEmitFunctionLikeDeclaration(node)) {
69216 return ts.createNotEmittedStatement(node);
69217 }
69218 var updated = ts.updateFunctionDeclaration(node,
69219 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name,
69220 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
69221 /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
69222 if (isExportOfNamespace(node)) {
69223 var statements = [updated];
69224 addExportMemberAssignment(statements, node);
69225 return statements;
69226 }
69227 return updated;
69228 }
69229 function visitFunctionExpression(node) {
69230 if (!shouldEmitFunctionLikeDeclaration(node)) {
69231 return ts.createOmittedExpression();
69232 }
69233 var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name,
69234 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
69235 /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
69236 return updated;
69237 }
69238 function visitArrowFunction(node) {
69239 var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier),
69240 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
69241 /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
69242 return updated;
69243 }
69244 function visitParameter(node) {
69245 if (ts.parameterIsThisKeyword(node)) {
69246 return undefined;
69247 }
69248 var updated = ts.updateParameter(node,
69249 /*decorators*/ undefined,
69250 /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName),
69251 /*questionToken*/ undefined,
69252 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
69253 if (updated !== node) {
69254 // While we emit the source map for the node after skipping decorators and modifiers,
69255 // we need to emit the comments for the original range.
69256 ts.setCommentRange(updated, node);
69257 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
69258 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
69259 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
69260 }
69261 return updated;
69262 }
69263 function visitVariableStatement(node) {
69264 if (isExportOfNamespace(node)) {
69265 var variables = ts.getInitializedVariables(node.declarationList);
69266 if (variables.length === 0) {
69267 // elide statement if there are no initialized variables.
69268 return undefined;
69269 }
69270 return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
69271 }
69272 else {
69273 return ts.visitEachChild(node, visitor, context);
69274 }
69275 }
69276 function transformInitializedVariable(node) {
69277 var name = node.name;
69278 if (ts.isBindingPattern(name)) {
69279 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */,
69280 /*needsValue*/ false, createNamespaceExportExpression);
69281 }
69282 else {
69283 return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)),
69284 /*location*/ node);
69285 }
69286 }
69287 function visitVariableDeclaration(node) {
69288 return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName),
69289 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
69290 }
69291 function visitParenthesizedExpression(node) {
69292 var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */);
69293 if (ts.isAssertionExpression(innerExpression)) {
69294 // Make sure we consider all nested cast expressions, e.g.:
69295 // (<any><number><any>-A).x;
69296 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
69297 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
69298 // is really not desirable. We would like to emit the subexpression as-is. Omitting
69299 // the parentheses, however, could cause change in the semantics of the generated
69300 // code if the casted expression has a lower precedence than the rest of the
69301 // expression.
69302 //
69303 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
69304 // preserve the position information of the original expression.
69305 //
69306 // Due to the auto-parenthesization rules used by the visitor and factory functions
69307 // we can safely elide the parentheses here, as a new synthetic
69308 // ParenthesizedExpression will be inserted if we remove parentheses too
69309 // aggressively.
69310 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
69311 // correctly for return and throw, we must keep the parenthesis
69312 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
69313 return ts.updateParen(node, expression);
69314 }
69315 return ts.createPartiallyEmittedExpression(expression, node);
69316 }
69317 return ts.visitEachChild(node, visitor, context);
69318 }
69319 function visitAssertionExpression(node) {
69320 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
69321 return ts.createPartiallyEmittedExpression(expression, node);
69322 }
69323 function visitNonNullExpression(node) {
69324 var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
69325 return ts.createPartiallyEmittedExpression(expression, node);
69326 }
69327 function visitCallExpression(node) {
69328 return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression),
69329 /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
69330 }
69331 function visitNewExpression(node) {
69332 return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression),
69333 /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
69334 }
69335 function visitTaggedTemplateExpression(node) {
69336 return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression),
69337 /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
69338 }
69339 /**
69340 * Determines whether to emit an enum declaration.
69341 *
69342 * @param node The enum declaration node.
69343 */
69344 function shouldEmitEnumDeclaration(node) {
69345 return !ts.isEnumConst(node)
69346 || compilerOptions.preserveConstEnums
69347 || compilerOptions.isolatedModules;
69348 }
69349 /**
69350 * Visits an enum declaration.
69351 *
69352 * This function will be called any time a TypeScript enum is encountered.
69353 *
69354 * @param node The enum declaration node.
69355 */
69356 function visitEnumDeclaration(node) {
69357 if (!shouldEmitEnumDeclaration(node)) {
69358 return undefined;
69359 }
69360 var statements = [];
69361 // We request to be advised when the printer is about to print this node. This allows
69362 // us to set up the correct state for later substitutions.
69363 var emitFlags = 2 /* AdviseOnEmitNode */;
69364 // If needed, we should emit a variable declaration for the enum. If we emit
69365 // a leading variable declaration, we should not emit leading comments for the
69366 // enum body.
69367 var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
69368 if (varAdded) {
69369 // We should still emit the comments if we are emitting a system module.
69370 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
69371 emitFlags |= 512 /* NoLeadingComments */;
69372 }
69373 }
69374 // `parameterName` is the declaration name used inside of the enum.
69375 var parameterName = getNamespaceParameterName(node);
69376 // `containerName` is the expression used inside of the enum for assignments.
69377 var containerName = getNamespaceContainerName(node);
69378 // `exportName` is the expression used within this node's container for any exported references.
69379 var exportName = ts.hasModifier(node, 1 /* Export */)
69380 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
69381 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
69382 // x || (x = {})
69383 // exports.x || (exports.x = {})
69384 var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
69385 if (hasNamespaceQualifiedExportName(node)) {
69386 // `localName` is the expression used within this node's containing scope for any local references.
69387 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
69388 // x = (exports.x || (exports.x = {}))
69389 moduleArg = ts.createAssignment(localName, moduleArg);
69390 }
69391 // (function (x) {
69392 // x[x["y"] = 0] = "y";
69393 // ...
69394 // })(x || (x = {}));
69395 var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
69396 /*modifiers*/ undefined,
69397 /*asteriskToken*/ undefined,
69398 /*name*/ undefined,
69399 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
69400 /*type*/ undefined, transformEnumBody(node, containerName)),
69401 /*typeArguments*/ undefined, [moduleArg]));
69402 ts.setOriginalNode(enumStatement, node);
69403 if (varAdded) {
69404 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
69405 ts.setSyntheticLeadingComments(enumStatement, undefined);
69406 ts.setSyntheticTrailingComments(enumStatement, undefined);
69407 }
69408 ts.setTextRange(enumStatement, node);
69409 ts.addEmitFlags(enumStatement, emitFlags);
69410 statements.push(enumStatement);
69411 // Add a DeclarationMarker for the enum to preserve trailing comments and mark
69412 // the end of the declaration.
69413 statements.push(ts.createEndOfDeclarationMarker(node));
69414 return statements;
69415 }
69416 /**
69417 * Transforms the body of an enum declaration.
69418 *
69419 * @param node The enum declaration node.
69420 */
69421 function transformEnumBody(node, localName) {
69422 var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
69423 currentNamespaceContainerName = localName;
69424 var statements = [];
69425 startLexicalEnvironment();
69426 var members = ts.map(node.members, transformEnumMember);
69427 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
69428 ts.addRange(statements, members);
69429 currentNamespaceContainerName = savedCurrentNamespaceLocalName;
69430 return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
69431 /*multiLine*/ true);
69432 }
69433 /**
69434 * Transforms an enum member into a statement.
69435 *
69436 * @param member The enum member node.
69437 */
69438 function transformEnumMember(member) {
69439 // enums don't support computed properties
69440 // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
69441 // old emitter always generate 'expression' part of the name as-is.
69442 var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
69443 var valueExpression = transformEnumMemberDeclarationValue(member);
69444 var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression);
69445 var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
69446 innerAssignment :
69447 ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name);
69448 return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
69449 }
69450 /**
69451 * Transforms the value of an enum member.
69452 *
69453 * @param member The enum member node.
69454 */
69455 function transformEnumMemberDeclarationValue(member) {
69456 var value = resolver.getConstantValue(member);
69457 if (value !== undefined) {
69458 return ts.createLiteral(value);
69459 }
69460 else {
69461 enableSubstitutionForNonQualifiedEnumMembers();
69462 if (member.initializer) {
69463 return ts.visitNode(member.initializer, visitor, ts.isExpression);
69464 }
69465 else {
69466 return ts.createVoidZero();
69467 }
69468 }
69469 }
69470 /**
69471 * Determines whether to elide a module declaration.
69472 *
69473 * @param node The module declaration node.
69474 */
69475 function shouldEmitModuleDeclaration(node) {
69476 return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
69477 }
69478 /**
69479 * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
69480 * or `exports.x`).
69481 */
69482 function hasNamespaceQualifiedExportName(node) {
69483 return isExportOfNamespace(node)
69484 || (isExternalModuleExport(node)
69485 && moduleKind !== ts.ModuleKind.ES2015
69486 && moduleKind !== ts.ModuleKind.ESNext
69487 && moduleKind !== ts.ModuleKind.System);
69488 }
69489 /**
69490 * Records that a declaration was emitted in the current scope, if it was the first
69491 * declaration for the provided symbol.
69492 */
69493 function recordEmittedDeclarationInScope(node) {
69494 if (!currentScopeFirstDeclarationsOfName) {
69495 currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap();
69496 }
69497 var name = declaredNameInScope(node);
69498 if (!currentScopeFirstDeclarationsOfName.has(name)) {
69499 currentScopeFirstDeclarationsOfName.set(name, node);
69500 }
69501 }
69502 /**
69503 * Determines whether a declaration is the first declaration with
69504 * the same name emitted in the current scope.
69505 */
69506 function isFirstEmittedDeclarationInScope(node) {
69507 if (currentScopeFirstDeclarationsOfName) {
69508 var name = declaredNameInScope(node);
69509 return currentScopeFirstDeclarationsOfName.get(name) === node;
69510 }
69511 return true;
69512 }
69513 function declaredNameInScope(node) {
69514 ts.Debug.assertNode(node.name, ts.isIdentifier);
69515 return node.name.escapedText;
69516 }
69517 /**
69518 * Adds a leading VariableStatement for a enum or module declaration.
69519 */
69520 function addVarForEnumOrModuleDeclaration(statements, node) {
69521 // Emit a variable statement for the module. We emit top-level enums as a `var`
69522 // declaration to avoid static errors in global scripts scripts due to redeclaration.
69523 // enums in any other scope are emitted as a `let` declaration.
69524 var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
69525 ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
69526 ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
69527 ts.setOriginalNode(statement, node);
69528 recordEmittedDeclarationInScope(node);
69529 if (isFirstEmittedDeclarationInScope(node)) {
69530 // Adjust the source map emit to match the old emitter.
69531 if (node.kind === 243 /* EnumDeclaration */) {
69532 ts.setSourceMapRange(statement.declarationList, node);
69533 }
69534 else {
69535 ts.setSourceMapRange(statement, node);
69536 }
69537 // Trailing comments for module declaration should be emitted after the function closure
69538 // instead of the variable statement:
69539 //
69540 // /** Module comment*/
69541 // module m1 {
69542 // function foo4Export() {
69543 // }
69544 // } // trailing comment module
69545 //
69546 // Should emit:
69547 //
69548 // /** Module comment*/
69549 // var m1;
69550 // (function (m1) {
69551 // function foo4Export() {
69552 // }
69553 // })(m1 || (m1 = {})); // trailing comment module
69554 //
69555 ts.setCommentRange(statement, node);
69556 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
69557 statements.push(statement);
69558 return true;
69559 }
69560 else {
69561 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
69562 // declaration we do not emit a leading variable declaration. To preserve the
69563 // begin/end semantics of the declararation and to properly handle exports
69564 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
69565 var mergeMarker = ts.createMergeDeclarationMarker(statement);
69566 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
69567 statements.push(mergeMarker);
69568 return false;
69569 }
69570 }
69571 /**
69572 * Visits a module declaration node.
69573 *
69574 * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
69575 *
69576 * @param node The module declaration node.
69577 */
69578 function visitModuleDeclaration(node) {
69579 if (!shouldEmitModuleDeclaration(node)) {
69580 return ts.createNotEmittedStatement(node);
69581 }
69582 ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
69583 enableSubstitutionForNamespaceExports();
69584 var statements = [];
69585 // We request to be advised when the printer is about to print this node. This allows
69586 // us to set up the correct state for later substitutions.
69587 var emitFlags = 2 /* AdviseOnEmitNode */;
69588 // If needed, we should emit a variable declaration for the module. If we emit
69589 // a leading variable declaration, we should not emit leading comments for the
69590 // module body.
69591 var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
69592 if (varAdded) {
69593 // We should still emit the comments if we are emitting a system module.
69594 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
69595 emitFlags |= 512 /* NoLeadingComments */;
69596 }
69597 }
69598 // `parameterName` is the declaration name used inside of the namespace.
69599 var parameterName = getNamespaceParameterName(node);
69600 // `containerName` is the expression used inside of the namespace for exports.
69601 var containerName = getNamespaceContainerName(node);
69602 // `exportName` is the expression used within this node's container for any exported references.
69603 var exportName = ts.hasModifier(node, 1 /* Export */)
69604 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
69605 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
69606 // x || (x = {})
69607 // exports.x || (exports.x = {})
69608 var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
69609 if (hasNamespaceQualifiedExportName(node)) {
69610 // `localName` is the expression used within this node's containing scope for any local references.
69611 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
69612 // x = (exports.x || (exports.x = {}))
69613 moduleArg = ts.createAssignment(localName, moduleArg);
69614 }
69615 // (function (x_1) {
69616 // x_1.y = ...;
69617 // })(x || (x = {}));
69618 var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
69619 /*modifiers*/ undefined,
69620 /*asteriskToken*/ undefined,
69621 /*name*/ undefined,
69622 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
69623 /*type*/ undefined, transformModuleBody(node, containerName)),
69624 /*typeArguments*/ undefined, [moduleArg]));
69625 ts.setOriginalNode(moduleStatement, node);
69626 if (varAdded) {
69627 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
69628 ts.setSyntheticLeadingComments(moduleStatement, undefined);
69629 ts.setSyntheticTrailingComments(moduleStatement, undefined);
69630 }
69631 ts.setTextRange(moduleStatement, node);
69632 ts.addEmitFlags(moduleStatement, emitFlags);
69633 statements.push(moduleStatement);
69634 // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
69635 // the end of the declaration.
69636 statements.push(ts.createEndOfDeclarationMarker(node));
69637 return statements;
69638 }
69639 /**
69640 * Transforms the body of a module declaration.
69641 *
69642 * @param node The module declaration node.
69643 */
69644 function transformModuleBody(node, namespaceLocalName) {
69645 var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
69646 var savedCurrentNamespace = currentNamespace;
69647 var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
69648 currentNamespaceContainerName = namespaceLocalName;
69649 currentNamespace = node;
69650 currentScopeFirstDeclarationsOfName = undefined;
69651 var statements = [];
69652 startLexicalEnvironment();
69653 var statementsLocation;
69654 var blockLocation;
69655 var body = node.body;
69656 if (body.kind === 245 /* ModuleBlock */) {
69657 saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
69658 statementsLocation = body.statements;
69659 blockLocation = body;
69660 }
69661 else {
69662 var result = visitModuleDeclaration(body);
69663 if (result) {
69664 if (ts.isArray(result)) {
69665 ts.addRange(statements, result);
69666 }
69667 else {
69668 statements.push(result);
69669 }
69670 }
69671 var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
69672 statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
69673 }
69674 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
69675 currentNamespaceContainerName = savedCurrentNamespaceContainerName;
69676 currentNamespace = savedCurrentNamespace;
69677 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
69678 var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
69679 /*location*/ statementsLocation),
69680 /*multiLine*/ true);
69681 ts.setTextRange(block, blockLocation);
69682 // namespace hello.hi.world {
69683 // function foo() {}
69684 //
69685 // // TODO, blah
69686 // }
69687 //
69688 // should be emitted as
69689 //
69690 // var hello;
69691 // (function (hello) {
69692 // var hi;
69693 // (function (hi) {
69694 // var world;
69695 // (function (world) {
69696 // function foo() { }
69697 // // TODO, blah
69698 // })(world = hi.world || (hi.world = {}));
69699 // })(hi = hello.hi || (hello.hi = {}));
69700 // })(hello || (hello = {}));
69701 // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
69702 if (body.kind !== 245 /* ModuleBlock */) {
69703 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
69704 }
69705 return block;
69706 }
69707 function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
69708 if (moduleDeclaration.body.kind === 244 /* ModuleDeclaration */) {
69709 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
69710 return recursiveInnerModule || moduleDeclaration.body;
69711 }
69712 }
69713 /**
69714 * Visits an import declaration, eliding it if it is not referenced.
69715 *
69716 * @param node The import declaration node.
69717 */
69718 function visitImportDeclaration(node) {
69719 if (!node.importClause) {
69720 // Do not elide a side-effect only import declaration.
69721 // import "foo";
69722 return node;
69723 }
69724 // Elide the declaration if the import clause was elided.
69725 var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
69726 return importClause
69727 ? ts.updateImportDeclaration(node,
69728 /*decorators*/ undefined,
69729 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
69730 : undefined;
69731 }
69732 /**
69733 * Visits an import clause, eliding it if it is not referenced.
69734 *
69735 * @param node The import clause node.
69736 */
69737 function visitImportClause(node) {
69738 // Elide the import clause if we elide both its name and its named bindings.
69739 var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
69740 var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
69741 return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined;
69742 }
69743 /**
69744 * Visits named import bindings, eliding it if it is not referenced.
69745 *
69746 * @param node The named import bindings node.
69747 */
69748 function visitNamedImportBindings(node) {
69749 if (node.kind === 251 /* NamespaceImport */) {
69750 // Elide a namespace import if it is not referenced.
69751 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
69752 }
69753 else {
69754 // Elide named imports if all of its import specifiers are elided.
69755 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
69756 return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined;
69757 }
69758 }
69759 /**
69760 * Visits an import specifier, eliding it if it is not referenced.
69761 *
69762 * @param node The import specifier node.
69763 */
69764 function visitImportSpecifier(node) {
69765 // Elide an import specifier if it is not referenced.
69766 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
69767 }
69768 /**
69769 * Visits an export assignment, eliding it if it does not contain a clause that resolves
69770 * to a value.
69771 *
69772 * @param node The export assignment node.
69773 */
69774 function visitExportAssignment(node) {
69775 // Elide the export assignment if it does not reference a value.
69776 return resolver.isValueAliasDeclaration(node)
69777 ? ts.visitEachChild(node, visitor, context)
69778 : undefined;
69779 }
69780 /**
69781 * Visits an export declaration, eliding it if it does not contain a clause that resolves
69782 * to a value.
69783 *
69784 * @param node The export declaration node.
69785 */
69786 function visitExportDeclaration(node) {
69787 if (!node.exportClause) {
69788 // Elide a star export if the module it references does not export a value.
69789 return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;
69790 }
69791 if (!resolver.isValueAliasDeclaration(node)) {
69792 // Elide the export declaration if it does not export a value.
69793 return undefined;
69794 }
69795 // Elide the export declaration if all of its named exports are elided.
69796 var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports);
69797 return exportClause
69798 ? ts.updateExportDeclaration(node,
69799 /*decorators*/ undefined,
69800 /*modifiers*/ undefined, exportClause, node.moduleSpecifier)
69801 : undefined;
69802 }
69803 /**
69804 * Visits named exports, eliding it if it does not contain an export specifier that
69805 * resolves to a value.
69806 *
69807 * @param node The named exports node.
69808 */
69809 function visitNamedExports(node) {
69810 // Elide the named exports if all of its export specifiers were elided.
69811 var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
69812 return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined;
69813 }
69814 /**
69815 * Visits an export specifier, eliding it if it does not resolve to a value.
69816 *
69817 * @param node The export specifier node.
69818 */
69819 function visitExportSpecifier(node) {
69820 // Elide an export specifier if it does not reference a value.
69821 return resolver.isValueAliasDeclaration(node) ? node : undefined;
69822 }
69823 /**
69824 * Determines whether to emit an import equals declaration.
69825 *
69826 * @param node The import equals declaration node.
69827 */
69828 function shouldEmitImportEqualsDeclaration(node) {
69829 // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
69830 // - current file is not external module
69831 // - import declaration is top level and target is value imported by entity name
69832 return resolver.isReferencedAliasDeclaration(node)
69833 || (!ts.isExternalModule(currentSourceFile)
69834 && resolver.isTopLevelValueImportEqualsWithEntityName(node));
69835 }
69836 /**
69837 * Visits an import equals declaration.
69838 *
69839 * @param node The import equals declaration node.
69840 */
69841 function visitImportEqualsDeclaration(node) {
69842 if (ts.isExternalModuleImportEqualsDeclaration(node)) {
69843 // Elide external module `import=` if it is not referenced.
69844 return resolver.isReferencedAliasDeclaration(node)
69845 ? ts.visitEachChild(node, visitor, context)
69846 : undefined;
69847 }
69848 if (!shouldEmitImportEqualsDeclaration(node)) {
69849 return undefined;
69850 }
69851 var moduleReference = ts.createExpressionFromEntityName(node.moduleReference);
69852 ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
69853 if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
69854 // export var ${name} = ${moduleReference};
69855 // var ${name} = ${moduleReference};
69856 return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
69857 ts.setOriginalNode(ts.createVariableDeclaration(node.name,
69858 /*type*/ undefined, moduleReference), node)
69859 ])), node), node);
69860 }
69861 else {
69862 // exports.${name} = ${moduleReference};
69863 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
69864 }
69865 }
69866 /**
69867 * Gets a value indicating whether the node is exported from a namespace.
69868 *
69869 * @param node The node to test.
69870 */
69871 function isExportOfNamespace(node) {
69872 return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */);
69873 }
69874 /**
69875 * Gets a value indicating whether the node is exported from an external module.
69876 *
69877 * @param node The node to test.
69878 */
69879 function isExternalModuleExport(node) {
69880 return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */);
69881 }
69882 /**
69883 * Gets a value indicating whether the node is a named export from an external module.
69884 *
69885 * @param node The node to test.
69886 */
69887 function isNamedExternalModuleExport(node) {
69888 return isExternalModuleExport(node)
69889 && !ts.hasModifier(node, 512 /* Default */);
69890 }
69891 /**
69892 * Gets a value indicating whether the node is the default export of an external module.
69893 *
69894 * @param node The node to test.
69895 */
69896 function isDefaultExternalModuleExport(node) {
69897 return isExternalModuleExport(node)
69898 && ts.hasModifier(node, 512 /* Default */);
69899 }
69900 /**
69901 * Creates a statement for the provided expression. This is used in calls to `map`.
69902 */
69903 function expressionToStatement(expression) {
69904 return ts.createExpressionStatement(expression);
69905 }
69906 function addExportMemberAssignment(statements, node) {
69907 var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node));
69908 ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
69909 var statement = ts.createExpressionStatement(expression);
69910 ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
69911 statements.push(statement);
69912 }
69913 function createNamespaceExport(exportName, exportValue, location) {
69914 return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
69915 }
69916 function createNamespaceExportExpression(exportName, exportValue, location) {
69917 return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
69918 }
69919 function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
69920 return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
69921 }
69922 /**
69923 * Gets the declaration name used inside of a namespace or enum.
69924 */
69925 function getNamespaceParameterName(node) {
69926 var name = ts.getGeneratedNameForNode(node);
69927 ts.setSourceMapRange(name, node.name);
69928 return name;
69929 }
69930 /**
69931 * Gets the expression used to refer to a namespace or enum within the body
69932 * of its declaration.
69933 */
69934 function getNamespaceContainerName(node) {
69935 return ts.getGeneratedNameForNode(node);
69936 }
69937 /**
69938 * Gets a local alias for a class declaration if it is a decorated class with an internal
69939 * reference to the static side of the class. This is necessary to avoid issues with
69940 * double-binding semantics for the class name.
69941 */
69942 function getClassAliasIfNeeded(node) {
69943 if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
69944 enableSubstitutionForClassAliases();
69945 var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
69946 classAliases[ts.getOriginalNodeId(node)] = classAlias;
69947 hoistVariableDeclaration(classAlias);
69948 return classAlias;
69949 }
69950 }
69951 function getClassPrototype(node) {
69952 return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype");
69953 }
69954 function getClassMemberPrefix(node, member) {
69955 return ts.hasModifier(member, 32 /* Static */)
69956 ? ts.getDeclarationName(node)
69957 : getClassPrototype(node);
69958 }
69959 function enableSubstitutionForNonQualifiedEnumMembers() {
69960 if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
69961 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
69962 context.enableSubstitution(72 /* Identifier */);
69963 }
69964 }
69965 function enableSubstitutionForClassAliases() {
69966 if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
69967 enabledSubstitutions |= 1 /* ClassAliases */;
69968 // We need to enable substitutions for identifiers. This allows us to
69969 // substitute class names inside of a class declaration.
69970 context.enableSubstitution(72 /* Identifier */);
69971 // Keep track of class aliases.
69972 classAliases = [];
69973 }
69974 }
69975 function enableSubstitutionForNamespaceExports() {
69976 if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
69977 enabledSubstitutions |= 2 /* NamespaceExports */;
69978 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
69979 // substitute the names of exported members of a namespace.
69980 context.enableSubstitution(72 /* Identifier */);
69981 context.enableSubstitution(276 /* ShorthandPropertyAssignment */);
69982 // We need to be notified when entering and exiting namespaces.
69983 context.enableEmitNotification(244 /* ModuleDeclaration */);
69984 }
69985 }
69986 function isTransformedModuleDeclaration(node) {
69987 return ts.getOriginalNode(node).kind === 244 /* ModuleDeclaration */;
69988 }
69989 function isTransformedEnumDeclaration(node) {
69990 return ts.getOriginalNode(node).kind === 243 /* EnumDeclaration */;
69991 }
69992 /**
69993 * Hook for node emit.
69994 *
69995 * @param hint A hint as to the intended usage of the node.
69996 * @param node The node to emit.
69997 * @param emit A callback used to emit the node in the printer.
69998 */
69999 function onEmitNode(hint, node, emitCallback) {
70000 var savedApplicableSubstitutions = applicableSubstitutions;
70001 var savedCurrentSourceFile = currentSourceFile;
70002 if (ts.isSourceFile(node)) {
70003 currentSourceFile = node;
70004 }
70005 if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
70006 applicableSubstitutions |= 2 /* NamespaceExports */;
70007 }
70008 if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
70009 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
70010 }
70011 previousOnEmitNode(hint, node, emitCallback);
70012 applicableSubstitutions = savedApplicableSubstitutions;
70013 currentSourceFile = savedCurrentSourceFile;
70014 }
70015 /**
70016 * Hooks node substitutions.
70017 *
70018 * @param hint A hint as to the intended usage of the node.
70019 * @param node The node to substitute.
70020 */
70021 function onSubstituteNode(hint, node) {
70022 node = previousOnSubstituteNode(hint, node);
70023 if (hint === 1 /* Expression */) {
70024 return substituteExpression(node);
70025 }
70026 else if (ts.isShorthandPropertyAssignment(node)) {
70027 return substituteShorthandPropertyAssignment(node);
70028 }
70029 return node;
70030 }
70031 function substituteShorthandPropertyAssignment(node) {
70032 if (enabledSubstitutions & 2 /* NamespaceExports */) {
70033 var name = node.name;
70034 var exportedName = trySubstituteNamespaceExportedName(name);
70035 if (exportedName) {
70036 // A shorthand property with an assignment initializer is probably part of a
70037 // destructuring assignment
70038 if (node.objectAssignmentInitializer) {
70039 var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
70040 return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
70041 }
70042 return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node);
70043 }
70044 }
70045 return node;
70046 }
70047 function substituteExpression(node) {
70048 switch (node.kind) {
70049 case 72 /* Identifier */:
70050 return substituteExpressionIdentifier(node);
70051 case 189 /* PropertyAccessExpression */:
70052 return substitutePropertyAccessExpression(node);
70053 case 190 /* ElementAccessExpression */:
70054 return substituteElementAccessExpression(node);
70055 }
70056 return node;
70057 }
70058 function substituteExpressionIdentifier(node) {
70059 return trySubstituteClassAlias(node)
70060 || trySubstituteNamespaceExportedName(node)
70061 || node;
70062 }
70063 function trySubstituteClassAlias(node) {
70064 if (enabledSubstitutions & 1 /* ClassAliases */) {
70065 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
70066 // Due to the emit for class decorators, any reference to the class from inside of the class body
70067 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
70068 // behavior of class names in ES6.
70069 // Also, when emitting statics for class expressions, we must substitute a class alias for
70070 // constructor references in static property initializers.
70071 var declaration = resolver.getReferencedValueDeclaration(node);
70072 if (declaration) {
70073 var classAlias = classAliases[declaration.id]; // TODO: GH#18217
70074 if (classAlias) {
70075 var clone_1 = ts.getSynthesizedClone(classAlias);
70076 ts.setSourceMapRange(clone_1, node);
70077 ts.setCommentRange(clone_1, node);
70078 return clone_1;
70079 }
70080 }
70081 }
70082 }
70083 return undefined;
70084 }
70085 function trySubstituteNamespaceExportedName(node) {
70086 // If this is explicitly a local name, do not substitute.
70087 if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
70088 // If we are nested within a namespace declaration, we may need to qualifiy
70089 // an identifier that is exported from a merged namespace.
70090 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
70091 if (container && container.kind !== 284 /* SourceFile */) {
70092 var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
70093 (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
70094 if (substitute) {
70095 return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node),
70096 /*location*/ node);
70097 }
70098 }
70099 }
70100 return undefined;
70101 }
70102 function substitutePropertyAccessExpression(node) {
70103 return substituteConstantValue(node);
70104 }
70105 function substituteElementAccessExpression(node) {
70106 return substituteConstantValue(node);
70107 }
70108 function substituteConstantValue(node) {
70109 var constantValue = tryGetConstEnumValue(node);
70110 if (constantValue !== undefined) {
70111 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
70112 ts.setConstantValue(node, constantValue);
70113 var substitute = ts.createLiteral(constantValue);
70114 if (!compilerOptions.removeComments) {
70115 var propertyName = ts.isPropertyAccessExpression(node)
70116 ? ts.declarationNameToString(node.name)
70117 : ts.getTextOfNode(node.argumentExpression);
70118 ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
70119 }
70120 return substitute;
70121 }
70122 return node;
70123 }
70124 function tryGetConstEnumValue(node) {
70125 if (compilerOptions.isolatedModules) {
70126 return undefined;
70127 }
70128 return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
70129 }
70130 }
70131 ts.transformTypeScript = transformTypeScript;
70132 function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
70133 var argumentsArray = [];
70134 argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true));
70135 argumentsArray.push(target);
70136 if (memberName) {
70137 argumentsArray.push(memberName);
70138 if (descriptor) {
70139 argumentsArray.push(descriptor);
70140 }
70141 }
70142 context.requestEmitHelper(ts.decorateHelper);
70143 return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
70144 /*typeArguments*/ undefined, argumentsArray), location);
70145 }
70146 ts.decorateHelper = {
70147 name: "typescript:decorate",
70148 scoped: false,
70149 priority: 2,
70150 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 };"
70151 };
70152 function createMetadataHelper(context, metadataKey, metadataValue) {
70153 context.requestEmitHelper(ts.metadataHelper);
70154 return ts.createCall(ts.getHelperName("__metadata"),
70155 /*typeArguments*/ undefined, [
70156 ts.createLiteral(metadataKey),
70157 metadataValue
70158 ]);
70159 }
70160 ts.metadataHelper = {
70161 name: "typescript:metadata",
70162 scoped: false,
70163 priority: 3,
70164 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 };"
70165 };
70166 function createParamHelper(context, expression, parameterOffset, location) {
70167 context.requestEmitHelper(ts.paramHelper);
70168 return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
70169 /*typeArguments*/ undefined, [
70170 ts.createLiteral(parameterOffset),
70171 expression
70172 ]), location);
70173 }
70174 ts.paramHelper = {
70175 name: "typescript:param",
70176 scoped: false,
70177 priority: 4,
70178 text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };"
70179 };
70180})(ts || (ts = {}));
70181/*@internal*/
70182var ts;
70183(function (ts) {
70184 var ES2017SubstitutionFlags;
70185 (function (ES2017SubstitutionFlags) {
70186 /** Enables substitutions for async methods with `super` calls. */
70187 ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
70188 })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
70189 function transformES2017(context) {
70190 var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
70191 var resolver = context.getEmitResolver();
70192 var compilerOptions = context.getCompilerOptions();
70193 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
70194 /**
70195 * Keeps track of whether expression substitution has been enabled for specific edge cases.
70196 * They are persisted between each SourceFile transformation and should not be reset.
70197 */
70198 var enabledSubstitutions;
70199 /**
70200 * This keeps track of containers where `super` is valid, for use with
70201 * just-in-time substitution for `super` expressions inside of async methods.
70202 */
70203 var enclosingSuperContainerFlags = 0;
70204 var enclosingFunctionParameterNames;
70205 /**
70206 * Keeps track of property names accessed on super (`super.x`) within async functions.
70207 */
70208 var capturedSuperProperties;
70209 /** Whether the async function contains an element access on super (`super[x]`). */
70210 var hasSuperElementAccess;
70211 /** A set of node IDs for generated super accessors (variable statements). */
70212 var substitutedSuperAccessors = [];
70213 // Save the previous transformation hooks.
70214 var previousOnEmitNode = context.onEmitNode;
70215 var previousOnSubstituteNode = context.onSubstituteNode;
70216 // Set new transformation hooks.
70217 context.onEmitNode = onEmitNode;
70218 context.onSubstituteNode = onSubstituteNode;
70219 return ts.chainBundle(transformSourceFile);
70220 function transformSourceFile(node) {
70221 if (node.isDeclarationFile) {
70222 return node;
70223 }
70224 var visited = ts.visitEachChild(node, visitor, context);
70225 ts.addEmitHelpers(visited, context.readEmitHelpers());
70226 return visited;
70227 }
70228 function visitor(node) {
70229 if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) {
70230 return node;
70231 }
70232 switch (node.kind) {
70233 case 121 /* AsyncKeyword */:
70234 // ES2017 async modifier should be elided for targets < ES2017
70235 return undefined;
70236 case 201 /* AwaitExpression */:
70237 return visitAwaitExpression(node);
70238 case 156 /* MethodDeclaration */:
70239 return visitMethodDeclaration(node);
70240 case 239 /* FunctionDeclaration */:
70241 return visitFunctionDeclaration(node);
70242 case 196 /* FunctionExpression */:
70243 return visitFunctionExpression(node);
70244 case 197 /* ArrowFunction */:
70245 return visitArrowFunction(node);
70246 case 189 /* PropertyAccessExpression */:
70247 if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) {
70248 capturedSuperProperties.set(node.name.escapedText, true);
70249 }
70250 return ts.visitEachChild(node, visitor, context);
70251 case 190 /* ElementAccessExpression */:
70252 if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) {
70253 hasSuperElementAccess = true;
70254 }
70255 return ts.visitEachChild(node, visitor, context);
70256 default:
70257 return ts.visitEachChild(node, visitor, context);
70258 }
70259 }
70260 function asyncBodyVisitor(node) {
70261 if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
70262 switch (node.kind) {
70263 case 219 /* VariableStatement */:
70264 return visitVariableStatementInAsyncBody(node);
70265 case 225 /* ForStatement */:
70266 return visitForStatementInAsyncBody(node);
70267 case 226 /* ForInStatement */:
70268 return visitForInStatementInAsyncBody(node);
70269 case 227 /* ForOfStatement */:
70270 return visitForOfStatementInAsyncBody(node);
70271 case 274 /* CatchClause */:
70272 return visitCatchClauseInAsyncBody(node);
70273 case 218 /* Block */:
70274 case 232 /* SwitchStatement */:
70275 case 246 /* CaseBlock */:
70276 case 271 /* CaseClause */:
70277 case 272 /* DefaultClause */:
70278 case 235 /* TryStatement */:
70279 case 223 /* DoStatement */:
70280 case 224 /* WhileStatement */:
70281 case 222 /* IfStatement */:
70282 case 231 /* WithStatement */:
70283 case 233 /* LabeledStatement */:
70284 return ts.visitEachChild(node, asyncBodyVisitor, context);
70285 default:
70286 return ts.Debug.assertNever(node, "Unhandled node.");
70287 }
70288 }
70289 return visitor(node);
70290 }
70291 function visitCatchClauseInAsyncBody(node) {
70292 var catchClauseNames = ts.createUnderscoreEscapedMap();
70293 recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
70294 // names declared in a catch variable are block scoped
70295 var catchClauseUnshadowedNames;
70296 catchClauseNames.forEach(function (_, escapedName) {
70297 if (enclosingFunctionParameterNames.has(escapedName)) {
70298 if (!catchClauseUnshadowedNames) {
70299 catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames);
70300 }
70301 catchClauseUnshadowedNames.delete(escapedName);
70302 }
70303 });
70304 if (catchClauseUnshadowedNames) {
70305 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
70306 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
70307 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
70308 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
70309 return result;
70310 }
70311 else {
70312 return ts.visitEachChild(node, asyncBodyVisitor, context);
70313 }
70314 }
70315 function visitVariableStatementInAsyncBody(node) {
70316 if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
70317 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
70318 return expression ? ts.createExpressionStatement(expression) : undefined;
70319 }
70320 return ts.visitEachChild(node, visitor, context);
70321 }
70322 function visitForInStatementInAsyncBody(node) {
70323 return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer)
70324 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
70325 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
70326 }
70327 function visitForOfStatementInAsyncBody(node) {
70328 return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
70329 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
70330 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
70331 }
70332 function visitForStatementInAsyncBody(node) {
70333 var initializer = node.initializer; // TODO: GH#18217
70334 return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer)
70335 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
70336 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
70337 }
70338 /**
70339 * Visits an AwaitExpression node.
70340 *
70341 * This function will be called any time a ES2017 await expression is encountered.
70342 *
70343 * @param node The node to visit.
70344 */
70345 function visitAwaitExpression(node) {
70346 return ts.setOriginalNode(ts.setTextRange(ts.createYield(
70347 /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
70348 }
70349 /**
70350 * Visits a MethodDeclaration node.
70351 *
70352 * This function will be called when one of the following conditions are met:
70353 * - The node is marked as async
70354 *
70355 * @param node The node to visit.
70356 */
70357 function visitMethodDeclaration(node) {
70358 return ts.updateMethod(node,
70359 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
70360 /*questionToken*/ undefined,
70361 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
70362 /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
70363 ? transformAsyncFunctionBody(node)
70364 : ts.visitFunctionBody(node.body, visitor, context));
70365 }
70366 /**
70367 * Visits a FunctionDeclaration node.
70368 *
70369 * This function will be called when one of the following conditions are met:
70370 * - The node is marked async
70371 *
70372 * @param node The node to visit.
70373 */
70374 function visitFunctionDeclaration(node) {
70375 return ts.updateFunctionDeclaration(node,
70376 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
70377 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
70378 /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
70379 ? transformAsyncFunctionBody(node)
70380 : ts.visitFunctionBody(node.body, visitor, context));
70381 }
70382 /**
70383 * Visits a FunctionExpression node.
70384 *
70385 * This function will be called when one of the following conditions are met:
70386 * - The node is marked async
70387 *
70388 * @param node The node to visit.
70389 */
70390 function visitFunctionExpression(node) {
70391 return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
70392 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
70393 /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
70394 ? transformAsyncFunctionBody(node)
70395 : ts.visitFunctionBody(node.body, visitor, context));
70396 }
70397 /**
70398 * Visits an ArrowFunction.
70399 *
70400 * This function will be called when one of the following conditions are met:
70401 * - The node is marked async
70402 *
70403 * @param node The node to visit.
70404 */
70405 function visitArrowFunction(node) {
70406 return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier),
70407 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
70408 /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
70409 ? transformAsyncFunctionBody(node)
70410 : ts.visitFunctionBody(node.body, visitor, context));
70411 }
70412 function recordDeclarationName(_a, names) {
70413 var name = _a.name;
70414 if (ts.isIdentifier(name)) {
70415 names.set(name.escapedText, true);
70416 }
70417 else {
70418 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
70419 var element = _b[_i];
70420 if (!ts.isOmittedExpression(element)) {
70421 recordDeclarationName(element, names);
70422 }
70423 }
70424 }
70425 }
70426 function isVariableDeclarationListWithCollidingName(node) {
70427 return !!node
70428 && ts.isVariableDeclarationList(node)
70429 && !(node.flags & 3 /* BlockScoped */)
70430 && node.declarations.some(collidesWithParameterName);
70431 }
70432 function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
70433 hoistVariableDeclarationList(node);
70434 var variables = ts.getInitializedVariables(node);
70435 if (variables.length === 0) {
70436 if (hasReceiver) {
70437 return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
70438 }
70439 return undefined;
70440 }
70441 return ts.inlineExpressions(ts.map(variables, transformInitializedVariable));
70442 }
70443 function hoistVariableDeclarationList(node) {
70444 ts.forEach(node.declarations, hoistVariable);
70445 }
70446 function hoistVariable(_a) {
70447 var name = _a.name;
70448 if (ts.isIdentifier(name)) {
70449 hoistVariableDeclaration(name);
70450 }
70451 else {
70452 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
70453 var element = _b[_i];
70454 if (!ts.isOmittedExpression(element)) {
70455 hoistVariable(element);
70456 }
70457 }
70458 }
70459 }
70460 function transformInitializedVariable(node) {
70461 var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node);
70462 return ts.visitNode(converted, visitor, ts.isExpression);
70463 }
70464 function collidesWithParameterName(_a) {
70465 var name = _a.name;
70466 if (ts.isIdentifier(name)) {
70467 return enclosingFunctionParameterNames.has(name.escapedText);
70468 }
70469 else {
70470 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
70471 var element = _b[_i];
70472 if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
70473 return true;
70474 }
70475 }
70476 }
70477 return false;
70478 }
70479 function transformAsyncFunctionBody(node) {
70480 resumeLexicalEnvironment();
70481 var original = ts.getOriginalNode(node, ts.isFunctionLike);
70482 var nodeType = original.type;
70483 var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
70484 var isArrowFunction = node.kind === 197 /* ArrowFunction */;
70485 var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
70486 // An async function is emit as an outer function that calls an inner
70487 // generator function. To preserve lexical bindings, we pass the current
70488 // `this` and `arguments` objects to `__awaiter`. The generator function
70489 // passed to `__awaiter` is executed inside of the callback to the
70490 // promise constructor.
70491 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
70492 enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap();
70493 for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
70494 var parameter = _a[_i];
70495 recordDeclarationName(parameter, enclosingFunctionParameterNames);
70496 }
70497 var savedCapturedSuperProperties = capturedSuperProperties;
70498 var savedHasSuperElementAccess = hasSuperElementAccess;
70499 if (!isArrowFunction) {
70500 capturedSuperProperties = ts.createUnderscoreEscapedMap();
70501 hasSuperElementAccess = false;
70502 }
70503 var result;
70504 if (!isArrowFunction) {
70505 var statements = [];
70506 var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
70507 statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
70508 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
70509 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
70510 // This step isn't needed if we eventually transform this to ES5.
70511 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
70512 if (emitSuperHelpers) {
70513 enableSubstitutionForAsyncMethodsWithSuper();
70514 if (ts.hasEntries(capturedSuperProperties)) {
70515 var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
70516 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
70517 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
70518 }
70519 }
70520 var block = ts.createBlock(statements, /*multiLine*/ true);
70521 ts.setTextRange(block, node.body);
70522 if (emitSuperHelpers && hasSuperElementAccess) {
70523 // Emit helpers for super element access expressions (`super[x]`).
70524 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
70525 ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
70526 }
70527 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
70528 ts.addEmitHelper(block, ts.asyncSuperHelper);
70529 }
70530 }
70531 result = block;
70532 }
70533 else {
70534 var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
70535 var declarations = endLexicalEnvironment();
70536 if (ts.some(declarations)) {
70537 var block = ts.convertToFunctionBody(expression);
70538 result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
70539 }
70540 else {
70541 result = expression;
70542 }
70543 }
70544 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
70545 if (!isArrowFunction) {
70546 capturedSuperProperties = savedCapturedSuperProperties;
70547 hasSuperElementAccess = savedHasSuperElementAccess;
70548 }
70549 return result;
70550 }
70551 function transformAsyncFunctionBodyWorker(body, start) {
70552 if (ts.isBlock(body)) {
70553 return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
70554 }
70555 else {
70556 return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
70557 }
70558 }
70559 function getPromiseConstructor(type) {
70560 var typeName = type && ts.getEntityNameFromTypeNode(type);
70561 if (typeName && ts.isEntityName(typeName)) {
70562 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
70563 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
70564 || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
70565 return typeName;
70566 }
70567 }
70568 return undefined;
70569 }
70570 function enableSubstitutionForAsyncMethodsWithSuper() {
70571 if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
70572 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
70573 // We need to enable substitutions for call, property access, and element access
70574 // if we need to rewrite super calls.
70575 context.enableSubstitution(191 /* CallExpression */);
70576 context.enableSubstitution(189 /* PropertyAccessExpression */);
70577 context.enableSubstitution(190 /* ElementAccessExpression */);
70578 // We need to be notified when entering and exiting declarations that bind super.
70579 context.enableEmitNotification(240 /* ClassDeclaration */);
70580 context.enableEmitNotification(156 /* MethodDeclaration */);
70581 context.enableEmitNotification(158 /* GetAccessor */);
70582 context.enableEmitNotification(159 /* SetAccessor */);
70583 context.enableEmitNotification(157 /* Constructor */);
70584 // We need to be notified when entering the generated accessor arrow functions.
70585 context.enableEmitNotification(219 /* VariableStatement */);
70586 }
70587 }
70588 /**
70589 * Hook for node emit.
70590 *
70591 * @param hint A hint as to the intended usage of the node.
70592 * @param node The node to emit.
70593 * @param emit A callback used to emit the node in the printer.
70594 */
70595 function onEmitNode(hint, node, emitCallback) {
70596 // If we need to support substitutions for `super` in an async method,
70597 // we should track it here.
70598 if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
70599 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
70600 if (superContainerFlags !== enclosingSuperContainerFlags) {
70601 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
70602 enclosingSuperContainerFlags = superContainerFlags;
70603 previousOnEmitNode(hint, node, emitCallback);
70604 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
70605 return;
70606 }
70607 }
70608 // Disable substitution in the generated super accessor itself.
70609 else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
70610 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
70611 enclosingSuperContainerFlags = 0;
70612 previousOnEmitNode(hint, node, emitCallback);
70613 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
70614 return;
70615 }
70616 previousOnEmitNode(hint, node, emitCallback);
70617 }
70618 /**
70619 * Hooks node substitutions.
70620 *
70621 * @param hint A hint as to the intended usage of the node.
70622 * @param node The node to substitute.
70623 */
70624 function onSubstituteNode(hint, node) {
70625 node = previousOnSubstituteNode(hint, node);
70626 if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
70627 return substituteExpression(node);
70628 }
70629 return node;
70630 }
70631 function substituteExpression(node) {
70632 switch (node.kind) {
70633 case 189 /* PropertyAccessExpression */:
70634 return substitutePropertyAccessExpression(node);
70635 case 190 /* ElementAccessExpression */:
70636 return substituteElementAccessExpression(node);
70637 case 191 /* CallExpression */:
70638 return substituteCallExpression(node);
70639 }
70640 return node;
70641 }
70642 function substitutePropertyAccessExpression(node) {
70643 if (node.expression.kind === 98 /* SuperKeyword */) {
70644 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
70645 }
70646 return node;
70647 }
70648 function substituteElementAccessExpression(node) {
70649 if (node.expression.kind === 98 /* SuperKeyword */) {
70650 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
70651 }
70652 return node;
70653 }
70654 function substituteCallExpression(node) {
70655 var expression = node.expression;
70656 if (ts.isSuperProperty(expression)) {
70657 var argumentExpression = ts.isPropertyAccessExpression(expression)
70658 ? substitutePropertyAccessExpression(expression)
70659 : substituteElementAccessExpression(expression);
70660 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"),
70661 /*typeArguments*/ undefined, [
70662 ts.createThis()
70663 ].concat(node.arguments));
70664 }
70665 return node;
70666 }
70667 function isSuperContainer(node) {
70668 var kind = node.kind;
70669 return kind === 240 /* ClassDeclaration */
70670 || kind === 157 /* Constructor */
70671 || kind === 156 /* MethodDeclaration */
70672 || kind === 158 /* GetAccessor */
70673 || kind === 159 /* SetAccessor */;
70674 }
70675 function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
70676 if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
70677 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"),
70678 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
70679 }
70680 else {
70681 return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"),
70682 /*typeArguments*/ undefined, [argumentExpression]), location);
70683 }
70684 }
70685 }
70686 ts.transformES2017 = transformES2017;
70687 /** Creates a variable named `_super` with accessor properties for the given property names. */
70688 function createSuperAccessVariableStatement(resolver, node, names) {
70689 // Create a variable declaration with a getter/setter (if binding) definition for each name:
70690 // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
70691 var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
70692 var accessors = [];
70693 names.forEach(function (_, key) {
70694 var name = ts.unescapeLeadingUnderscores(key);
70695 var getterAndSetter = [];
70696 getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(
70697 /* modifiers */ undefined,
70698 /* typeParameters */ undefined,
70699 /* parameters */ [],
70700 /* type */ undefined,
70701 /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
70702 if (hasBinding) {
70703 getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
70704 /* modifiers */ undefined,
70705 /* typeParameters */ undefined,
70706 /* parameters */ [
70707 ts.createParameter(
70708 /* decorators */ undefined,
70709 /* modifiers */ undefined,
70710 /* dotDotDotToken */ undefined, "v",
70711 /* questionToken */ undefined,
70712 /* type */ undefined,
70713 /* initializer */ undefined)
70714 ],
70715 /* type */ undefined,
70716 /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
70717 }
70718 accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
70719 });
70720 return ts.createVariableStatement(
70721 /* modifiers */ undefined, ts.createVariableDeclarationList([
70722 ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"),
70723 /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"),
70724 /* typeArguments */ undefined, [
70725 ts.createNull(),
70726 ts.createObjectLiteral(accessors, /* multiline */ true)
70727 ]))
70728 ], 2 /* Const */));
70729 }
70730 ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
70731 ts.awaiterHelper = {
70732 name: "typescript:awaiter",
70733 scoped: false,
70734 priority: 5,
70735 text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
70736 };
70737 function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
70738 context.requestEmitHelper(ts.awaiterHelper);
70739 var generatorFunc = ts.createFunctionExpression(
70740 /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
70741 /*name*/ undefined,
70742 /*typeParameters*/ undefined,
70743 /*parameters*/ [],
70744 /*type*/ undefined, body);
70745 // Mark this node as originally an async function
70746 (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
70747 return ts.createCall(ts.getHelperName("__awaiter"),
70748 /*typeArguments*/ undefined, [
70749 ts.createThis(),
70750 hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
70751 promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
70752 generatorFunc
70753 ]);
70754 }
70755 ts.asyncSuperHelper = {
70756 name: "typescript:async-super",
70757 scoped: true,
70758 text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex")
70759 };
70760 ts.advancedAsyncSuperHelper = {
70761 name: "typescript:advanced-async-super",
70762 scoped: true,
70763 text: ts.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")
70764 };
70765})(ts || (ts = {}));
70766/*@internal*/
70767var ts;
70768(function (ts) {
70769 var ESNextSubstitutionFlags;
70770 (function (ESNextSubstitutionFlags) {
70771 /** Enables substitutions for async methods with `super` calls. */
70772 ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
70773 })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
70774 function transformES2018(context) {
70775 var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
70776 var resolver = context.getEmitResolver();
70777 var compilerOptions = context.getCompilerOptions();
70778 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
70779 var previousOnEmitNode = context.onEmitNode;
70780 context.onEmitNode = onEmitNode;
70781 var previousOnSubstituteNode = context.onSubstituteNode;
70782 context.onSubstituteNode = onSubstituteNode;
70783 var enabledSubstitutions;
70784 var enclosingFunctionFlags;
70785 var enclosingSuperContainerFlags = 0;
70786 /** Keeps track of property names accessed on super (`super.x`) within async functions. */
70787 var capturedSuperProperties;
70788 /** Whether the async function contains an element access on super (`super[x]`). */
70789 var hasSuperElementAccess;
70790 /** A set of node IDs for generated super accessors. */
70791 var substitutedSuperAccessors = [];
70792 return ts.chainBundle(transformSourceFile);
70793 function transformSourceFile(node) {
70794 if (node.isDeclarationFile) {
70795 return node;
70796 }
70797 var visited = ts.visitEachChild(node, visitor, context);
70798 ts.addEmitHelpers(visited, context.readEmitHelpers());
70799 return visited;
70800 }
70801 function visitor(node) {
70802 return visitorWorker(node, /*noDestructuringValue*/ false);
70803 }
70804 function visitorNoDestructuringValue(node) {
70805 return visitorWorker(node, /*noDestructuringValue*/ true);
70806 }
70807 function visitorNoAsyncModifier(node) {
70808 if (node.kind === 121 /* AsyncKeyword */) {
70809 return undefined;
70810 }
70811 return node;
70812 }
70813 function visitorWorker(node, noDestructuringValue) {
70814 if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) {
70815 return node;
70816 }
70817 switch (node.kind) {
70818 case 201 /* AwaitExpression */:
70819 return visitAwaitExpression(node);
70820 case 207 /* YieldExpression */:
70821 return visitYieldExpression(node);
70822 case 230 /* ReturnStatement */:
70823 return visitReturnStatement(node);
70824 case 233 /* LabeledStatement */:
70825 return visitLabeledStatement(node);
70826 case 188 /* ObjectLiteralExpression */:
70827 return visitObjectLiteralExpression(node);
70828 case 204 /* BinaryExpression */:
70829 return visitBinaryExpression(node, noDestructuringValue);
70830 case 237 /* VariableDeclaration */:
70831 return visitVariableDeclaration(node);
70832 case 227 /* ForOfStatement */:
70833 return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
70834 case 225 /* ForStatement */:
70835 return visitForStatement(node);
70836 case 200 /* VoidExpression */:
70837 return visitVoidExpression(node);
70838 case 157 /* Constructor */:
70839 return visitConstructorDeclaration(node);
70840 case 156 /* MethodDeclaration */:
70841 return visitMethodDeclaration(node);
70842 case 158 /* GetAccessor */:
70843 return visitGetAccessorDeclaration(node);
70844 case 159 /* SetAccessor */:
70845 return visitSetAccessorDeclaration(node);
70846 case 239 /* FunctionDeclaration */:
70847 return visitFunctionDeclaration(node);
70848 case 196 /* FunctionExpression */:
70849 return visitFunctionExpression(node);
70850 case 197 /* ArrowFunction */:
70851 return visitArrowFunction(node);
70852 case 151 /* Parameter */:
70853 return visitParameter(node);
70854 case 221 /* ExpressionStatement */:
70855 return visitExpressionStatement(node);
70856 case 195 /* ParenthesizedExpression */:
70857 return visitParenthesizedExpression(node, noDestructuringValue);
70858 case 189 /* PropertyAccessExpression */:
70859 if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) {
70860 capturedSuperProperties.set(node.name.escapedText, true);
70861 }
70862 return ts.visitEachChild(node, visitor, context);
70863 case 190 /* ElementAccessExpression */:
70864 if (capturedSuperProperties && node.expression.kind === 98 /* SuperKeyword */) {
70865 hasSuperElementAccess = true;
70866 }
70867 return ts.visitEachChild(node, visitor, context);
70868 default:
70869 return ts.visitEachChild(node, visitor, context);
70870 }
70871 }
70872 function visitAwaitExpression(node) {
70873 if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
70874 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))),
70875 /*location*/ node), node);
70876 }
70877 return ts.visitEachChild(node, visitor, context);
70878 }
70879 function visitYieldExpression(node) {
70880 if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
70881 if (node.asteriskToken) {
70882 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
70883 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
70884 }
70885 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
70886 ? ts.visitNode(node.expression, visitor, ts.isExpression)
70887 : ts.createVoidZero())), node), node);
70888 }
70889 return ts.visitEachChild(node, visitor, context);
70890 }
70891 function visitReturnStatement(node) {
70892 if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
70893 return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero()));
70894 }
70895 return ts.visitEachChild(node, visitor, context);
70896 }
70897 function visitLabeledStatement(node) {
70898 if (enclosingFunctionFlags & 2 /* Async */) {
70899 var statement = ts.unwrapInnermostStatementOfLabel(node);
70900 if (statement.kind === 227 /* ForOfStatement */ && statement.awaitModifier) {
70901 return visitForOfStatement(statement, node);
70902 }
70903 return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node);
70904 }
70905 return ts.visitEachChild(node, visitor, context);
70906 }
70907 function chunkObjectLiteralElements(elements) {
70908 var chunkObject;
70909 var objects = [];
70910 for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
70911 var e = elements_4[_i];
70912 if (e.kind === 277 /* SpreadAssignment */) {
70913 if (chunkObject) {
70914 objects.push(ts.createObjectLiteral(chunkObject));
70915 chunkObject = undefined;
70916 }
70917 var target = e.expression;
70918 objects.push(ts.visitNode(target, visitor, ts.isExpression));
70919 }
70920 else {
70921 chunkObject = ts.append(chunkObject, e.kind === 275 /* PropertyAssignment */
70922 ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
70923 : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
70924 }
70925 }
70926 if (chunkObject) {
70927 objects.push(ts.createObjectLiteral(chunkObject));
70928 }
70929 return objects;
70930 }
70931 function visitObjectLiteralExpression(node) {
70932 if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
70933 // spread elements emit like so:
70934 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
70935 // { a, ...o, b } => __assign({a}, o, {b});
70936 // If the first element is a spread element, then the first argument to __assign is {}:
70937 // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2)
70938 var objects = chunkObjectLiteralElements(node.properties);
70939 if (objects.length && objects[0].kind !== 188 /* ObjectLiteralExpression */) {
70940 objects.unshift(ts.createObjectLiteral());
70941 }
70942 return createAssignHelper(context, objects);
70943 }
70944 return ts.visitEachChild(node, visitor, context);
70945 }
70946 function visitExpressionStatement(node) {
70947 return ts.visitEachChild(node, visitorNoDestructuringValue, context);
70948 }
70949 function visitParenthesizedExpression(node, noDestructuringValue) {
70950 return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
70951 }
70952 /**
70953 * Visits a BinaryExpression that contains a destructuring assignment.
70954 *
70955 * @param node A BinaryExpression node.
70956 */
70957 function visitBinaryExpression(node, noDestructuringValue) {
70958 if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
70959 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
70960 }
70961 else if (node.operatorToken.kind === 27 /* CommaToken */) {
70962 return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression));
70963 }
70964 return ts.visitEachChild(node, visitor, context);
70965 }
70966 /**
70967 * Visits a VariableDeclaration node with a binding pattern.
70968 *
70969 * @param node A VariableDeclaration node.
70970 */
70971 function visitVariableDeclaration(node) {
70972 // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
70973 if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
70974 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */);
70975 }
70976 return ts.visitEachChild(node, visitor, context);
70977 }
70978 function visitForStatement(node) {
70979 return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement));
70980 }
70981 function visitVoidExpression(node) {
70982 return ts.visitEachChild(node, visitorNoDestructuringValue, context);
70983 }
70984 /**
70985 * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
70986 *
70987 * @param node A ForOfStatement.
70988 */
70989 function visitForOfStatement(node, outermostLabeledStatement) {
70990 if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
70991 node = transformForOfStatementWithObjectRest(node);
70992 }
70993 if (node.awaitModifier) {
70994 return transformForAwaitOfStatement(node, outermostLabeledStatement);
70995 }
70996 else {
70997 return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
70998 }
70999 }
71000 function transformForOfStatementWithObjectRest(node) {
71001 var initializerWithoutParens = ts.skipParentheses(node.initializer);
71002 if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
71003 var bodyLocation = void 0;
71004 var statementsLocation = void 0;
71005 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
71006 var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)];
71007 if (ts.isBlock(node.statement)) {
71008 ts.addRange(statements, node.statement.statements);
71009 bodyLocation = node.statement;
71010 statementsLocation = node.statement.statements;
71011 }
71012 else if (node.statement) {
71013 ts.append(statements, node.statement);
71014 bodyLocation = node.statement;
71015 statementsLocation = node.statement;
71016 }
71017 return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([
71018 ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer)
71019 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation),
71020 /*multiLine*/ true), bodyLocation));
71021 }
71022 return node;
71023 }
71024 function convertForOfStatementHead(node, boundValue) {
71025 var binding = ts.createForOfBindingStatement(node.initializer, boundValue);
71026 var bodyLocation;
71027 var statementsLocation;
71028 var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
71029 var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
71030 if (ts.isBlock(statement)) {
71031 ts.addRange(statements, statement.statements);
71032 bodyLocation = statement;
71033 statementsLocation = statement.statements;
71034 }
71035 else {
71036 statements.push(statement);
71037 }
71038 return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation),
71039 /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
71040 }
71041 function createDownlevelAwait(expression) {
71042 return enclosingFunctionFlags & 1 /* Generator */
71043 ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
71044 : ts.createAwait(expression);
71045 }
71046 function transformForAwaitOfStatement(node, outermostLabeledStatement) {
71047 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
71048 var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
71049 var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
71050 var errorRecord = ts.createUniqueName("e");
71051 var catchVariable = ts.getGeneratedNameForNode(errorRecord);
71052 var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
71053 var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
71054 var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
71055 var getDone = ts.createPropertyAccess(result, "done");
71056 var getValue = ts.createPropertyAccess(result, "value");
71057 var callReturn = ts.createFunctionCall(returnMethod, iterator, []);
71058 hoistVariableDeclaration(errorRecord);
71059 hoistVariableDeclaration(returnMethod);
71060 var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
71061 /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
71062 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression),
71063 ts.createVariableDeclaration(result)
71064 ]), node.expression), 2097152 /* NoHoisting */),
71065 /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)),
71066 /*incrementor*/ undefined,
71067 /*statement*/ convertForOfStatementHead(node, getValue)),
71068 /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
71069 return ts.createTry(ts.createBlock([
71070 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
71071 ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
71072 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
71073 ts.createPropertyAssignment("error", catchVariable)
71074 ])))
71075 ]), 1 /* SingleLine */)), ts.createBlock([
71076 ts.createTry(
71077 /*tryBlock*/ ts.createBlock([
71078 ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */)
71079 ]),
71080 /*catchClause*/ undefined,
71081 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
71082 ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
71083 ]), 1 /* SingleLine */))
71084 ]));
71085 }
71086 function visitParameter(node) {
71087 if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
71088 // Binding patterns are converted into a generated name and are
71089 // evaluated inside the function body.
71090 return ts.updateParameter(node,
71091 /*decorators*/ undefined,
71092 /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node),
71093 /*questionToken*/ undefined,
71094 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
71095 }
71096 return ts.visitEachChild(node, visitor, context);
71097 }
71098 function visitConstructorDeclaration(node) {
71099 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
71100 enclosingFunctionFlags = 0 /* Normal */;
71101 var updated = ts.updateConstructor(node,
71102 /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
71103 enclosingFunctionFlags = savedEnclosingFunctionFlags;
71104 return updated;
71105 }
71106 function visitGetAccessorDeclaration(node) {
71107 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
71108 enclosingFunctionFlags = 0 /* Normal */;
71109 var updated = ts.updateGetAccessor(node,
71110 /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context),
71111 /*type*/ undefined, transformFunctionBody(node));
71112 enclosingFunctionFlags = savedEnclosingFunctionFlags;
71113 return updated;
71114 }
71115 function visitSetAccessorDeclaration(node) {
71116 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
71117 enclosingFunctionFlags = 0 /* Normal */;
71118 var updated = ts.updateSetAccessor(node,
71119 /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
71120 enclosingFunctionFlags = savedEnclosingFunctionFlags;
71121 return updated;
71122 }
71123 function visitMethodDeclaration(node) {
71124 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
71125 enclosingFunctionFlags = ts.getFunctionFlags(node);
71126 var updated = ts.updateMethod(node,
71127 /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
71128 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
71129 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
71130 ? undefined
71131 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken),
71132 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
71133 /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
71134 ? transformAsyncGeneratorFunctionBody(node)
71135 : transformFunctionBody(node));
71136 enclosingFunctionFlags = savedEnclosingFunctionFlags;
71137 return updated;
71138 }
71139 function visitFunctionDeclaration(node) {
71140 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
71141 enclosingFunctionFlags = ts.getFunctionFlags(node);
71142 var updated = ts.updateFunctionDeclaration(node,
71143 /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
71144 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
71145 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
71146 ? undefined
71147 : node.asteriskToken, node.name,
71148 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
71149 /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
71150 ? transformAsyncGeneratorFunctionBody(node)
71151 : transformFunctionBody(node));
71152 enclosingFunctionFlags = savedEnclosingFunctionFlags;
71153 return updated;
71154 }
71155 function visitArrowFunction(node) {
71156 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
71157 enclosingFunctionFlags = ts.getFunctionFlags(node);
71158 var updated = ts.updateArrowFunction(node, node.modifiers,
71159 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
71160 /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
71161 enclosingFunctionFlags = savedEnclosingFunctionFlags;
71162 return updated;
71163 }
71164 function visitFunctionExpression(node) {
71165 var savedEnclosingFunctionFlags = enclosingFunctionFlags;
71166 enclosingFunctionFlags = ts.getFunctionFlags(node);
71167 var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
71168 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
71169 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
71170 ? undefined
71171 : node.asteriskToken, node.name,
71172 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
71173 /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
71174 ? transformAsyncGeneratorFunctionBody(node)
71175 : transformFunctionBody(node));
71176 enclosingFunctionFlags = savedEnclosingFunctionFlags;
71177 return updated;
71178 }
71179 function transformAsyncGeneratorFunctionBody(node) {
71180 resumeLexicalEnvironment();
71181 var statements = [];
71182 var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
71183 appendObjectRestAssignmentsIfNeeded(statements, node);
71184 var savedCapturedSuperProperties = capturedSuperProperties;
71185 var savedHasSuperElementAccess = hasSuperElementAccess;
71186 capturedSuperProperties = ts.createUnderscoreEscapedMap();
71187 hasSuperElementAccess = false;
71188 var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(
71189 /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name),
71190 /*typeParameters*/ undefined,
71191 /*parameters*/ [],
71192 /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))));
71193 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
71194 // This step isn't needed if we eventually transform this to ES5.
71195 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
71196 if (emitSuperHelpers) {
71197 enableSubstitutionForAsyncMethodsWithSuper();
71198 var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
71199 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
71200 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
71201 }
71202 statements.push(returnStatement);
71203 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
71204 var block = ts.updateBlock(node.body, statements);
71205 if (emitSuperHelpers && hasSuperElementAccess) {
71206 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
71207 ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
71208 }
71209 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
71210 ts.addEmitHelper(block, ts.asyncSuperHelper);
71211 }
71212 }
71213 capturedSuperProperties = savedCapturedSuperProperties;
71214 hasSuperElementAccess = savedHasSuperElementAccess;
71215 return block;
71216 }
71217 function transformFunctionBody(node) {
71218 resumeLexicalEnvironment();
71219 var statementOffset = 0;
71220 var statements = [];
71221 var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
71222 if (ts.isBlock(body)) {
71223 statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
71224 }
71225 ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
71226 var leadingStatements = endLexicalEnvironment();
71227 if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
71228 var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
71229 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
71230 ts.addRange(statements, block.statements.slice(statementOffset));
71231 return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
71232 }
71233 return body;
71234 }
71235 function appendObjectRestAssignmentsIfNeeded(statements, node) {
71236 for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
71237 var parameter = _a[_i];
71238 if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
71239 var temp = ts.getGeneratedNameForNode(parameter);
71240 var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp,
71241 /*doNotRecordTempVariablesInLine*/ false,
71242 /*skipInitializer*/ true);
71243 if (ts.some(declarations)) {
71244 var statement = ts.createVariableStatement(
71245 /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations));
71246 ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
71247 statements = ts.append(statements, statement);
71248 }
71249 }
71250 }
71251 return statements;
71252 }
71253 function enableSubstitutionForAsyncMethodsWithSuper() {
71254 if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
71255 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
71256 // We need to enable substitutions for call, property access, and element access
71257 // if we need to rewrite super calls.
71258 context.enableSubstitution(191 /* CallExpression */);
71259 context.enableSubstitution(189 /* PropertyAccessExpression */);
71260 context.enableSubstitution(190 /* ElementAccessExpression */);
71261 // We need to be notified when entering and exiting declarations that bind super.
71262 context.enableEmitNotification(240 /* ClassDeclaration */);
71263 context.enableEmitNotification(156 /* MethodDeclaration */);
71264 context.enableEmitNotification(158 /* GetAccessor */);
71265 context.enableEmitNotification(159 /* SetAccessor */);
71266 context.enableEmitNotification(157 /* Constructor */);
71267 // We need to be notified when entering the generated accessor arrow functions.
71268 context.enableEmitNotification(219 /* VariableStatement */);
71269 }
71270 }
71271 /**
71272 * Called by the printer just before a node is printed.
71273 *
71274 * @param hint A hint as to the intended usage of the node.
71275 * @param node The node to be printed.
71276 * @param emitCallback The callback used to emit the node.
71277 */
71278 function onEmitNode(hint, node, emitCallback) {
71279 // If we need to support substitutions for `super` in an async method,
71280 // we should track it here.
71281 if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
71282 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
71283 if (superContainerFlags !== enclosingSuperContainerFlags) {
71284 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
71285 enclosingSuperContainerFlags = superContainerFlags;
71286 previousOnEmitNode(hint, node, emitCallback);
71287 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
71288 return;
71289 }
71290 }
71291 // Disable substitution in the generated super accessor itself.
71292 else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
71293 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
71294 enclosingSuperContainerFlags = 0;
71295 previousOnEmitNode(hint, node, emitCallback);
71296 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
71297 return;
71298 }
71299 previousOnEmitNode(hint, node, emitCallback);
71300 }
71301 /**
71302 * Hooks node substitutions.
71303 *
71304 * @param hint The context for the emitter.
71305 * @param node The node to substitute.
71306 */
71307 function onSubstituteNode(hint, node) {
71308 node = previousOnSubstituteNode(hint, node);
71309 if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
71310 return substituteExpression(node);
71311 }
71312 return node;
71313 }
71314 function substituteExpression(node) {
71315 switch (node.kind) {
71316 case 189 /* PropertyAccessExpression */:
71317 return substitutePropertyAccessExpression(node);
71318 case 190 /* ElementAccessExpression */:
71319 return substituteElementAccessExpression(node);
71320 case 191 /* CallExpression */:
71321 return substituteCallExpression(node);
71322 }
71323 return node;
71324 }
71325 function substitutePropertyAccessExpression(node) {
71326 if (node.expression.kind === 98 /* SuperKeyword */) {
71327 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
71328 }
71329 return node;
71330 }
71331 function substituteElementAccessExpression(node) {
71332 if (node.expression.kind === 98 /* SuperKeyword */) {
71333 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
71334 }
71335 return node;
71336 }
71337 function substituteCallExpression(node) {
71338 var expression = node.expression;
71339 if (ts.isSuperProperty(expression)) {
71340 var argumentExpression = ts.isPropertyAccessExpression(expression)
71341 ? substitutePropertyAccessExpression(expression)
71342 : substituteElementAccessExpression(expression);
71343 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"),
71344 /*typeArguments*/ undefined, [
71345 ts.createThis()
71346 ].concat(node.arguments));
71347 }
71348 return node;
71349 }
71350 function isSuperContainer(node) {
71351 var kind = node.kind;
71352 return kind === 240 /* ClassDeclaration */
71353 || kind === 157 /* Constructor */
71354 || kind === 156 /* MethodDeclaration */
71355 || kind === 158 /* GetAccessor */
71356 || kind === 159 /* SetAccessor */;
71357 }
71358 function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
71359 if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
71360 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"),
71361 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
71362 }
71363 else {
71364 return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"),
71365 /*typeArguments*/ undefined, [argumentExpression]), location);
71366 }
71367 }
71368 }
71369 ts.transformES2018 = transformES2018;
71370 ts.assignHelper = {
71371 name: "typescript:assign",
71372 scoped: false,
71373 priority: 1,
71374 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 };"
71375 };
71376 function createAssignHelper(context, attributesSegments) {
71377 if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
71378 return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
71379 /*typeArguments*/ undefined, attributesSegments);
71380 }
71381 context.requestEmitHelper(ts.assignHelper);
71382 return ts.createCall(ts.getHelperName("__assign"),
71383 /*typeArguments*/ undefined, attributesSegments);
71384 }
71385 ts.createAssignHelper = createAssignHelper;
71386 ts.awaitHelper = {
71387 name: "typescript:await",
71388 scoped: false,
71389 text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
71390 };
71391 function createAwaitHelper(context, expression) {
71392 context.requestEmitHelper(ts.awaitHelper);
71393 return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
71394 }
71395 ts.asyncGeneratorHelper = {
71396 name: "typescript:asyncGenerator",
71397 scoped: false,
71398 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 };"
71399 };
71400 function createAsyncGeneratorHelper(context, generatorFunc) {
71401 context.requestEmitHelper(ts.awaitHelper);
71402 context.requestEmitHelper(ts.asyncGeneratorHelper);
71403 // Mark this node as originally an async function
71404 (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
71405 return ts.createCall(ts.getHelperName("__asyncGenerator"),
71406 /*typeArguments*/ undefined, [
71407 ts.createThis(),
71408 ts.createIdentifier("arguments"),
71409 generatorFunc
71410 ]);
71411 }
71412 ts.asyncDelegator = {
71413 name: "typescript:asyncDelegator",
71414 scoped: false,
71415 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 };"
71416 };
71417 function createAsyncDelegatorHelper(context, expression, location) {
71418 context.requestEmitHelper(ts.awaitHelper);
71419 context.requestEmitHelper(ts.asyncDelegator);
71420 return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
71421 /*typeArguments*/ undefined, [expression]), location);
71422 }
71423 ts.asyncValues = {
71424 name: "typescript:asyncValues",
71425 scoped: false,
71426 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 };"
71427 };
71428 function createAsyncValuesHelper(context, expression, location) {
71429 context.requestEmitHelper(ts.asyncValues);
71430 return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
71431 /*typeArguments*/ undefined, [expression]), location);
71432 }
71433})(ts || (ts = {}));
71434/*@internal*/
71435var ts;
71436(function (ts) {
71437 function transformES2019(context) {
71438 return ts.chainBundle(transformSourceFile);
71439 function transformSourceFile(node) {
71440 if (node.isDeclarationFile) {
71441 return node;
71442 }
71443 return ts.visitEachChild(node, visitor, context);
71444 }
71445 function visitor(node) {
71446 if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) {
71447 return node;
71448 }
71449 switch (node.kind) {
71450 case 274 /* CatchClause */:
71451 return visitCatchClause(node);
71452 default:
71453 return ts.visitEachChild(node, visitor, context);
71454 }
71455 }
71456 function visitCatchClause(node) {
71457 if (!node.variableDeclaration) {
71458 return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
71459 }
71460 return ts.visitEachChild(node, visitor, context);
71461 }
71462 }
71463 ts.transformES2019 = transformES2019;
71464})(ts || (ts = {}));
71465/*@internal*/
71466var ts;
71467(function (ts) {
71468 function transformESNext(context) {
71469 return ts.chainBundle(transformSourceFile);
71470 function transformSourceFile(node) {
71471 if (node.isDeclarationFile) {
71472 return node;
71473 }
71474 return ts.visitEachChild(node, visitor, context);
71475 }
71476 function visitor(node) {
71477 if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
71478 return node;
71479 }
71480 switch (node.kind) {
71481 default:
71482 return ts.visitEachChild(node, visitor, context);
71483 }
71484 }
71485 }
71486 ts.transformESNext = transformESNext;
71487})(ts || (ts = {}));
71488/*@internal*/
71489var ts;
71490(function (ts) {
71491 function transformJsx(context) {
71492 var compilerOptions = context.getCompilerOptions();
71493 var currentSourceFile;
71494 return ts.chainBundle(transformSourceFile);
71495 /**
71496 * Transform JSX-specific syntax in a SourceFile.
71497 *
71498 * @param node A SourceFile node.
71499 */
71500 function transformSourceFile(node) {
71501 if (node.isDeclarationFile) {
71502 return node;
71503 }
71504 currentSourceFile = node;
71505 var visited = ts.visitEachChild(node, visitor, context);
71506 ts.addEmitHelpers(visited, context.readEmitHelpers());
71507 return visited;
71508 }
71509 function visitor(node) {
71510 if (node.transformFlags & 2 /* ContainsJsx */) {
71511 return visitorWorker(node);
71512 }
71513 else {
71514 return node;
71515 }
71516 }
71517 function visitorWorker(node) {
71518 switch (node.kind) {
71519 case 260 /* JsxElement */:
71520 return visitJsxElement(node, /*isChild*/ false);
71521 case 261 /* JsxSelfClosingElement */:
71522 return visitJsxSelfClosingElement(node, /*isChild*/ false);
71523 case 264 /* JsxFragment */:
71524 return visitJsxFragment(node, /*isChild*/ false);
71525 case 270 /* JsxExpression */:
71526 return visitJsxExpression(node);
71527 default:
71528 return ts.visitEachChild(node, visitor, context);
71529 }
71530 }
71531 function transformJsxChildToExpression(node) {
71532 switch (node.kind) {
71533 case 11 /* JsxText */:
71534 return visitJsxText(node);
71535 case 270 /* JsxExpression */:
71536 return visitJsxExpression(node);
71537 case 260 /* JsxElement */:
71538 return visitJsxElement(node, /*isChild*/ true);
71539 case 261 /* JsxSelfClosingElement */:
71540 return visitJsxSelfClosingElement(node, /*isChild*/ true);
71541 case 264 /* JsxFragment */:
71542 return visitJsxFragment(node, /*isChild*/ true);
71543 default:
71544 return ts.Debug.failBadSyntaxKind(node);
71545 }
71546 }
71547 function visitJsxElement(node, isChild) {
71548 return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
71549 }
71550 function visitJsxSelfClosingElement(node, isChild) {
71551 return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
71552 }
71553 function visitJsxFragment(node, isChild) {
71554 return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
71555 }
71556 function visitJsxOpeningLikeElement(node, children, isChild, location) {
71557 var tagName = getTagName(node);
71558 var objectProperties;
71559 var attrs = node.attributes.properties;
71560 if (attrs.length === 0) {
71561 // When there are no attributes, React wants "null"
71562 objectProperties = ts.createNull();
71563 }
71564 else {
71565 // Map spans of JsxAttribute nodes into object literals and spans
71566 // of JsxSpreadAttribute nodes into expressions.
71567 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
71568 ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
71569 : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
71570 if (ts.isJsxSpreadAttribute(attrs[0])) {
71571 // We must always emit at least one object literal before a spread
71572 // argument.
71573 segments.unshift(ts.createObjectLiteral());
71574 }
71575 // Either emit one big object literal (no spread attribs), or
71576 // a call to the __assign helper.
71577 objectProperties = ts.singleOrUndefined(segments);
71578 if (!objectProperties) {
71579 objectProperties = ts.createAssignHelper(context, segments);
71580 }
71581 }
71582 var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
71583 tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
71584 if (isChild) {
71585 ts.startOnNewLine(element);
71586 }
71587 return element;
71588 }
71589 function visitJsxOpeningFragment(node, children, isChild, location) {
71590 var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
71591 ts.mapDefined(children, transformJsxChildToExpression), node, location);
71592 if (isChild) {
71593 ts.startOnNewLine(element);
71594 }
71595 return element;
71596 }
71597 function transformJsxSpreadAttributeToExpression(node) {
71598 return ts.visitNode(node.expression, visitor, ts.isExpression);
71599 }
71600 function transformJsxAttributeToObjectLiteralElement(node) {
71601 var name = getAttributeName(node);
71602 var expression = transformJsxAttributeInitializer(node.initializer);
71603 return ts.createPropertyAssignment(name, expression);
71604 }
71605 function transformJsxAttributeInitializer(node) {
71606 if (node === undefined) {
71607 return ts.createTrue();
71608 }
71609 else if (node.kind === 10 /* StringLiteral */) {
71610 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
71611 // Need to be escaped to be handled correctly in a normal string
71612 var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text);
71613 literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
71614 return ts.setTextRange(literal, node);
71615 }
71616 else if (node.kind === 270 /* JsxExpression */) {
71617 if (node.expression === undefined) {
71618 return ts.createTrue();
71619 }
71620 return visitJsxExpression(node);
71621 }
71622 else {
71623 return ts.Debug.failBadSyntaxKind(node);
71624 }
71625 }
71626 function visitJsxText(node) {
71627 var fixed = fixupWhitespaceAndDecodeEntities(node.text);
71628 return fixed === undefined ? undefined : ts.createLiteral(fixed);
71629 }
71630 /**
71631 * JSX trims whitespace at the end and beginning of lines, except that the
71632 * start/end of a tag is considered a start/end of a line only if that line is
71633 * on the same line as the closing tag. See examples in
71634 * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
71635 * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model
71636 *
71637 * An equivalent algorithm would be:
71638 * - If there is only one line, return it.
71639 * - If there is only whitespace (but multiple lines), return `undefined`.
71640 * - Split the text into lines.
71641 * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
71642 * - Decode entities on each line (individually).
71643 * - Remove empty lines and join the rest with " ".
71644 */
71645 function fixupWhitespaceAndDecodeEntities(text) {
71646 var acc;
71647 // First non-whitespace character on this line.
71648 var firstNonWhitespace = 0;
71649 // Last non-whitespace character on this line.
71650 var lastNonWhitespace = -1;
71651 // These initial values are special because the first line is:
71652 // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
71653 // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
71654 for (var i = 0; i < text.length; i++) {
71655 var c = text.charCodeAt(i);
71656 if (ts.isLineBreak(c)) {
71657 // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
71658 // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
71659 if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
71660 acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
71661 }
71662 // Reset firstNonWhitespace for the next line.
71663 // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
71664 firstNonWhitespace = -1;
71665 }
71666 else if (!ts.isWhiteSpaceSingleLine(c)) {
71667 lastNonWhitespace = i;
71668 if (firstNonWhitespace === -1) {
71669 firstNonWhitespace = i;
71670 }
71671 }
71672 }
71673 return firstNonWhitespace !== -1
71674 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
71675 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
71676 // Last line was all whitespace, so ignore it
71677 : acc;
71678 }
71679 function addLineOfJsxText(acc, trimmedLine) {
71680 // We do not escape the string here as that is handled by the printer
71681 // when it emits the literal. We do, however, need to decode JSX entities.
71682 var decoded = decodeEntities(trimmedLine);
71683 return acc === undefined ? decoded : acc + " " + decoded;
71684 }
71685 /**
71686 * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
71687 * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
71688 */
71689 function decodeEntities(text) {
71690 return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
71691 if (decimal) {
71692 return String.fromCharCode(parseInt(decimal, 10));
71693 }
71694 else if (hex) {
71695 return String.fromCharCode(parseInt(hex, 16));
71696 }
71697 else {
71698 var ch = entities.get(word);
71699 // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
71700 return ch ? String.fromCharCode(ch) : match;
71701 }
71702 });
71703 }
71704 /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
71705 function tryDecodeEntities(text) {
71706 var decoded = decodeEntities(text);
71707 return decoded === text ? undefined : decoded;
71708 }
71709 function getTagName(node) {
71710 if (node.kind === 260 /* JsxElement */) {
71711 return getTagName(node.openingElement);
71712 }
71713 else {
71714 var name = node.tagName;
71715 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
71716 return ts.createLiteral(ts.idText(name));
71717 }
71718 else {
71719 return ts.createExpressionFromEntityName(name);
71720 }
71721 }
71722 }
71723 /**
71724 * Emit an attribute name, which is quoted if it needs to be quoted. Because
71725 * these emit into an object literal property name, we don't need to be worried
71726 * about keywords, just non-identifier characters
71727 */
71728 function getAttributeName(node) {
71729 var name = node.name;
71730 var text = ts.idText(name);
71731 if (/^[A-Za-z_]\w*$/.test(text)) {
71732 return name;
71733 }
71734 else {
71735 return ts.createLiteral(text);
71736 }
71737 }
71738 function visitJsxExpression(node) {
71739 return ts.visitNode(node.expression, visitor, ts.isExpression);
71740 }
71741 }
71742 ts.transformJsx = transformJsx;
71743 var entities = ts.createMapFromTemplate({
71744 quot: 0x0022,
71745 amp: 0x0026,
71746 apos: 0x0027,
71747 lt: 0x003C,
71748 gt: 0x003E,
71749 nbsp: 0x00A0,
71750 iexcl: 0x00A1,
71751 cent: 0x00A2,
71752 pound: 0x00A3,
71753 curren: 0x00A4,
71754 yen: 0x00A5,
71755 brvbar: 0x00A6,
71756 sect: 0x00A7,
71757 uml: 0x00A8,
71758 copy: 0x00A9,
71759 ordf: 0x00AA,
71760 laquo: 0x00AB,
71761 not: 0x00AC,
71762 shy: 0x00AD,
71763 reg: 0x00AE,
71764 macr: 0x00AF,
71765 deg: 0x00B0,
71766 plusmn: 0x00B1,
71767 sup2: 0x00B2,
71768 sup3: 0x00B3,
71769 acute: 0x00B4,
71770 micro: 0x00B5,
71771 para: 0x00B6,
71772 middot: 0x00B7,
71773 cedil: 0x00B8,
71774 sup1: 0x00B9,
71775 ordm: 0x00BA,
71776 raquo: 0x00BB,
71777 frac14: 0x00BC,
71778 frac12: 0x00BD,
71779 frac34: 0x00BE,
71780 iquest: 0x00BF,
71781 Agrave: 0x00C0,
71782 Aacute: 0x00C1,
71783 Acirc: 0x00C2,
71784 Atilde: 0x00C3,
71785 Auml: 0x00C4,
71786 Aring: 0x00C5,
71787 AElig: 0x00C6,
71788 Ccedil: 0x00C7,
71789 Egrave: 0x00C8,
71790 Eacute: 0x00C9,
71791 Ecirc: 0x00CA,
71792 Euml: 0x00CB,
71793 Igrave: 0x00CC,
71794 Iacute: 0x00CD,
71795 Icirc: 0x00CE,
71796 Iuml: 0x00CF,
71797 ETH: 0x00D0,
71798 Ntilde: 0x00D1,
71799 Ograve: 0x00D2,
71800 Oacute: 0x00D3,
71801 Ocirc: 0x00D4,
71802 Otilde: 0x00D5,
71803 Ouml: 0x00D6,
71804 times: 0x00D7,
71805 Oslash: 0x00D8,
71806 Ugrave: 0x00D9,
71807 Uacute: 0x00DA,
71808 Ucirc: 0x00DB,
71809 Uuml: 0x00DC,
71810 Yacute: 0x00DD,
71811 THORN: 0x00DE,
71812 szlig: 0x00DF,
71813 agrave: 0x00E0,
71814 aacute: 0x00E1,
71815 acirc: 0x00E2,
71816 atilde: 0x00E3,
71817 auml: 0x00E4,
71818 aring: 0x00E5,
71819 aelig: 0x00E6,
71820 ccedil: 0x00E7,
71821 egrave: 0x00E8,
71822 eacute: 0x00E9,
71823 ecirc: 0x00EA,
71824 euml: 0x00EB,
71825 igrave: 0x00EC,
71826 iacute: 0x00ED,
71827 icirc: 0x00EE,
71828 iuml: 0x00EF,
71829 eth: 0x00F0,
71830 ntilde: 0x00F1,
71831 ograve: 0x00F2,
71832 oacute: 0x00F3,
71833 ocirc: 0x00F4,
71834 otilde: 0x00F5,
71835 ouml: 0x00F6,
71836 divide: 0x00F7,
71837 oslash: 0x00F8,
71838 ugrave: 0x00F9,
71839 uacute: 0x00FA,
71840 ucirc: 0x00FB,
71841 uuml: 0x00FC,
71842 yacute: 0x00FD,
71843 thorn: 0x00FE,
71844 yuml: 0x00FF,
71845 OElig: 0x0152,
71846 oelig: 0x0153,
71847 Scaron: 0x0160,
71848 scaron: 0x0161,
71849 Yuml: 0x0178,
71850 fnof: 0x0192,
71851 circ: 0x02C6,
71852 tilde: 0x02DC,
71853 Alpha: 0x0391,
71854 Beta: 0x0392,
71855 Gamma: 0x0393,
71856 Delta: 0x0394,
71857 Epsilon: 0x0395,
71858 Zeta: 0x0396,
71859 Eta: 0x0397,
71860 Theta: 0x0398,
71861 Iota: 0x0399,
71862 Kappa: 0x039A,
71863 Lambda: 0x039B,
71864 Mu: 0x039C,
71865 Nu: 0x039D,
71866 Xi: 0x039E,
71867 Omicron: 0x039F,
71868 Pi: 0x03A0,
71869 Rho: 0x03A1,
71870 Sigma: 0x03A3,
71871 Tau: 0x03A4,
71872 Upsilon: 0x03A5,
71873 Phi: 0x03A6,
71874 Chi: 0x03A7,
71875 Psi: 0x03A8,
71876 Omega: 0x03A9,
71877 alpha: 0x03B1,
71878 beta: 0x03B2,
71879 gamma: 0x03B3,
71880 delta: 0x03B4,
71881 epsilon: 0x03B5,
71882 zeta: 0x03B6,
71883 eta: 0x03B7,
71884 theta: 0x03B8,
71885 iota: 0x03B9,
71886 kappa: 0x03BA,
71887 lambda: 0x03BB,
71888 mu: 0x03BC,
71889 nu: 0x03BD,
71890 xi: 0x03BE,
71891 omicron: 0x03BF,
71892 pi: 0x03C0,
71893 rho: 0x03C1,
71894 sigmaf: 0x03C2,
71895 sigma: 0x03C3,
71896 tau: 0x03C4,
71897 upsilon: 0x03C5,
71898 phi: 0x03C6,
71899 chi: 0x03C7,
71900 psi: 0x03C8,
71901 omega: 0x03C9,
71902 thetasym: 0x03D1,
71903 upsih: 0x03D2,
71904 piv: 0x03D6,
71905 ensp: 0x2002,
71906 emsp: 0x2003,
71907 thinsp: 0x2009,
71908 zwnj: 0x200C,
71909 zwj: 0x200D,
71910 lrm: 0x200E,
71911 rlm: 0x200F,
71912 ndash: 0x2013,
71913 mdash: 0x2014,
71914 lsquo: 0x2018,
71915 rsquo: 0x2019,
71916 sbquo: 0x201A,
71917 ldquo: 0x201C,
71918 rdquo: 0x201D,
71919 bdquo: 0x201E,
71920 dagger: 0x2020,
71921 Dagger: 0x2021,
71922 bull: 0x2022,
71923 hellip: 0x2026,
71924 permil: 0x2030,
71925 prime: 0x2032,
71926 Prime: 0x2033,
71927 lsaquo: 0x2039,
71928 rsaquo: 0x203A,
71929 oline: 0x203E,
71930 frasl: 0x2044,
71931 euro: 0x20AC,
71932 image: 0x2111,
71933 weierp: 0x2118,
71934 real: 0x211C,
71935 trade: 0x2122,
71936 alefsym: 0x2135,
71937 larr: 0x2190,
71938 uarr: 0x2191,
71939 rarr: 0x2192,
71940 darr: 0x2193,
71941 harr: 0x2194,
71942 crarr: 0x21B5,
71943 lArr: 0x21D0,
71944 uArr: 0x21D1,
71945 rArr: 0x21D2,
71946 dArr: 0x21D3,
71947 hArr: 0x21D4,
71948 forall: 0x2200,
71949 part: 0x2202,
71950 exist: 0x2203,
71951 empty: 0x2205,
71952 nabla: 0x2207,
71953 isin: 0x2208,
71954 notin: 0x2209,
71955 ni: 0x220B,
71956 prod: 0x220F,
71957 sum: 0x2211,
71958 minus: 0x2212,
71959 lowast: 0x2217,
71960 radic: 0x221A,
71961 prop: 0x221D,
71962 infin: 0x221E,
71963 ang: 0x2220,
71964 and: 0x2227,
71965 or: 0x2228,
71966 cap: 0x2229,
71967 cup: 0x222A,
71968 int: 0x222B,
71969 there4: 0x2234,
71970 sim: 0x223C,
71971 cong: 0x2245,
71972 asymp: 0x2248,
71973 ne: 0x2260,
71974 equiv: 0x2261,
71975 le: 0x2264,
71976 ge: 0x2265,
71977 sub: 0x2282,
71978 sup: 0x2283,
71979 nsub: 0x2284,
71980 sube: 0x2286,
71981 supe: 0x2287,
71982 oplus: 0x2295,
71983 otimes: 0x2297,
71984 perp: 0x22A5,
71985 sdot: 0x22C5,
71986 lceil: 0x2308,
71987 rceil: 0x2309,
71988 lfloor: 0x230A,
71989 rfloor: 0x230B,
71990 lang: 0x2329,
71991 rang: 0x232A,
71992 loz: 0x25CA,
71993 spades: 0x2660,
71994 clubs: 0x2663,
71995 hearts: 0x2665,
71996 diams: 0x2666
71997 });
71998})(ts || (ts = {}));
71999/*@internal*/
72000var ts;
72001(function (ts) {
72002 function transformES2016(context) {
72003 var hoistVariableDeclaration = context.hoistVariableDeclaration;
72004 return ts.chainBundle(transformSourceFile);
72005 function transformSourceFile(node) {
72006 if (node.isDeclarationFile) {
72007 return node;
72008 }
72009 return ts.visitEachChild(node, visitor, context);
72010 }
72011 function visitor(node) {
72012 if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) {
72013 return node;
72014 }
72015 switch (node.kind) {
72016 case 204 /* BinaryExpression */:
72017 return visitBinaryExpression(node);
72018 default:
72019 return ts.visitEachChild(node, visitor, context);
72020 }
72021 }
72022 function visitBinaryExpression(node) {
72023 switch (node.operatorToken.kind) {
72024 case 63 /* AsteriskAsteriskEqualsToken */:
72025 return visitExponentiationAssignmentExpression(node);
72026 case 41 /* AsteriskAsteriskToken */:
72027 return visitExponentiationExpression(node);
72028 default:
72029 return ts.visitEachChild(node, visitor, context);
72030 }
72031 }
72032 function visitExponentiationAssignmentExpression(node) {
72033 var target;
72034 var value;
72035 var left = ts.visitNode(node.left, visitor, ts.isExpression);
72036 var right = ts.visitNode(node.right, visitor, ts.isExpression);
72037 if (ts.isElementAccessExpression(left)) {
72038 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
72039 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
72040 var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
72041 target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
72042 value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
72043 }
72044 else if (ts.isPropertyAccessExpression(left)) {
72045 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
72046 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
72047 target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
72048 value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
72049 }
72050 else {
72051 // Transforms `a **= b` into `a = Math.pow(a, b)`
72052 target = left;
72053 value = left;
72054 }
72055 return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
72056 }
72057 function visitExponentiationExpression(node) {
72058 // Transforms `a ** b` into `Math.pow(a, b)`
72059 var left = ts.visitNode(node.left, visitor, ts.isExpression);
72060 var right = ts.visitNode(node.right, visitor, ts.isExpression);
72061 return ts.createMathPow(left, right, /*location*/ node);
72062 }
72063 }
72064 ts.transformES2016 = transformES2016;
72065})(ts || (ts = {}));
72066/*@internal*/
72067var ts;
72068(function (ts) {
72069 var ES2015SubstitutionFlags;
72070 (function (ES2015SubstitutionFlags) {
72071 /** Enables substitutions for captured `this` */
72072 ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
72073 /** Enables substitutions for block-scoped bindings. */
72074 ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
72075 })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
72076 var LoopOutParameterFlags;
72077 (function (LoopOutParameterFlags) {
72078 LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
72079 LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
72080 })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
72081 var CopyDirection;
72082 (function (CopyDirection) {
72083 CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
72084 CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
72085 })(CopyDirection || (CopyDirection = {}));
72086 var Jump;
72087 (function (Jump) {
72088 Jump[Jump["Break"] = 2] = "Break";
72089 Jump[Jump["Continue"] = 4] = "Continue";
72090 Jump[Jump["Return"] = 8] = "Return";
72091 })(Jump || (Jump = {}));
72092 // Facts we track as we traverse the tree
72093 var HierarchyFacts;
72094 (function (HierarchyFacts) {
72095 HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
72096 //
72097 // Ancestor facts
72098 //
72099 HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
72100 HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
72101 HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
72102 HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
72103 HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
72104 HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
72105 HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
72106 HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
72107 HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
72108 HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
72109 HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement";
72110 HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement";
72111 HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper";
72112 // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
72113 // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
72114 //
72115 // Ancestor masks
72116 //
72117 HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask";
72118 // We are always in *some* kind of block scope, but only specific block-scope containers are
72119 // top-level or Blocks.
72120 HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
72121 HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes";
72122 // A source file is a top-level block scope.
72123 HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
72124 HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes";
72125 // Functions, methods, and accessors are both new lexical scopes and new block scopes.
72126 HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
72127 HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes";
72128 HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
72129 HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes";
72130 // Arrow functions are lexically scoped to their container, but are new block scopes.
72131 HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
72132 HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes";
72133 // Constructors are both new lexical scopes and new block scopes. Constructors are also
72134 // always considered non-static members of a class.
72135 HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
72136 HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes";
72137 // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
72138 // within an IterationStatement to indicate whether the embedded statement is an
72139 // IterationStatementBlock.
72140 HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes";
72141 HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
72142 // 'for' statements are new block scopes and have special handling for 'let' declarations.
72143 HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes";
72144 HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes";
72145 // 'for-in' and 'for-of' statements are new block scopes and have special handling for
72146 // 'let' declarations.
72147 HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes";
72148 HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes";
72149 // Blocks (other than function bodies) are new block scopes.
72150 HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
72151 HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes";
72152 HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
72153 HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes";
72154 //
72155 // Subtree facts
72156 //
72157 HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget";
72158 HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis";
72159 //
72160 // Subtree masks
72161 //
72162 HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask";
72163 HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
72164 HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes";
72165 })(HierarchyFacts || (HierarchyFacts = {}));
72166 function transformES2015(context) {
72167 var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
72168 var compilerOptions = context.getCompilerOptions();
72169 var resolver = context.getEmitResolver();
72170 var previousOnSubstituteNode = context.onSubstituteNode;
72171 var previousOnEmitNode = context.onEmitNode;
72172 context.onEmitNode = onEmitNode;
72173 context.onSubstituteNode = onSubstituteNode;
72174 var currentSourceFile;
72175 var currentText;
72176 var hierarchyFacts;
72177 var taggedTemplateStringDeclarations;
72178 function recordTaggedTemplateString(temp) {
72179 taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
72180 }
72181 /**
72182 * Used to track if we are emitting body of the converted loop
72183 */
72184 var convertedLoopState;
72185 /**
72186 * Keeps track of whether substitutions have been enabled for specific cases.
72187 * They are persisted between each SourceFile transformation and should not
72188 * be reset.
72189 */
72190 var enabledSubstitutions;
72191 return ts.chainBundle(transformSourceFile);
72192 function transformSourceFile(node) {
72193 if (node.isDeclarationFile) {
72194 return node;
72195 }
72196 currentSourceFile = node;
72197 currentText = node.text;
72198 var visited = visitSourceFile(node);
72199 ts.addEmitHelpers(visited, context.readEmitHelpers());
72200 currentSourceFile = undefined;
72201 currentText = undefined;
72202 taggedTemplateStringDeclarations = undefined;
72203 hierarchyFacts = 0 /* None */;
72204 return visited;
72205 }
72206 /**
72207 * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
72208 * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
72209 * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
72210 */
72211 function enterSubtree(excludeFacts, includeFacts) {
72212 var ancestorFacts = hierarchyFacts;
72213 hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */;
72214 return ancestorFacts;
72215 }
72216 /**
72217 * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
72218 * subtree, propagating specific facts from the subtree.
72219 * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
72220 * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
72221 * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
72222 */
72223 function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
72224 hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts;
72225 }
72226 function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
72227 return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0
72228 && node.kind === 230 /* ReturnStatement */
72229 && !node.expression;
72230 }
72231 function shouldVisitNode(node) {
72232 return (node.transformFlags & 128 /* ContainsES2015 */) !== 0
72233 || convertedLoopState !== undefined
72234 || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 218 /* Block */)))
72235 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
72236 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
72237 }
72238 function visitor(node) {
72239 if (shouldVisitNode(node)) {
72240 return visitJavaScript(node);
72241 }
72242 else {
72243 return node;
72244 }
72245 }
72246 function callExpressionVisitor(node) {
72247 if (node.kind === 98 /* SuperKeyword */) {
72248 return visitSuperKeyword(/*isExpressionOfCall*/ true);
72249 }
72250 return visitor(node);
72251 }
72252 function visitJavaScript(node) {
72253 switch (node.kind) {
72254 case 116 /* StaticKeyword */:
72255 return undefined; // elide static keyword
72256 case 240 /* ClassDeclaration */:
72257 return visitClassDeclaration(node);
72258 case 209 /* ClassExpression */:
72259 return visitClassExpression(node);
72260 case 151 /* Parameter */:
72261 return visitParameter(node);
72262 case 239 /* FunctionDeclaration */:
72263 return visitFunctionDeclaration(node);
72264 case 197 /* ArrowFunction */:
72265 return visitArrowFunction(node);
72266 case 196 /* FunctionExpression */:
72267 return visitFunctionExpression(node);
72268 case 237 /* VariableDeclaration */:
72269 return visitVariableDeclaration(node);
72270 case 72 /* Identifier */:
72271 return visitIdentifier(node);
72272 case 238 /* VariableDeclarationList */:
72273 return visitVariableDeclarationList(node);
72274 case 232 /* SwitchStatement */:
72275 return visitSwitchStatement(node);
72276 case 246 /* CaseBlock */:
72277 return visitCaseBlock(node);
72278 case 218 /* Block */:
72279 return visitBlock(node, /*isFunctionBody*/ false);
72280 case 229 /* BreakStatement */:
72281 case 228 /* ContinueStatement */:
72282 return visitBreakOrContinueStatement(node);
72283 case 233 /* LabeledStatement */:
72284 return visitLabeledStatement(node);
72285 case 223 /* DoStatement */:
72286 case 224 /* WhileStatement */:
72287 return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
72288 case 225 /* ForStatement */:
72289 return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
72290 case 226 /* ForInStatement */:
72291 return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
72292 case 227 /* ForOfStatement */:
72293 return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
72294 case 221 /* ExpressionStatement */:
72295 return visitExpressionStatement(node);
72296 case 188 /* ObjectLiteralExpression */:
72297 return visitObjectLiteralExpression(node);
72298 case 274 /* CatchClause */:
72299 return visitCatchClause(node);
72300 case 276 /* ShorthandPropertyAssignment */:
72301 return visitShorthandPropertyAssignment(node);
72302 case 149 /* ComputedPropertyName */:
72303 return visitComputedPropertyName(node);
72304 case 187 /* ArrayLiteralExpression */:
72305 return visitArrayLiteralExpression(node);
72306 case 191 /* CallExpression */:
72307 return visitCallExpression(node);
72308 case 192 /* NewExpression */:
72309 return visitNewExpression(node);
72310 case 195 /* ParenthesizedExpression */:
72311 return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
72312 case 204 /* BinaryExpression */:
72313 return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
72314 case 14 /* NoSubstitutionTemplateLiteral */:
72315 case 15 /* TemplateHead */:
72316 case 16 /* TemplateMiddle */:
72317 case 17 /* TemplateTail */:
72318 return visitTemplateLiteral(node);
72319 case 10 /* StringLiteral */:
72320 return visitStringLiteral(node);
72321 case 8 /* NumericLiteral */:
72322 return visitNumericLiteral(node);
72323 case 193 /* TaggedTemplateExpression */:
72324 return visitTaggedTemplateExpression(node);
72325 case 206 /* TemplateExpression */:
72326 return visitTemplateExpression(node);
72327 case 207 /* YieldExpression */:
72328 return visitYieldExpression(node);
72329 case 208 /* SpreadElement */:
72330 return visitSpreadElement(node);
72331 case 98 /* SuperKeyword */:
72332 return visitSuperKeyword(/*isExpressionOfCall*/ false);
72333 case 100 /* ThisKeyword */:
72334 return visitThisKeyword(node);
72335 case 214 /* MetaProperty */:
72336 return visitMetaProperty(node);
72337 case 156 /* MethodDeclaration */:
72338 return visitMethodDeclaration(node);
72339 case 158 /* GetAccessor */:
72340 case 159 /* SetAccessor */:
72341 return visitAccessorDeclaration(node);
72342 case 219 /* VariableStatement */:
72343 return visitVariableStatement(node);
72344 case 230 /* ReturnStatement */:
72345 return visitReturnStatement(node);
72346 default:
72347 return ts.visitEachChild(node, visitor, context);
72348 }
72349 }
72350 function visitSourceFile(node) {
72351 var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
72352 var prologue = [];
72353 var statements = [];
72354 startLexicalEnvironment();
72355 var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
72356 statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
72357 ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
72358 if (taggedTemplateStringDeclarations) {
72359 statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
72360 }
72361 ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
72362 insertCaptureThisForNodeIfNeeded(prologue, node);
72363 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
72364 return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
72365 }
72366 function visitSwitchStatement(node) {
72367 if (convertedLoopState !== undefined) {
72368 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
72369 // for switch statement allow only non-labeled break
72370 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
72371 var result = ts.visitEachChild(node, visitor, context);
72372 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
72373 return result;
72374 }
72375 return ts.visitEachChild(node, visitor, context);
72376 }
72377 function visitCaseBlock(node) {
72378 var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
72379 var updated = ts.visitEachChild(node, visitor, context);
72380 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
72381 return updated;
72382 }
72383 function returnCapturedThis(node) {
72384 return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node);
72385 }
72386 function visitReturnStatement(node) {
72387 if (convertedLoopState) {
72388 convertedLoopState.nonLocalJumps |= 8 /* Return */;
72389 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
72390 node = returnCapturedThis(node);
72391 }
72392 return ts.createReturn(ts.createObjectLiteral([
72393 ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
72394 ? ts.visitNode(node.expression, visitor, ts.isExpression)
72395 : ts.createVoidZero())
72396 ]));
72397 }
72398 else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
72399 return returnCapturedThis(node);
72400 }
72401 return ts.visitEachChild(node, visitor, context);
72402 }
72403 function visitThisKeyword(node) {
72404 if (hierarchyFacts & 2 /* ArrowFunction */) {
72405 hierarchyFacts |= 16384 /* CapturedLexicalThis */;
72406 }
72407 if (convertedLoopState) {
72408 if (hierarchyFacts & 2 /* ArrowFunction */) {
72409 // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
72410 convertedLoopState.containsLexicalThis = true;
72411 return node;
72412 }
72413 return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
72414 }
72415 return node;
72416 }
72417 function visitIdentifier(node) {
72418 if (!convertedLoopState) {
72419 return node;
72420 }
72421 if (ts.isGeneratedIdentifier(node)) {
72422 return node;
72423 }
72424 if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
72425 return node;
72426 }
72427 return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments"));
72428 }
72429 function visitBreakOrContinueStatement(node) {
72430 if (convertedLoopState) {
72431 // check if we can emit break/continue as is
72432 // it is possible if either
72433 // - break/continue is labeled and label is located inside the converted loop
72434 // - break/continue is non-labeled and located in non-converted loop/switch statement
72435 var jump = node.kind === 229 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
72436 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
72437 (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
72438 if (!canUseBreakOrContinue) {
72439 var labelMarker = void 0;
72440 var label = node.label;
72441 if (!label) {
72442 if (node.kind === 229 /* BreakStatement */) {
72443 convertedLoopState.nonLocalJumps |= 2 /* Break */;
72444 labelMarker = "break";
72445 }
72446 else {
72447 convertedLoopState.nonLocalJumps |= 4 /* Continue */;
72448 // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
72449 labelMarker = "continue";
72450 }
72451 }
72452 else {
72453 if (node.kind === 229 /* BreakStatement */) {
72454 labelMarker = "break-" + label.escapedText;
72455 setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
72456 }
72457 else {
72458 labelMarker = "continue-" + label.escapedText;
72459 setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
72460 }
72461 }
72462 var returnExpression = ts.createLiteral(labelMarker);
72463 if (convertedLoopState.loopOutParameters.length) {
72464 var outParams = convertedLoopState.loopOutParameters;
72465 var expr = void 0;
72466 for (var i = 0; i < outParams.length; i++) {
72467 var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
72468 if (i === 0) {
72469 expr = copyExpr;
72470 }
72471 else {
72472 expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr);
72473 }
72474 }
72475 returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression);
72476 }
72477 return ts.createReturn(returnExpression);
72478 }
72479 }
72480 return ts.visitEachChild(node, visitor, context);
72481 }
72482 /**
72483 * Visits a ClassDeclaration and transforms it into a variable statement.
72484 *
72485 * @param node A ClassDeclaration node.
72486 */
72487 function visitClassDeclaration(node) {
72488 // [source]
72489 // class C { }
72490 //
72491 // [output]
72492 // var C = (function () {
72493 // function C() {
72494 // }
72495 // return C;
72496 // }());
72497 var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true),
72498 /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
72499 ts.setOriginalNode(variable, node);
72500 var statements = [];
72501 var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]));
72502 ts.setOriginalNode(statement, node);
72503 ts.setTextRange(statement, node);
72504 ts.startOnNewLine(statement);
72505 statements.push(statement);
72506 // Add an `export default` statement for default exports (for `--target es5 --module es6`)
72507 if (ts.hasModifier(node, 1 /* Export */)) {
72508 var exportStatement = ts.hasModifier(node, 512 /* Default */)
72509 ? ts.createExportDefault(ts.getLocalName(node))
72510 : ts.createExternalModuleExport(ts.getLocalName(node));
72511 ts.setOriginalNode(exportStatement, statement);
72512 statements.push(exportStatement);
72513 }
72514 var emitFlags = ts.getEmitFlags(node);
72515 if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
72516 // Add a DeclarationMarker as a marker for the end of the declaration
72517 statements.push(ts.createEndOfDeclarationMarker(node));
72518 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
72519 }
72520 return ts.singleOrMany(statements);
72521 }
72522 /**
72523 * Visits a ClassExpression and transforms it into an expression.
72524 *
72525 * @param node A ClassExpression node.
72526 */
72527 function visitClassExpression(node) {
72528 // [source]
72529 // C = class { }
72530 //
72531 // [output]
72532 // C = (function () {
72533 // function class_1() {
72534 // }
72535 // return class_1;
72536 // }())
72537 return transformClassLikeDeclarationToExpression(node);
72538 }
72539 /**
72540 * Transforms a ClassExpression or ClassDeclaration into an expression.
72541 *
72542 * @param node A ClassExpression or ClassDeclaration node.
72543 */
72544 function transformClassLikeDeclarationToExpression(node) {
72545 // [source]
72546 // class C extends D {
72547 // constructor() {}
72548 // method() {}
72549 // get prop() {}
72550 // set prop(v) {}
72551 // }
72552 //
72553 // [output]
72554 // (function (_super) {
72555 // __extends(C, _super);
72556 // function C() {
72557 // }
72558 // C.prototype.method = function () {}
72559 // Object.defineProperty(C.prototype, "prop", {
72560 // get: function() {},
72561 // set: function() {},
72562 // enumerable: true,
72563 // configurable: true
72564 // });
72565 // return C;
72566 // }(D))
72567 if (node.name) {
72568 enableSubstitutionsForBlockScopedBindings();
72569 }
72570 var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
72571 var classFunction = ts.createFunctionExpression(
72572 /*modifiers*/ undefined,
72573 /*asteriskToken*/ undefined,
72574 /*name*/ undefined,
72575 /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [],
72576 /*type*/ undefined, transformClassBody(node, extendsClauseElement));
72577 // To preserve the behavior of the old emitter, we explicitly indent
72578 // the body of the function here if it was requested in an earlier
72579 // transformation.
72580 ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
72581 // "inner" and "outer" below are added purely to preserve source map locations from
72582 // the old emitter
72583 var inner = ts.createPartiallyEmittedExpression(classFunction);
72584 inner.end = node.end;
72585 ts.setEmitFlags(inner, 1536 /* NoComments */);
72586 var outer = ts.createPartiallyEmittedExpression(inner);
72587 outer.end = ts.skipTrivia(currentText, node.pos);
72588 ts.setEmitFlags(outer, 1536 /* NoComments */);
72589 var result = ts.createParen(ts.createCall(outer,
72590 /*typeArguments*/ undefined, extendsClauseElement
72591 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
72592 : []));
72593 ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
72594 return result;
72595 }
72596 /**
72597 * Transforms a ClassExpression or ClassDeclaration into a function body.
72598 *
72599 * @param node A ClassExpression or ClassDeclaration node.
72600 * @param extendsClauseElement The expression for the class `extends` clause.
72601 */
72602 function transformClassBody(node, extendsClauseElement) {
72603 var statements = [];
72604 startLexicalEnvironment();
72605 addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
72606 addConstructor(statements, node, extendsClauseElement);
72607 addClassMembers(statements, node);
72608 // Create a synthetic text range for the return statement.
72609 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
72610 var localName = ts.getInternalName(node);
72611 // The following partially-emitted expression exists purely to align our sourcemap
72612 // emit with the original emitter.
72613 var outer = ts.createPartiallyEmittedExpression(localName);
72614 outer.end = closingBraceLocation.end;
72615 ts.setEmitFlags(outer, 1536 /* NoComments */);
72616 var statement = ts.createReturn(outer);
72617 statement.pos = closingBraceLocation.pos;
72618 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
72619 statements.push(statement);
72620 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
72621 var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
72622 ts.setEmitFlags(block, 1536 /* NoComments */);
72623 return block;
72624 }
72625 /**
72626 * Adds a call to the `__extends` helper if needed for a class.
72627 *
72628 * @param statements The statements of the class body function.
72629 * @param node The ClassExpression or ClassDeclaration node.
72630 * @param extendsClauseElement The expression for the class `extends` clause.
72631 */
72632 function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
72633 if (extendsClauseElement) {
72634 statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))),
72635 /*location*/ extendsClauseElement));
72636 }
72637 }
72638 /**
72639 * Adds the constructor of the class to a class body function.
72640 *
72641 * @param statements The statements of the class body function.
72642 * @param node The ClassExpression or ClassDeclaration node.
72643 * @param extendsClauseElement The expression for the class `extends` clause.
72644 */
72645 function addConstructor(statements, node, extendsClauseElement) {
72646 var savedConvertedLoopState = convertedLoopState;
72647 convertedLoopState = undefined;
72648 var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
72649 var constructor = ts.getFirstConstructorWithBody(node);
72650 var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
72651 var constructorFunction = ts.createFunctionDeclaration(
72652 /*decorators*/ undefined,
72653 /*modifiers*/ undefined,
72654 /*asteriskToken*/ undefined, ts.getInternalName(node),
72655 /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper),
72656 /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
72657 ts.setTextRange(constructorFunction, constructor || node);
72658 if (extendsClauseElement) {
72659 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
72660 }
72661 statements.push(constructorFunction);
72662 exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
72663 convertedLoopState = savedConvertedLoopState;
72664 }
72665 /**
72666 * Transforms the parameters of the constructor declaration of a class.
72667 *
72668 * @param constructor The constructor for the class.
72669 * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
72670 * synthesized `super` call.
72671 */
72672 function transformConstructorParameters(constructor, hasSynthesizedSuper) {
72673 // If the TypeScript transformer needed to synthesize a constructor for property
72674 // initializers, it would have also added a synthetic `...args` parameter and
72675 // `super` call.
72676 // If this is the case, we do not include the synthetic `...args` parameter and
72677 // will instead use the `arguments` object in ES5/3.
72678 return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
72679 || [];
72680 }
72681 function createDefaultConstructorBody(node, isDerivedClass) {
72682 // We must be here because the user didn't write a constructor
72683 // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
72684 // If that's the case we can just immediately return the result of a 'super()' call.
72685 var statements = [];
72686 resumeLexicalEnvironment();
72687 ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
72688 if (isDerivedClass) {
72689 // return _super !== null && _super.apply(this, arguments) || this;
72690 statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
72691 }
72692 var statementsArray = ts.createNodeArray(statements);
72693 ts.setTextRange(statementsArray, node.members);
72694 var block = ts.createBlock(statementsArray, /*multiLine*/ true);
72695 ts.setTextRange(block, node);
72696 ts.setEmitFlags(block, 1536 /* NoComments */);
72697 return block;
72698 }
72699 /**
72700 * Transforms the body of a constructor declaration of a class.
72701 *
72702 * @param constructor The constructor for the class.
72703 * @param node The node which contains the constructor.
72704 * @param extendsClauseElement The expression for the class `extends` clause.
72705 * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
72706 * synthesized `super` call.
72707 */
72708 function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
72709 // determine whether the class is known syntactically to be a derived class (e.g. a
72710 // class that extends a value that is not syntactically known to be `null`).
72711 var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
72712 // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
72713 // representation:
72714 //
72715 // ```
72716 // // es2015 (source)
72717 // class C extends Base { }
72718 //
72719 // // es5 (transformed)
72720 // var C = (function (_super) {
72721 // function C() {
72722 // return _super.apply(this, arguments) || this;
72723 // }
72724 // return C;
72725 // })(Base);
72726 // ```
72727 if (!constructor)
72728 return createDefaultConstructorBody(node, isDerivedClass);
72729 // The prologue will contain all leading standard and custom prologue statements added by this transform
72730 var prologue = [];
72731 var statements = [];
72732 resumeLexicalEnvironment();
72733 // If a super call has already been synthesized,
72734 // we're going to assume that we should just transform everything after that.
72735 // The assumption is that no prior step in the pipeline has added any prologue directives.
72736 var statementOffset = 0;
72737 if (!hasSynthesizedSuper)
72738 statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
72739 addDefaultValueAssignmentsIfNeeded(statements, constructor);
72740 addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
72741 if (!hasSynthesizedSuper)
72742 statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
72743 // If the first statement is a call to `super()`, visit the statement directly
72744 var superCallExpression;
72745 if (hasSynthesizedSuper) {
72746 superCallExpression = createDefaultSuperCallOrThis();
72747 }
72748 else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
72749 var firstStatement = constructor.body.statements[statementOffset];
72750 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
72751 superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
72752 }
72753 }
72754 if (superCallExpression) {
72755 hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */;
72756 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
72757 }
72758 // visit the remaining statements
72759 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
72760 ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
72761 insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
72762 if (isDerivedClass) {
72763 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) {
72764 // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
72765 // following representation:
72766 //
72767 // ```
72768 // // es2015 (source)
72769 // class C extends Base {
72770 // constructor() {
72771 // super("foo");
72772 // }
72773 // }
72774 //
72775 // // es5 (transformed)
72776 // var C = (function (_super) {
72777 // function C() {
72778 // return _super.call(this, "foo") || this;
72779 // }
72780 // return C;
72781 // })(Base);
72782 // ```
72783 var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
72784 var returnStatement = ts.createReturn(superCallExpression);
72785 ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
72786 ts.setEmitFlags(superCall, 1536 /* NoComments */);
72787 statements.push(returnStatement);
72788 }
72789 else {
72790 // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
72791 //
72792 // ```
72793 // // es2015 (source)
72794 // class C extends Base {
72795 // constructor() {
72796 // super("foo");
72797 // this.x = 1;
72798 // }
72799 // }
72800 //
72801 // // es5 (transformed)
72802 // var C = (function (_super) {
72803 // function C() {
72804 // var _this = _super.call(this, "foo") || this;
72805 // _this.x = 1;
72806 // return _this;
72807 // }
72808 // return C;
72809 // })(Base);
72810 // ```
72811 // Since the `super()` call was the first statement, we insert the `this` capturing call to
72812 // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
72813 insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
72814 if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
72815 statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
72816 }
72817 }
72818 }
72819 else {
72820 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
72821 // captured when necessitated by an arrow function capturing the lexical `this`:
72822 //
72823 // ```
72824 // // es2015
72825 // class C {}
72826 //
72827 // // es5
72828 // var C = (function () {
72829 // function C() {
72830 // }
72831 // return C;
72832 // })();
72833 // ```
72834 insertCaptureThisForNodeIfNeeded(prologue, constructor);
72835 }
72836 var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)),
72837 /*location*/ constructor.body.statements),
72838 /*multiLine*/ true);
72839 ts.setTextRange(block, constructor.body);
72840 return block;
72841 }
72842 /**
72843 * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
72844 * It would generate obviously dead code, so we'll try to make things a little bit prettier
72845 * by doing a minimal check on whether some common patterns always explicitly return.
72846 */
72847 function isSufficientlyCoveredByReturnStatements(statement) {
72848 // A return statement is considered covered.
72849 if (statement.kind === 230 /* ReturnStatement */) {
72850 return true;
72851 }
72852 // An if-statement with two covered branches is covered.
72853 else if (statement.kind === 222 /* IfStatement */) {
72854 var ifStatement = statement;
72855 if (ifStatement.elseStatement) {
72856 return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
72857 isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
72858 }
72859 }
72860 // A block is covered if it has a last statement which is covered.
72861 else if (statement.kind === 218 /* Block */) {
72862 var lastStatement = ts.lastOrUndefined(statement.statements);
72863 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
72864 return true;
72865 }
72866 }
72867 return false;
72868 }
72869 function createActualThis() {
72870 return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
72871 }
72872 function createDefaultSuperCallOrThis() {
72873 return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis());
72874 }
72875 /**
72876 * Visits a parameter declaration.
72877 *
72878 * @param node A ParameterDeclaration node.
72879 */
72880 function visitParameter(node) {
72881 if (node.dotDotDotToken) {
72882 // rest parameters are elided
72883 return undefined;
72884 }
72885 else if (ts.isBindingPattern(node.name)) {
72886 // Binding patterns are converted into a generated name and are
72887 // evaluated inside the function body.
72888 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
72889 /*decorators*/ undefined,
72890 /*modifiers*/ undefined,
72891 /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node),
72892 /*questionToken*/ undefined,
72893 /*type*/ undefined,
72894 /*initializer*/ undefined),
72895 /*location*/ node),
72896 /*original*/ node);
72897 }
72898 else if (node.initializer) {
72899 // Initializers are elided
72900 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
72901 /*decorators*/ undefined,
72902 /*modifiers*/ undefined,
72903 /*dotDotDotToken*/ undefined, node.name,
72904 /*questionToken*/ undefined,
72905 /*type*/ undefined,
72906 /*initializer*/ undefined),
72907 /*location*/ node),
72908 /*original*/ node);
72909 }
72910 else {
72911 return node;
72912 }
72913 }
72914 function hasDefaultValueOrBindingPattern(node) {
72915 return node.initializer !== undefined
72916 || ts.isBindingPattern(node.name);
72917 }
72918 /**
72919 * Adds statements to the body of a function-like node if it contains parameters with
72920 * binding patterns or initializers.
72921 *
72922 * @param statements The statements for the new function body.
72923 * @param node A function-like node.
72924 */
72925 function addDefaultValueAssignmentsIfNeeded(statements, node) {
72926 if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
72927 return false;
72928 }
72929 var added = false;
72930 for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
72931 var parameter = _a[_i];
72932 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
72933 // A rest parameter cannot have a binding pattern or an initializer,
72934 // so let's just ignore it.
72935 if (dotDotDotToken) {
72936 continue;
72937 }
72938 if (ts.isBindingPattern(name)) {
72939 added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
72940 }
72941 else if (initializer) {
72942 insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
72943 added = true;
72944 }
72945 }
72946 return added;
72947 }
72948 /**
72949 * Adds statements to the body of a function-like node for parameters with binding patterns
72950 *
72951 * @param statements The statements for the new function body.
72952 * @param parameter The parameter for the function.
72953 * @param name The name of the parameter.
72954 * @param initializer The initializer for the parameter.
72955 */
72956 function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
72957 // In cases where a binding pattern is simply '[]' or '{}',
72958 // we usually don't want to emit a var declaration; however, in the presence
72959 // of an initializer, we must emit that expression to preserve side effects.
72960 if (name.elements.length > 0) {
72961 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
72962 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
72963 return true;
72964 }
72965 else if (initializer) {
72966 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
72967 return true;
72968 }
72969 return false;
72970 }
72971 /**
72972 * Adds statements to the body of a function-like node for parameters with initializers.
72973 *
72974 * @param statements The statements for the new function body.
72975 * @param parameter The parameter for the function.
72976 * @param name The name of the parameter.
72977 * @param initializer The initializer for the parameter.
72978 */
72979 function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
72980 initializer = ts.visitNode(initializer, visitor, ts.isExpression);
72981 var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
72982 ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
72983 ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
72984 ts.startOnNewLine(statement);
72985 ts.setTextRange(statement, parameter);
72986 ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
72987 ts.insertStatementAfterCustomPrologue(statements, statement);
72988 }
72989 /**
72990 * Gets a value indicating whether we need to add statements to handle a rest parameter.
72991 *
72992 * @param node A ParameterDeclaration node.
72993 * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
72994 * part of a constructor declaration with a
72995 * synthesized call to `super`
72996 */
72997 function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
72998 return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
72999 }
73000 /**
73001 * Adds statements to the body of a function-like node if it contains a rest parameter.
73002 *
73003 * @param statements The statements for the new function body.
73004 * @param node A function-like node.
73005 * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
73006 * part of a constructor declaration with a
73007 * synthesized call to `super`
73008 */
73009 function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
73010 var prologueStatements = [];
73011 var parameter = ts.lastOrUndefined(node.parameters);
73012 if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
73013 return false;
73014 }
73015 // `declarationName` is the name of the local declaration for the parameter.
73016 var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
73017 ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
73018 // `expressionName` is the name of the parameter used in expressions.
73019 var expressionName = parameter.name.kind === 72 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName;
73020 var restIndex = node.parameters.length - 1;
73021 var temp = ts.createLoopVariable();
73022 // var param = [];
73023 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
73024 /*modifiers*/ undefined, ts.createVariableDeclarationList([
73025 ts.createVariableDeclaration(declarationName,
73026 /*type*/ undefined, ts.createArrayLiteral([]))
73027 ])),
73028 /*location*/ parameter), 1048576 /* CustomPrologue */));
73029 // for (var _i = restIndex; _i < arguments.length; _i++) {
73030 // param[_i - restIndex] = arguments[_i];
73031 // }
73032 var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
73033 ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex))
73034 ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([
73035 ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
73036 ? temp
73037 : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))),
73038 /*location*/ parameter))
73039 ]));
73040 ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
73041 ts.startOnNewLine(forStatement);
73042 prologueStatements.push(forStatement);
73043 if (parameter.name.kind !== 72 /* Identifier */) {
73044 // do the actual destructuring of the rest parameter if necessary
73045 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
73046 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
73047 }
73048 ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
73049 return true;
73050 }
73051 /**
73052 * Adds a statement to capture the `this` of a function declaration if it is needed.
73053 * NOTE: This must be executed *after* the subtree has been visited.
73054 *
73055 * @param statements The statements for the new function body.
73056 * @param node A node.
73057 */
73058 function insertCaptureThisForNodeIfNeeded(statements, node) {
73059 if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
73060 insertCaptureThisForNode(statements, node, ts.createThis());
73061 return true;
73062 }
73063 return false;
73064 }
73065 function insertCaptureThisForNode(statements, node, initializer) {
73066 enableSubstitutionsForCapturedThis();
73067 var captureThisStatement = ts.createVariableStatement(
73068 /*modifiers*/ undefined, ts.createVariableDeclarationList([
73069 ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"),
73070 /*type*/ undefined, initializer)
73071 ]));
73072 ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
73073 ts.setSourceMapRange(captureThisStatement, node);
73074 ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
73075 }
73076 function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
73077 if (hierarchyFacts & 8192 /* NewTarget */) {
73078 var newTarget = void 0;
73079 switch (node.kind) {
73080 case 197 /* ArrowFunction */:
73081 return statements;
73082 case 156 /* MethodDeclaration */:
73083 case 158 /* GetAccessor */:
73084 case 159 /* SetAccessor */:
73085 // Methods and accessors cannot be constructors, so 'new.target' will
73086 // always return 'undefined'.
73087 newTarget = ts.createVoidZero();
73088 break;
73089 case 157 /* Constructor */:
73090 // Class constructors can only be called with `new`, so `this.constructor`
73091 // should be relatively safe to use.
73092 newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor");
73093 break;
73094 case 239 /* FunctionDeclaration */:
73095 case 196 /* FunctionExpression */:
73096 // Functions can be called or constructed, and may have a `this` due to
73097 // being a member or when calling an imported function via `other_1.f()`.
73098 newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 94 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero());
73099 break;
73100 default:
73101 return ts.Debug.failBadSyntaxKind(node);
73102 }
73103 var captureNewTargetStatement = ts.createVariableStatement(
73104 /*modifiers*/ undefined, ts.createVariableDeclarationList([
73105 ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"),
73106 /*type*/ undefined, newTarget)
73107 ]));
73108 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
73109 if (copyOnWrite) {
73110 statements = statements.slice();
73111 }
73112 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
73113 }
73114 return statements;
73115 }
73116 /**
73117 * Adds statements to the class body function for a class to define the members of the
73118 * class.
73119 *
73120 * @param statements The statements for the class body function.
73121 * @param node The ClassExpression or ClassDeclaration node.
73122 */
73123 function addClassMembers(statements, node) {
73124 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
73125 var member = _a[_i];
73126 switch (member.kind) {
73127 case 217 /* SemicolonClassElement */:
73128 statements.push(transformSemicolonClassElementToStatement(member));
73129 break;
73130 case 156 /* MethodDeclaration */:
73131 statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
73132 break;
73133 case 158 /* GetAccessor */:
73134 case 159 /* SetAccessor */:
73135 var accessors = ts.getAllAccessorDeclarations(node.members, member);
73136 if (member === accessors.firstAccessor) {
73137 statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
73138 }
73139 break;
73140 case 157 /* Constructor */:
73141 // Constructors are handled in visitClassExpression/visitClassDeclaration
73142 break;
73143 default:
73144 ts.Debug.failBadSyntaxKind(node);
73145 break;
73146 }
73147 }
73148 }
73149 /**
73150 * Transforms a SemicolonClassElement into a statement for a class body function.
73151 *
73152 * @param member The SemicolonClassElement node.
73153 */
73154 function transformSemicolonClassElementToStatement(member) {
73155 return ts.setTextRange(ts.createEmptyStatement(), member);
73156 }
73157 /**
73158 * Transforms a MethodDeclaration into a statement for a class body function.
73159 *
73160 * @param receiver The receiver for the member.
73161 * @param member The MethodDeclaration node.
73162 */
73163 function transformClassMethodDeclarationToStatement(receiver, member, container) {
73164 var commentRange = ts.getCommentRange(member);
73165 var sourceMapRange = ts.getSourceMapRange(member);
73166 var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name);
73167 var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
73168 ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
73169 ts.setSourceMapRange(memberFunction, sourceMapRange);
73170 var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)),
73171 /*location*/ member);
73172 ts.setOriginalNode(statement, member);
73173 ts.setCommentRange(statement, commentRange);
73174 // The location for the statement is used to emit comments only.
73175 // No source map should be emitted for this statement to align with the
73176 // old emitter.
73177 ts.setEmitFlags(statement, 48 /* NoSourceMap */);
73178 return statement;
73179 }
73180 /**
73181 * Transforms a set of related of get/set accessors into a statement for a class body function.
73182 *
73183 * @param receiver The receiver for the member.
73184 * @param accessors The set of related get/set accessors.
73185 */
73186 function transformAccessorsToStatement(receiver, accessors, container) {
73187 var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
73188 // The location for the statement is used to emit source maps only.
73189 // No comments should be emitted for this statement to align with the
73190 // old emitter.
73191 ts.setEmitFlags(statement, 1536 /* NoComments */);
73192 ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
73193 return statement;
73194 }
73195 /**
73196 * Transforms a set of related get/set accessors into an expression for either a class
73197 * body function or an ObjectLiteralExpression with computed properties.
73198 *
73199 * @param receiver The receiver for the member.
73200 */
73201 function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
73202 var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
73203 // To align with source maps in the old emitter, the receiver and property name
73204 // arguments are both mapped contiguously to the accessor name.
73205 var target = ts.getMutableClone(receiver);
73206 ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
73207 ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217
73208 var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName));
73209 ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
73210 ts.setSourceMapRange(propertyName, firstAccessor.name);
73211 var properties = [];
73212 if (getAccessor) {
73213 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
73214 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
73215 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
73216 var getter = ts.createPropertyAssignment("get", getterFunction);
73217 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
73218 properties.push(getter);
73219 }
73220 if (setAccessor) {
73221 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
73222 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
73223 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
73224 var setter = ts.createPropertyAssignment("set", setterFunction);
73225 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
73226 properties.push(setter);
73227 }
73228 properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue()));
73229 var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
73230 /*typeArguments*/ undefined, [
73231 target,
73232 propertyName,
73233 ts.createObjectLiteral(properties, /*multiLine*/ true)
73234 ]);
73235 if (startsOnNewLine) {
73236 ts.startOnNewLine(call);
73237 }
73238 return call;
73239 }
73240 /**
73241 * Visits an ArrowFunction and transforms it into a FunctionExpression.
73242 *
73243 * @param node An ArrowFunction node.
73244 */
73245 function visitArrowFunction(node) {
73246 if (node.transformFlags & 2048 /* ContainsLexicalThis */) {
73247 hierarchyFacts |= 16384 /* CapturedLexicalThis */;
73248 }
73249 var savedConvertedLoopState = convertedLoopState;
73250 convertedLoopState = undefined;
73251 var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
73252 var func = ts.createFunctionExpression(
73253 /*modifiers*/ undefined,
73254 /*asteriskToken*/ undefined,
73255 /*name*/ undefined,
73256 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
73257 /*type*/ undefined, transformFunctionBody(node));
73258 ts.setTextRange(func, node);
73259 ts.setOriginalNode(func, node);
73260 ts.setEmitFlags(func, 8 /* CapturesThis */);
73261 if (hierarchyFacts & 16384 /* CapturedLexicalThis */) {
73262 enableSubstitutionsForCapturedThis();
73263 }
73264 // If an arrow function contains
73265 exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
73266 convertedLoopState = savedConvertedLoopState;
73267 return func;
73268 }
73269 /**
73270 * Visits a FunctionExpression node.
73271 *
73272 * @param node a FunctionExpression node.
73273 */
73274 function visitFunctionExpression(node) {
73275 var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
73276 ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
73277 : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
73278 var savedConvertedLoopState = convertedLoopState;
73279 convertedLoopState = undefined;
73280 var parameters = ts.visitParameterList(node.parameters, visitor, context);
73281 var body = transformFunctionBody(node);
73282 var name = hierarchyFacts & 8192 /* NewTarget */
73283 ? ts.getLocalName(node)
73284 : node.name;
73285 exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
73286 convertedLoopState = savedConvertedLoopState;
73287 return ts.updateFunctionExpression(node,
73288 /*modifiers*/ undefined, node.asteriskToken, name,
73289 /*typeParameters*/ undefined, parameters,
73290 /*type*/ undefined, body);
73291 }
73292 /**
73293 * Visits a FunctionDeclaration node.
73294 *
73295 * @param node a FunctionDeclaration node.
73296 */
73297 function visitFunctionDeclaration(node) {
73298 var savedConvertedLoopState = convertedLoopState;
73299 convertedLoopState = undefined;
73300 var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
73301 var parameters = ts.visitParameterList(node.parameters, visitor, context);
73302 var body = transformFunctionBody(node);
73303 var name = hierarchyFacts & 8192 /* NewTarget */
73304 ? ts.getLocalName(node)
73305 : node.name;
73306 exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
73307 convertedLoopState = savedConvertedLoopState;
73308 return ts.updateFunctionDeclaration(node,
73309 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name,
73310 /*typeParameters*/ undefined, parameters,
73311 /*type*/ undefined, body);
73312 }
73313 /**
73314 * Transforms a function-like node into a FunctionExpression.
73315 *
73316 * @param node The function-like node to transform.
73317 * @param location The source-map location for the new FunctionExpression.
73318 * @param name The name of the new FunctionExpression.
73319 */
73320 function transformFunctionLikeToExpression(node, location, name, container) {
73321 var savedConvertedLoopState = convertedLoopState;
73322 convertedLoopState = undefined;
73323 var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
73324 ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
73325 : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
73326 var parameters = ts.visitParameterList(node.parameters, visitor, context);
73327 var body = transformFunctionBody(node);
73328 if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
73329 name = ts.getGeneratedNameForNode(node);
73330 }
73331 exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
73332 convertedLoopState = savedConvertedLoopState;
73333 return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
73334 /*modifiers*/ undefined, node.asteriskToken, name,
73335 /*typeParameters*/ undefined, parameters,
73336 /*type*/ undefined, body), location),
73337 /*original*/ node);
73338 }
73339 /**
73340 * Transforms the body of a function-like node.
73341 *
73342 * @param node A function-like node.
73343 */
73344 function transformFunctionBody(node) {
73345 var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
73346 var singleLine = false; // indicates whether the block *may* be emitted as a single line
73347 var statementsLocation;
73348 var closeBraceLocation;
73349 var prologue = [];
73350 var statements = [];
73351 var body = node.body;
73352 var statementOffset;
73353 resumeLexicalEnvironment();
73354 if (ts.isBlock(body)) {
73355 // ensureUseStrict is false because no new prologue-directive should be added.
73356 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
73357 statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
73358 }
73359 multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
73360 multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
73361 if (ts.isBlock(body)) {
73362 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
73363 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
73364 statementsLocation = body.statements;
73365 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
73366 // If the original body was a multi-line block, this must be a multi-line block.
73367 if (!multiLine && body.multiLine) {
73368 multiLine = true;
73369 }
73370 }
73371 else {
73372 ts.Debug.assert(node.kind === 197 /* ArrowFunction */);
73373 // To align with the old emitter, we use a synthetic end position on the location
73374 // for the statement list we synthesize when we down-level an arrow function with
73375 // an expression function body. This prevents both comments and source maps from
73376 // being emitted for the end position only.
73377 statementsLocation = ts.moveRangeEnd(body, -1);
73378 var equalsGreaterThanToken = node.equalsGreaterThanToken;
73379 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
73380 if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
73381 singleLine = true;
73382 }
73383 else {
73384 multiLine = true;
73385 }
73386 }
73387 var expression = ts.visitNode(body, visitor, ts.isExpression);
73388 var returnStatement = ts.createReturn(expression);
73389 ts.setTextRange(returnStatement, body);
73390 ts.moveSyntheticComments(returnStatement, body);
73391 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
73392 statements.push(returnStatement);
73393 // To align with the source map emit for the old emitter, we set a custom
73394 // source map location for the close brace.
73395 closeBraceLocation = body;
73396 }
73397 ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
73398 insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
73399 insertCaptureThisForNodeIfNeeded(prologue, node);
73400 // If we added any final generated statements, this must be a multi-line block
73401 if (ts.some(prologue)) {
73402 multiLine = true;
73403 }
73404 statements.unshift.apply(statements, prologue);
73405 if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
73406 // no changes were made, preserve the tree
73407 return body;
73408 }
73409 var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
73410 ts.setTextRange(block, node.body);
73411 if (!multiLine && singleLine) {
73412 ts.setEmitFlags(block, 1 /* SingleLine */);
73413 }
73414 if (closeBraceLocation) {
73415 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
73416 }
73417 ts.setOriginalNode(block, node.body);
73418 return block;
73419 }
73420 function visitBlock(node, isFunctionBody) {
73421 if (isFunctionBody) {
73422 // A function body is not a block scope.
73423 return ts.visitEachChild(node, visitor, context);
73424 }
73425 var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
73426 ? enterSubtree(4032 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
73427 : enterSubtree(3904 /* BlockExcludes */, 128 /* BlockIncludes */);
73428 var updated = ts.visitEachChild(node, visitor, context);
73429 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
73430 return updated;
73431 }
73432 /**
73433 * Visits an ExpressionStatement that contains a destructuring assignment.
73434 *
73435 * @param node An ExpressionStatement node.
73436 */
73437 function visitExpressionStatement(node) {
73438 // If we are here it is most likely because our expression is a destructuring assignment.
73439 switch (node.expression.kind) {
73440 case 195 /* ParenthesizedExpression */:
73441 return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
73442 case 204 /* BinaryExpression */:
73443 return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
73444 }
73445 return ts.visitEachChild(node, visitor, context);
73446 }
73447 /**
73448 * Visits a ParenthesizedExpression that may contain a destructuring assignment.
73449 *
73450 * @param node A ParenthesizedExpression node.
73451 * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
73452 * of a destructuring assignment.
73453 */
73454 function visitParenthesizedExpression(node, needsDestructuringValue) {
73455 // If we are here it is most likely because our expression is a destructuring assignment.
73456 if (!needsDestructuringValue) {
73457 // By default we always emit the RHS at the end of a flattened destructuring
73458 // expression. If we are in a state where we do not need the destructuring value,
73459 // we pass that information along to the children that care about it.
73460 switch (node.expression.kind) {
73461 case 195 /* ParenthesizedExpression */:
73462 return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
73463 case 204 /* BinaryExpression */:
73464 return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
73465 }
73466 }
73467 return ts.visitEachChild(node, visitor, context);
73468 }
73469 /**
73470 * Visits a BinaryExpression that contains a destructuring assignment.
73471 *
73472 * @param node A BinaryExpression node.
73473 * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
73474 * of a destructuring assignment.
73475 */
73476 function visitBinaryExpression(node, needsDestructuringValue) {
73477 // If we are here it is because this is a destructuring assignment.
73478 if (ts.isDestructuringAssignment(node)) {
73479 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
73480 }
73481 return ts.visitEachChild(node, visitor, context);
73482 }
73483 function visitVariableStatement(node) {
73484 var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
73485 var updated;
73486 if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) {
73487 // we are inside a converted loop - hoist variable declarations
73488 var assignments = void 0;
73489 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
73490 var decl = _a[_i];
73491 hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
73492 if (decl.initializer) {
73493 var assignment = void 0;
73494 if (ts.isBindingPattern(decl.name)) {
73495 assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
73496 }
73497 else {
73498 assignment = ts.createBinary(decl.name, 59 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
73499 ts.setTextRange(assignment, decl);
73500 }
73501 assignments = ts.append(assignments, assignment);
73502 }
73503 }
73504 if (assignments) {
73505 updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node);
73506 }
73507 else {
73508 // none of declarations has initializer - the entire variable statement can be deleted
73509 updated = undefined;
73510 }
73511 }
73512 else {
73513 updated = ts.visitEachChild(node, visitor, context);
73514 }
73515 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
73516 return updated;
73517 }
73518 /**
73519 * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
73520 *
73521 * @param node A VariableDeclarationList node.
73522 */
73523 function visitVariableDeclarationList(node) {
73524 if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) {
73525 if (node.flags & 3 /* BlockScoped */) {
73526 enableSubstitutionsForBlockScopedBindings();
73527 }
73528 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
73529 ? visitVariableDeclarationInLetDeclarationList
73530 : visitVariableDeclaration);
73531 var declarationList = ts.createVariableDeclarationList(declarations);
73532 ts.setOriginalNode(declarationList, node);
73533 ts.setTextRange(declarationList, node);
73534 ts.setCommentRange(declarationList, node);
73535 // If the first or last declaration is a binding pattern, we need to modify
73536 // the source map range for the declaration list.
73537 if (node.transformFlags & 65536 /* ContainsBindingPattern */
73538 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
73539 ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
73540 }
73541 return declarationList;
73542 }
73543 return ts.visitEachChild(node, visitor, context);
73544 }
73545 function getRangeUnion(declarations) {
73546 // declarations may not be sorted by position.
73547 // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
73548 var pos = -1, end = -1;
73549 for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
73550 var node = declarations_10[_i];
73551 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
73552 end = Math.max(end, node.end);
73553 }
73554 return ts.createRange(pos, end);
73555 }
73556 /**
73557 * Gets a value indicating whether we should emit an explicit initializer for a variable
73558 * declaration in a `let` declaration list.
73559 *
73560 * @param node A VariableDeclaration node.
73561 */
73562 function shouldEmitExplicitInitializerForLetDeclaration(node) {
73563 // Nested let bindings might need to be initialized explicitly to preserve
73564 // ES6 semantic:
73565 //
73566 // { let x = 1; }
73567 // { let x; } // x here should be undefined. not 1
73568 //
73569 // Top level bindings never collide with anything and thus don't require
73570 // explicit initialization. As for nested let bindings there are two cases:
73571 //
73572 // - Nested let bindings that were not renamed definitely should be
73573 // initialized explicitly:
73574 //
73575 // { let x = 1; }
73576 // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
73577 //
73578 // Without explicit initialization code in /*1*/ can be executed even if
73579 // some-condition is evaluated to false.
73580 //
73581 // - Renaming introduces fresh name that should not collide with any
73582 // existing names, however renamed bindings sometimes also should be
73583 // explicitly initialized. One particular case: non-captured binding
73584 // declared inside loop body (but not in loop initializer):
73585 //
73586 // let x;
73587 // for (;;) {
73588 // let x;
73589 // }
73590 //
73591 // In downlevel codegen inner 'x' will be renamed so it won't collide
73592 // with outer 'x' however it will should be reset on every iteration as
73593 // if it was declared anew.
73594 //
73595 // * Why non-captured binding?
73596 // - Because if loop contains block scoped binding captured in some
73597 // function then loop body will be rewritten to have a fresh scope
73598 // on every iteration so everything will just work.
73599 //
73600 // * Why loop initializer is excluded?
73601 // - Since we've introduced a fresh name it already will be undefined.
73602 var flags = resolver.getNodeCheckFlags(node);
73603 var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
73604 var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
73605 var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
73606 || (isCapturedInFunction
73607 && isDeclaredInLoop
73608 && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
73609 var emitExplicitInitializer = !emittedAsTopLevel
73610 && (hierarchyFacts & 2048 /* ForInOrForOfStatement */) === 0
73611 && (!resolver.isDeclarationWithCollidingName(node)
73612 || (isDeclaredInLoop
73613 && !isCapturedInFunction
73614 && (hierarchyFacts & (1024 /* ForStatement */ | 2048 /* ForInOrForOfStatement */)) === 0));
73615 return emitExplicitInitializer;
73616 }
73617 /**
73618 * Visits a VariableDeclaration in a `let` declaration list.
73619 *
73620 * @param node A VariableDeclaration node.
73621 */
73622 function visitVariableDeclarationInLetDeclarationList(node) {
73623 // For binding pattern names that lack initializers there is no point to emit
73624 // explicit initializer since downlevel codegen for destructuring will fail
73625 // in the absence of initializer so all binding elements will say uninitialized
73626 var name = node.name;
73627 if (ts.isBindingPattern(name)) {
73628 return visitVariableDeclaration(node);
73629 }
73630 if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
73631 var clone_2 = ts.getMutableClone(node);
73632 clone_2.initializer = ts.createVoidZero();
73633 return clone_2;
73634 }
73635 return ts.visitEachChild(node, visitor, context);
73636 }
73637 /**
73638 * Visits a VariableDeclaration node with a binding pattern.
73639 *
73640 * @param node A VariableDeclaration node.
73641 */
73642 function visitVariableDeclaration(node) {
73643 var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
73644 var updated;
73645 if (ts.isBindingPattern(node.name)) {
73646 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */,
73647 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
73648 }
73649 else {
73650 updated = ts.visitEachChild(node, visitor, context);
73651 }
73652 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
73653 return updated;
73654 }
73655 function recordLabel(node) {
73656 convertedLoopState.labels.set(ts.idText(node.label), true);
73657 }
73658 function resetLabel(node) {
73659 convertedLoopState.labels.set(ts.idText(node.label), false);
73660 }
73661 function visitLabeledStatement(node) {
73662 if (convertedLoopState && !convertedLoopState.labels) {
73663 convertedLoopState.labels = ts.createMap();
73664 }
73665 var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
73666 return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
73667 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
73668 : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel);
73669 }
73670 function visitIterationStatement(node, outermostLabeledStatement) {
73671 switch (node.kind) {
73672 case 223 /* DoStatement */:
73673 case 224 /* WhileStatement */:
73674 return visitDoOrWhileStatement(node, outermostLabeledStatement);
73675 case 225 /* ForStatement */:
73676 return visitForStatement(node, outermostLabeledStatement);
73677 case 226 /* ForInStatement */:
73678 return visitForInStatement(node, outermostLabeledStatement);
73679 case 227 /* ForOfStatement */:
73680 return visitForOfStatement(node, outermostLabeledStatement);
73681 }
73682 }
73683 function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
73684 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
73685 var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert);
73686 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
73687 return updated;
73688 }
73689 function visitDoOrWhileStatement(node, outermostLabeledStatement) {
73690 return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 256 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
73691 }
73692 function visitForStatement(node, outermostLabeledStatement) {
73693 return visitIterationStatementWithFacts(3008 /* ForStatementExcludes */, 1280 /* ForStatementIncludes */, node, outermostLabeledStatement);
73694 }
73695 function visitForInStatement(node, outermostLabeledStatement) {
73696 return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
73697 }
73698 function visitForOfStatement(node, outermostLabeledStatement) {
73699 return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
73700 }
73701 function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
73702 var statements = [];
73703 var initializer = node.initializer;
73704 if (ts.isVariableDeclarationList(initializer)) {
73705 if (node.initializer.flags & 3 /* BlockScoped */) {
73706 enableSubstitutionsForBlockScopedBindings();
73707 }
73708 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
73709 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
73710 // This works whether the declaration is a var, let, or const.
73711 // It will use rhsIterationValue _a[_i] as the initializer.
73712 var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
73713 var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer);
73714 ts.setOriginalNode(declarationList, node.initializer);
73715 // Adjust the source map range for the first declaration to align with the old
73716 // emitter.
73717 ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
73718 statements.push(ts.createVariableStatement(
73719 /*modifiers*/ undefined, declarationList));
73720 }
73721 else {
73722 // The following call does not include the initializer, so we have
73723 // to emit it separately.
73724 statements.push(ts.setTextRange(ts.createVariableStatement(
73725 /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([
73726 ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined),
73727 /*type*/ undefined, boundValue)
73728 ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
73729 }
73730 }
73731 else {
73732 // Initializer is an expression. Emit the expression in the body, so that it's
73733 // evaluated on every iteration.
73734 var assignment = ts.createAssignment(initializer, boundValue);
73735 if (ts.isDestructuringAssignment(assignment)) {
73736 ts.aggregateTransformFlags(assignment);
73737 statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
73738 }
73739 else {
73740 assignment.end = initializer.end;
73741 statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
73742 }
73743 }
73744 if (convertedLoopBodyStatements) {
73745 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
73746 }
73747 else {
73748 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
73749 if (ts.isBlock(statement)) {
73750 return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
73751 }
73752 else {
73753 statements.push(statement);
73754 return createSyntheticBlockForConvertedStatements(statements);
73755 }
73756 }
73757 }
73758 function createSyntheticBlockForConvertedStatements(statements) {
73759 return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements),
73760 /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
73761 }
73762 function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
73763 // The following ES6 code:
73764 //
73765 // for (let v of expr) { }
73766 //
73767 // should be emitted as
73768 //
73769 // for (var _i = 0, _a = expr; _i < _a.length; _i++) {
73770 // var v = _a[_i];
73771 // }
73772 //
73773 // where _a and _i are temps emitted to capture the RHS and the counter,
73774 // respectively.
73775 // When the left hand side is an expression instead of a let declaration,
73776 // the "let v" is not emitted.
73777 // When the left hand side is a let/const, the v is renamed if there is
73778 // another v in scope.
73779 // Note that all assignments to the LHS are emitted in the body, including
73780 // all destructuring.
73781 // Note also that because an extra statement is needed to assign to the LHS,
73782 // for-of bodies are always emitted as blocks.
73783 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
73784 // In the case where the user wrote an identifier as the RHS, like this:
73785 //
73786 // for (let v of arr) { }
73787 //
73788 // we don't want to emit a temporary variable for the RHS, just use it directly.
73789 var counter = ts.createLoopVariable();
73790 var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
73791 // The old emitter does not emit source maps for the expression
73792 ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
73793 var forStatement = ts.setTextRange(ts.createFor(
73794 /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
73795 ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)),
73796 ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression)
73797 ]), node.expression), 2097152 /* NoHoisting */),
73798 /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression),
73799 /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression),
73800 /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)),
73801 /*location*/ node);
73802 // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
73803 ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
73804 ts.setTextRange(forStatement, node);
73805 return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
73806 }
73807 function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements) {
73808 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
73809 var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
73810 var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
73811 var errorRecord = ts.createUniqueName("e");
73812 var catchVariable = ts.getGeneratedNameForNode(errorRecord);
73813 var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
73814 var values = ts.createValuesHelper(context, expression, node.expression);
73815 var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
73816 hoistVariableDeclaration(errorRecord);
73817 hoistVariableDeclaration(returnMethod);
73818 var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
73819 /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
73820 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression),
73821 ts.createVariableDeclaration(result, /*type*/ undefined, next)
73822 ]), node.expression), 2097152 /* NoHoisting */),
73823 /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")),
73824 /*incrementor*/ ts.createAssignment(result, next),
73825 /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)),
73826 /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
73827 return ts.createTry(ts.createBlock([
73828 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
73829 ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
73830 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
73831 ts.createPropertyAssignment("error", catchVariable)
73832 ])))
73833 ]), 1 /* SingleLine */)), ts.createBlock([
73834 ts.createTry(
73835 /*tryBlock*/ ts.createBlock([
73836 ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */),
73837 ]),
73838 /*catchClause*/ undefined,
73839 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
73840 ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
73841 ]), 1 /* SingleLine */))
73842 ]));
73843 }
73844 /**
73845 * Visits an ObjectLiteralExpression with computed property names.
73846 *
73847 * @param node An ObjectLiteralExpression node.
73848 */
73849 function visitObjectLiteralExpression(node) {
73850 // We are here because a ComputedPropertyName was used somewhere in the expression.
73851 var properties = node.properties;
73852 var numProperties = properties.length;
73853 // Find the first computed property.
73854 // Everything until that point can be emitted as part of the initial object literal.
73855 var numInitialProperties = numProperties;
73856 var numInitialPropertiesWithoutYield = numProperties;
73857 for (var i = 0; i < numProperties; i++) {
73858 var property = properties[i];
73859 if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
73860 && i < numInitialPropertiesWithoutYield) {
73861 numInitialPropertiesWithoutYield = i;
73862 }
73863 if (property.name.kind === 149 /* ComputedPropertyName */) {
73864 numInitialProperties = i;
73865 break;
73866 }
73867 }
73868 if (numInitialProperties !== numProperties) {
73869 if (numInitialPropertiesWithoutYield < numInitialProperties) {
73870 numInitialProperties = numInitialPropertiesWithoutYield;
73871 }
73872 // For computed properties, we need to create a unique handle to the object
73873 // literal so we can modify it without risking internal assignments tainting the object.
73874 var temp = ts.createTempVariable(hoistVariableDeclaration);
73875 // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
73876 var expressions = [];
73877 var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */));
73878 if (node.multiLine) {
73879 ts.startOnNewLine(assignment);
73880 }
73881 expressions.push(assignment);
73882 addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
73883 // We need to clone the temporary identifier so that we can write it on a
73884 // new line
73885 expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
73886 return ts.inlineExpressions(expressions);
73887 }
73888 return ts.visitEachChild(node, visitor, context);
73889 }
73890 function shouldConvertPartOfIterationStatement(node) {
73891 return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
73892 }
73893 function shouldConvertInitializerOfForStatement(node) {
73894 return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
73895 }
73896 function shouldConvertConditionOfForStatement(node) {
73897 return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
73898 }
73899 function shouldConvertIncrementorOfForStatement(node) {
73900 return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
73901 }
73902 function shouldConvertIterationStatement(node) {
73903 return shouldConvertBodyOfIterationStatement(node)
73904 || shouldConvertInitializerOfForStatement(node);
73905 }
73906 function shouldConvertBodyOfIterationStatement(node) {
73907 return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
73908 }
73909 /**
73910 * Records constituents of name for the given variable to be hoisted in the outer scope.
73911 */
73912 function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
73913 if (!state.hoistedLocalVariables) {
73914 state.hoistedLocalVariables = [];
73915 }
73916 visit(node.name);
73917 function visit(node) {
73918 if (node.kind === 72 /* Identifier */) {
73919 state.hoistedLocalVariables.push(node);
73920 }
73921 else {
73922 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
73923 var element = _a[_i];
73924 if (!ts.isOmittedExpression(element)) {
73925 visit(element.name);
73926 }
73927 }
73928 }
73929 }
73930 }
73931 function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) {
73932 if (!shouldConvertIterationStatement(node)) {
73933 var saveAllowedNonLabeledJumps = void 0;
73934 if (convertedLoopState) {
73935 // we get here if we are trying to emit normal loop loop inside converted loop
73936 // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
73937 saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
73938 convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
73939 }
73940 var result = convert
73941 ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined)
73942 : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
73943 if (convertedLoopState) {
73944 convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
73945 }
73946 return result;
73947 }
73948 var currentState = createConvertedLoopState(node);
73949 var statements = [];
73950 var outerConvertedLoopState = convertedLoopState;
73951 convertedLoopState = currentState;
73952 var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
73953 var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
73954 convertedLoopState = outerConvertedLoopState;
73955 if (initializerFunction)
73956 statements.push(initializerFunction.functionDeclaration);
73957 if (bodyFunction)
73958 statements.push(bodyFunction.functionDeclaration);
73959 addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
73960 if (initializerFunction) {
73961 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
73962 }
73963 var loop;
73964 if (bodyFunction) {
73965 if (convert) {
73966 loop = convert(node, outermostLabeledStatement, bodyFunction.part);
73967 }
73968 else {
73969 var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true));
73970 ts.aggregateTransformFlags(clone_3);
73971 loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel);
73972 }
73973 }
73974 else {
73975 var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
73976 ts.aggregateTransformFlags(clone_4);
73977 loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
73978 }
73979 statements.push(loop);
73980 return statements;
73981 }
73982 function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
73983 switch (node.kind) {
73984 case 225 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
73985 case 226 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
73986 case 227 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
73987 case 223 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
73988 case 224 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
73989 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
73990 }
73991 }
73992 function convertForStatement(node, initializerFunction, convertedLoopBody) {
73993 var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
73994 var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
73995 return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody);
73996 }
73997 function convertForOfStatement(node, convertedLoopBody) {
73998 return ts.updateForOf(node,
73999 /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
74000 }
74001 function convertForInStatement(node, convertedLoopBody) {
74002 return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
74003 }
74004 function convertDoStatement(node, convertedLoopBody) {
74005 return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
74006 }
74007 function convertWhileStatement(node, convertedLoopBody) {
74008 return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
74009 }
74010 function createConvertedLoopState(node) {
74011 var loopInitializer;
74012 switch (node.kind) {
74013 case 225 /* ForStatement */:
74014 case 226 /* ForInStatement */:
74015 case 227 /* ForOfStatement */:
74016 var initializer = node.initializer;
74017 if (initializer && initializer.kind === 238 /* VariableDeclarationList */) {
74018 loopInitializer = initializer;
74019 }
74020 break;
74021 }
74022 // variables that will be passed to the loop as parameters
74023 var loopParameters = [];
74024 // variables declared in the loop initializer that will be changed inside the loop
74025 var loopOutParameters = [];
74026 if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
74027 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
74028 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
74029 var decl = _a[_i];
74030 processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
74031 }
74032 }
74033 var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
74034 if (convertedLoopState) {
74035 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
74036 // if outer converted loop has already accumulated some state - pass it through
74037 if (convertedLoopState.argumentsName) {
74038 // outer loop has already used 'arguments' so we've already have some name to alias it
74039 // use the same name in all nested loops
74040 currentState.argumentsName = convertedLoopState.argumentsName;
74041 }
74042 if (convertedLoopState.thisName) {
74043 // outer loop has already used 'this' so we've already have some name to alias it
74044 // use the same name in all nested loops
74045 currentState.thisName = convertedLoopState.thisName;
74046 }
74047 if (convertedLoopState.hoistedLocalVariables) {
74048 // we've already collected some non-block scoped variable declarations in enclosing loop
74049 // use the same storage in nested loop
74050 currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
74051 }
74052 }
74053 return currentState;
74054 }
74055 function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
74056 var extraVariableDeclarations;
74057 // propagate state from the inner loop to the outer loop if necessary
74058 if (state.argumentsName) {
74059 // if alias for arguments is set
74060 if (outerState) {
74061 // pass it to outer converted loop
74062 outerState.argumentsName = state.argumentsName;
74063 }
74064 else {
74065 // this is top level converted loop and we need to create an alias for 'arguments' object
74066 (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName,
74067 /*type*/ undefined, ts.createIdentifier("arguments")));
74068 }
74069 }
74070 if (state.thisName) {
74071 // if alias for this is set
74072 if (outerState) {
74073 // pass it to outer converted loop
74074 outerState.thisName = state.thisName;
74075 }
74076 else {
74077 // this is top level converted loop so we need to create an alias for 'this' here
74078 // NOTE:
74079 // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
74080 // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
74081 (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName,
74082 /*type*/ undefined, ts.createIdentifier("this")));
74083 }
74084 }
74085 if (state.hoistedLocalVariables) {
74086 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
74087 if (outerState) {
74088 // pass them to outer converted loop
74089 outerState.hoistedLocalVariables = state.hoistedLocalVariables;
74090 }
74091 else {
74092 if (!extraVariableDeclarations) {
74093 extraVariableDeclarations = [];
74094 }
74095 // hoist collected variable declarations
74096 for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
74097 var identifier = _a[_i];
74098 extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
74099 }
74100 }
74101 }
74102 // add extra variables to hold out parameters if necessary
74103 if (state.loopOutParameters.length) {
74104 if (!extraVariableDeclarations) {
74105 extraVariableDeclarations = [];
74106 }
74107 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
74108 var outParam = _c[_b];
74109 extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName));
74110 }
74111 }
74112 if (state.conditionVariable) {
74113 if (!extraVariableDeclarations) {
74114 extraVariableDeclarations = [];
74115 }
74116 extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse()));
74117 }
74118 // create variable statement to hold all introduced variable declarations
74119 if (extraVariableDeclarations) {
74120 statements.push(ts.createVariableStatement(
74121 /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations)));
74122 }
74123 }
74124 function createOutVariable(p) {
74125 return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName);
74126 }
74127 /**
74128 * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
74129 * that is captured in a closure inside of the initializer. The `_loop_init` function is
74130 * used to preserve the per-iteration environment semantics of
74131 * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
74132 */
74133 function createFunctionForInitializerOfForStatement(node, currentState) {
74134 var functionName = ts.createUniqueName("_loop_init");
74135 var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0;
74136 var emitFlags = 0 /* None */;
74137 if (currentState.containsLexicalThis)
74138 emitFlags |= 8 /* CapturesThis */;
74139 if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
74140 emitFlags |= 262144 /* AsyncFunctionBody */;
74141 var statements = [];
74142 statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer));
74143 copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
74144 // This transforms the following ES2015 syntax:
74145 //
74146 // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
74147 // // loop body
74148 // }
74149 //
74150 // Into the following ES5 syntax:
74151 //
74152 // var _loop_init_1 = function () {
74153 // var i = (setImmediate(() => console.log(i)), 0);
74154 // out_i_1 = i;
74155 // };
74156 // var out_i_1;
74157 // _loop_init_1();
74158 // for (var i = out_i_1; i < 2; i++) {
74159 // // loop body
74160 // }
74161 //
74162 // Which prevents mutations to `i` in the per-iteration environment of the body
74163 // from affecting the initial value for `i` outside of the per-iteration environment.
74164 var functionDeclaration = ts.createVariableStatement(
74165 /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
74166 ts.createVariableDeclaration(functionName,
74167 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
74168 /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined,
74169 /*name*/ undefined,
74170 /*typeParameters*/ undefined,
74171 /*parameters*/ undefined,
74172 /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
74173 ]), 2097152 /* NoHoisting */));
74174 var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
74175 return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
74176 }
74177 /**
74178 * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
74179 * that is captured in a closure inside of the loop body. The `_loop` function is used to
74180 * preserve the per-iteration environment semantics of
74181 * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
74182 */
74183 function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
74184 var functionName = ts.createUniqueName("_loop");
74185 startLexicalEnvironment();
74186 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
74187 var lexicalEnvironment = endLexicalEnvironment();
74188 var statements = [];
74189 if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
74190 // If a block-scoped variable declared in the initializer of `node` is captured in
74191 // the condition or incrementor, we must move the condition and incrementor into
74192 // the body of the for loop.
74193 //
74194 // This transforms the following ES2015 syntax:
74195 //
74196 // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
74197 // // loop body
74198 // }
74199 //
74200 // Into the following ES5 syntax:
74201 //
74202 // var _loop_1 = function (i) {
74203 // if (inc_1)
74204 // setImmediate(() => console.log(i)), i++;
74205 // else
74206 // inc_1 = true;
74207 // if (!(setImmediate(() => console.log(i)), i < 2))
74208 // return out_i_1 = i, "break";
74209 // // loop body
74210 // out_i_1 = i;
74211 // }
74212 // var out_i_1, inc_1 = false;
74213 // for (var i = 0;;) {
74214 // var state_1 = _loop_1(i);
74215 // i = out_i_1;
74216 // if (state_1 === "break")
74217 // break;
74218 // }
74219 //
74220 // Which prevents mutations to `i` in the per-iteration environment of the body
74221 // from affecting the value of `i` in the previous per-iteration environment.
74222 //
74223 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
74224 // environment that is carried over to the next iteration of the loop. As a result,
74225 // we must indicate whether this is the first evaluation of the loop body so that
74226 // we only evaluate the incrementor on subsequent evaluations.
74227 currentState.conditionVariable = ts.createUniqueName("inc");
74228 statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue()))));
74229 if (shouldConvertConditionOfForStatement(node)) {
74230 statements.push(ts.createIf(ts.createPrefix(52 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement)));
74231 }
74232 }
74233 if (ts.isBlock(statement)) {
74234 ts.addRange(statements, statement.statements);
74235 }
74236 else {
74237 statements.push(statement);
74238 }
74239 copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
74240 ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
74241 var loopBody = ts.createBlock(statements, /*multiLine*/ true);
74242 if (ts.isBlock(statement))
74243 ts.setOriginalNode(loopBody, statement);
74244 var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0;
74245 var emitFlags = 0;
74246 if (currentState.containsLexicalThis)
74247 emitFlags |= 8 /* CapturesThis */;
74248 if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
74249 emitFlags |= 262144 /* AsyncFunctionBody */;
74250 // This transforms the following ES2015 syntax (in addition to other variations):
74251 //
74252 // for (let i = 0; i < 2; i++) {
74253 // setImmediate(() => console.log(i));
74254 // }
74255 //
74256 // Into the following ES5 syntax:
74257 //
74258 // var _loop_1 = function (i) {
74259 // setImmediate(() => console.log(i));
74260 // };
74261 // for (var i = 0; i < 2; i++) {
74262 // _loop_1(i);
74263 // }
74264 var functionDeclaration = ts.createVariableStatement(
74265 /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
74266 ts.createVariableDeclaration(functionName,
74267 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
74268 /*modifiers*/ undefined, containsYield ? ts.createToken(40 /* AsteriskToken */) : undefined,
74269 /*name*/ undefined,
74270 /*typeParameters*/ undefined, currentState.loopParameters,
74271 /*type*/ undefined, loopBody), emitFlags))
74272 ]), 2097152 /* NoHoisting */));
74273 var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
74274 return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
74275 }
74276 function copyOutParameter(outParam, copyDirection) {
74277 var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
74278 var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
74279 return ts.createBinary(target, 59 /* EqualsToken */, source);
74280 }
74281 function copyOutParameters(outParams, partFlags, copyDirection, statements) {
74282 for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
74283 var outParam = outParams_1[_i];
74284 if (outParam.flags & partFlags) {
74285 statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
74286 }
74287 }
74288 }
74289 function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
74290 var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []);
74291 var callResult = containsYield
74292 ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
74293 : call;
74294 return ts.createStatement(callResult);
74295 }
74296 function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
74297 var statements = [];
74298 // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
74299 // simple loops are emitted as just 'loop()';
74300 // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
74301 var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
74302 !state.labeledNonLocalBreaks &&
74303 !state.labeledNonLocalContinues;
74304 var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
74305 var callResult = containsYield
74306 ? ts.createYield(ts.createToken(40 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
74307 : call;
74308 if (isSimpleLoop) {
74309 statements.push(ts.createExpressionStatement(callResult));
74310 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
74311 }
74312 else {
74313 var loopResultName = ts.createUniqueName("state");
74314 var stateVariable = ts.createVariableStatement(
74315 /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)]));
74316 statements.push(stateVariable);
74317 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
74318 if (state.nonLocalJumps & 8 /* Return */) {
74319 var returnStatement = void 0;
74320 if (outerState) {
74321 outerState.nonLocalJumps |= 8 /* Return */;
74322 returnStatement = ts.createReturn(loopResultName);
74323 }
74324 else {
74325 returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value"));
74326 }
74327 statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement));
74328 }
74329 if (state.nonLocalJumps & 2 /* Break */) {
74330 statements.push(ts.createIf(ts.createBinary(loopResultName, 35 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak()));
74331 }
74332 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
74333 var caseClauses = [];
74334 processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
74335 processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
74336 statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses)));
74337 }
74338 }
74339 return statements;
74340 }
74341 function setLabeledJump(state, isBreak, labelText, labelMarker) {
74342 if (isBreak) {
74343 if (!state.labeledNonLocalBreaks) {
74344 state.labeledNonLocalBreaks = ts.createMap();
74345 }
74346 state.labeledNonLocalBreaks.set(labelText, labelMarker);
74347 }
74348 else {
74349 if (!state.labeledNonLocalContinues) {
74350 state.labeledNonLocalContinues = ts.createMap();
74351 }
74352 state.labeledNonLocalContinues.set(labelText, labelMarker);
74353 }
74354 }
74355 function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
74356 if (!table) {
74357 return;
74358 }
74359 table.forEach(function (labelMarker, labelText) {
74360 var statements = [];
74361 // if there are no outer converted loop or outer label in question is located inside outer converted loop
74362 // then emit labeled break\continue
74363 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
74364 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
74365 var label = ts.createIdentifier(labelText);
74366 statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label));
74367 }
74368 else {
74369 setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
74370 statements.push(ts.createReturn(loopResultName));
74371 }
74372 caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements));
74373 });
74374 }
74375 function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
74376 var name = decl.name;
74377 if (ts.isBindingPattern(name)) {
74378 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
74379 var element = _a[_i];
74380 if (!ts.isOmittedExpression(element)) {
74381 processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
74382 }
74383 }
74384 }
74385 else {
74386 loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
74387 var checkFlags = resolver.getNodeCheckFlags(decl);
74388 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
74389 var outParamName = ts.createUniqueName("out_" + ts.idText(name));
74390 var flags = 0;
74391 if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
74392 flags |= 1 /* Body */;
74393 }
74394 if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
74395 flags |= 2 /* Initializer */;
74396 }
74397 loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
74398 }
74399 }
74400 }
74401 /**
74402 * Adds the members of an object literal to an array of expressions.
74403 *
74404 * @param expressions An array of expressions.
74405 * @param node An ObjectLiteralExpression node.
74406 * @param receiver The receiver for members of the ObjectLiteralExpression.
74407 * @param numInitialNonComputedProperties The number of initial properties without
74408 * computed property names.
74409 */
74410 function addObjectLiteralMembers(expressions, node, receiver, start) {
74411 var properties = node.properties;
74412 var numProperties = properties.length;
74413 for (var i = start; i < numProperties; i++) {
74414 var property = properties[i];
74415 switch (property.kind) {
74416 case 158 /* GetAccessor */:
74417 case 159 /* SetAccessor */:
74418 var accessors = ts.getAllAccessorDeclarations(node.properties, property);
74419 if (property === accessors.firstAccessor) {
74420 expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
74421 }
74422 break;
74423 case 156 /* MethodDeclaration */:
74424 expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
74425 break;
74426 case 275 /* PropertyAssignment */:
74427 expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
74428 break;
74429 case 276 /* ShorthandPropertyAssignment */:
74430 expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
74431 break;
74432 default:
74433 ts.Debug.failBadSyntaxKind(node);
74434 break;
74435 }
74436 }
74437 }
74438 /**
74439 * Transforms a PropertyAssignment node into an expression.
74440 *
74441 * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
74442 * @param property The PropertyAssignment node.
74443 * @param receiver The receiver for the assignment.
74444 */
74445 function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
74446 var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
74447 ts.setTextRange(expression, property);
74448 if (startsOnNewLine) {
74449 ts.startOnNewLine(expression);
74450 }
74451 return expression;
74452 }
74453 /**
74454 * Transforms a ShorthandPropertyAssignment node into an expression.
74455 *
74456 * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
74457 * @param property The ShorthandPropertyAssignment node.
74458 * @param receiver The receiver for the assignment.
74459 */
74460 function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
74461 var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name));
74462 ts.setTextRange(expression, property);
74463 if (startsOnNewLine) {
74464 ts.startOnNewLine(expression);
74465 }
74466 return expression;
74467 }
74468 /**
74469 * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
74470 *
74471 * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
74472 * @param method The MethodDeclaration node.
74473 * @param receiver The receiver for the assignment.
74474 */
74475 function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
74476 var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
74477 ts.setTextRange(expression, method);
74478 if (startsOnNewLine) {
74479 ts.startOnNewLine(expression);
74480 }
74481 return expression;
74482 }
74483 function visitCatchClause(node) {
74484 var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
74485 var updated;
74486 ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
74487 if (ts.isBindingPattern(node.variableDeclaration.name)) {
74488 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
74489 var newVariableDeclaration = ts.createVariableDeclaration(temp);
74490 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
74491 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
74492 var list = ts.createVariableDeclarationList(vars);
74493 ts.setTextRange(list, node.variableDeclaration);
74494 var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list);
74495 updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
74496 }
74497 else {
74498 updated = ts.visitEachChild(node, visitor, context);
74499 }
74500 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
74501 return updated;
74502 }
74503 function addStatementToStartOfBlock(block, statement) {
74504 var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
74505 return ts.updateBlock(block, [statement].concat(transformedStatements));
74506 }
74507 /**
74508 * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
74509 * PropertyAssignment.
74510 *
74511 * @param node A MethodDeclaration node.
74512 */
74513 function visitMethodDeclaration(node) {
74514 // We should only get here for methods on an object literal with regular identifier names.
74515 // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
74516 // Methods with computed property names are handled in visitObjectLiteralExpression.
74517 ts.Debug.assert(!ts.isComputedPropertyName(node.name));
74518 var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
74519 ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
74520 return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression),
74521 /*location*/ node);
74522 }
74523 /**
74524 * Visits an AccessorDeclaration of an ObjectLiteralExpression.
74525 *
74526 * @param node An AccessorDeclaration node.
74527 */
74528 function visitAccessorDeclaration(node) {
74529 ts.Debug.assert(!ts.isComputedPropertyName(node.name));
74530 var savedConvertedLoopState = convertedLoopState;
74531 convertedLoopState = undefined;
74532 var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
74533 var updated;
74534 var parameters = ts.visitParameterList(node.parameters, visitor, context);
74535 var body = transformFunctionBody(node);
74536 if (node.kind === 158 /* GetAccessor */) {
74537 updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
74538 }
74539 else {
74540 updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
74541 }
74542 exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
74543 convertedLoopState = savedConvertedLoopState;
74544 return updated;
74545 }
74546 /**
74547 * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
74548 *
74549 * @param node A ShorthandPropertyAssignment node.
74550 */
74551 function visitShorthandPropertyAssignment(node) {
74552 return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)),
74553 /*location*/ node);
74554 }
74555 function visitComputedPropertyName(node) {
74556 return ts.visitEachChild(node, visitor, context);
74557 }
74558 /**
74559 * Visits a YieldExpression node.
74560 *
74561 * @param node A YieldExpression node.
74562 */
74563 function visitYieldExpression(node) {
74564 // `yield` expressions are transformed using the generators transformer.
74565 return ts.visitEachChild(node, visitor, context);
74566 }
74567 /**
74568 * Visits an ArrayLiteralExpression that contains a spread element.
74569 *
74570 * @param node An ArrayLiteralExpression node.
74571 */
74572 function visitArrayLiteralExpression(node) {
74573 if (ts.some(node.elements, ts.isSpreadElement)) {
74574 // We are here because we contain a SpreadElementExpression.
74575 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
74576 }
74577 return ts.visitEachChild(node, visitor, context);
74578 }
74579 /**
74580 * Visits a CallExpression that contains either a spread element or `super`.
74581 *
74582 * @param node a CallExpression.
74583 */
74584 function visitCallExpression(node) {
74585 if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
74586 return visitTypeScriptClassWrapper(node);
74587 }
74588 var expression = ts.skipOuterExpressions(node.expression);
74589 if (expression.kind === 98 /* SuperKeyword */ ||
74590 ts.isSuperProperty(expression) ||
74591 ts.some(node.arguments, ts.isSpreadElement)) {
74592 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
74593 }
74594 return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression),
74595 /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
74596 }
74597 function visitTypeScriptClassWrapper(node) {
74598 // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
74599 // The wrapper has a form similar to:
74600 //
74601 // (function() {
74602 // class C { // 1
74603 // }
74604 // C.x = 1; // 2
74605 // return C;
74606 // }())
74607 //
74608 // When we transform the class, we end up with something like this:
74609 //
74610 // (function () {
74611 // var C = (function () { // 3
74612 // function C() {
74613 // }
74614 // return C; // 4
74615 // }());
74616 // C.x = 1;
74617 // return C;
74618 // }())
74619 //
74620 // We want to simplify the two nested IIFEs to end up with something like this:
74621 //
74622 // (function () {
74623 // function C() {
74624 // }
74625 // C.x = 1;
74626 // return C;
74627 // }())
74628 // We skip any outer expressions in a number of places to get to the innermost
74629 // expression, but we will restore them later to preserve comments and source maps.
74630 var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
74631 // The class statements are the statements generated by visiting the first statement with initializer of the
74632 // body (1), while all other statements are added to remainingStatements (2)
74633 var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
74634 var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
74635 var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
74636 var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
74637 var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
74638 // We know there is only one variable declaration here as we verified this in an
74639 // earlier call to isTypeScriptClassWrapper
74640 var variable = varStatement.declarationList.declarations[0];
74641 var initializer = ts.skipOuterExpressions(variable.initializer);
74642 // Under certain conditions, the 'ts' transformer may introduce a class alias, which
74643 // we see as an assignment, for example:
74644 //
74645 // (function () {
74646 // var C_1;
74647 // var C = C_1 = (function () {
74648 // function C() {
74649 // }
74650 // C.x = function () { return C_1; }
74651 // return C;
74652 // }());
74653 // C = C_1 = __decorate([dec], C);
74654 // return C;
74655 // }())
74656 //
74657 var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
74658 // The underlying call (3) is another IIFE that may contain a '_super' argument.
74659 var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
74660 var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
74661 var funcStatements = func.body.statements;
74662 var classBodyStart = 0;
74663 var classBodyEnd = -1;
74664 var statements = [];
74665 if (aliasAssignment) {
74666 // If we have a class alias assignment, we need to move it to the down-level constructor
74667 // function we generated for the class.
74668 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
74669 if (extendsCall) {
74670 statements.push(extendsCall);
74671 classBodyStart++;
74672 }
74673 // The next statement is the function declaration.
74674 statements.push(funcStatements[classBodyStart]);
74675 classBodyStart++;
74676 // Add the class alias following the declaration.
74677 statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
74678 }
74679 // Find the trailing 'return' statement (4)
74680 while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
74681 classBodyEnd--;
74682 }
74683 // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
74684 // as we already have one that has been introduced by the 'ts' transformer.
74685 ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
74686 if (classBodyEnd < -1) {
74687 // If there were any hoisted declarations following the return statement, we should
74688 // append them.
74689 ts.addRange(statements, funcStatements, classBodyEnd + 1);
74690 }
74691 // Add the remaining statements of the outer wrapper.
74692 ts.addRange(statements, remainingStatements);
74693 // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
74694 // after the remaining statements from the 'ts' transformer.
74695 ts.addRange(statements, classStatements, /*start*/ 1);
74696 // Recreate any outer parentheses or partially-emitted expressions to preserve source map
74697 // and comment locations.
74698 return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func,
74699 /*modifiers*/ undefined,
74700 /*asteriskToken*/ undefined,
74701 /*name*/ undefined,
74702 /*typeParameters*/ undefined, func.parameters,
74703 /*type*/ undefined, ts.updateBlock(func.body, statements))),
74704 /*typeArguments*/ undefined, call.arguments))));
74705 }
74706 function visitImmediateSuperCallInBody(node) {
74707 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
74708 }
74709 function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
74710 // We are here either because SuperKeyword was used somewhere in the expression, or
74711 // because we contain a SpreadElementExpression.
74712 if (node.transformFlags & 4096 /* ContainsRestOrSpread */ ||
74713 node.expression.kind === 98 /* SuperKeyword */ ||
74714 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
74715 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
74716 if (node.expression.kind === 98 /* SuperKeyword */) {
74717 ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
74718 }
74719 var resultingCall = void 0;
74720 if (node.transformFlags & 4096 /* ContainsRestOrSpread */) {
74721 // [source]
74722 // f(...a, b)
74723 // x.m(...a, b)
74724 // super(...a, b)
74725 // super.m(...a, b) // in static
74726 // super.m(...a, b) // in instance
74727 //
74728 // [output]
74729 // f.apply(void 0, a.concat([b]))
74730 // (_a = x).m.apply(_a, a.concat([b]))
74731 // _super.apply(this, a.concat([b]))
74732 // _super.m.apply(this, a.concat([b]))
74733 // _super.prototype.m.apply(this, a.concat([b]))
74734 resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
74735 }
74736 else {
74737 // [source]
74738 // super(a)
74739 // super.m(a) // in static
74740 // super.m(a) // in instance
74741 //
74742 // [output]
74743 // _super.call(this, a)
74744 // _super.m.call(this, a)
74745 // _super.prototype.m.call(this, a)
74746 resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
74747 /*location*/ node);
74748 }
74749 if (node.expression.kind === 98 /* SuperKeyword */) {
74750 var initializer = ts.createLogicalOr(resultingCall, createActualThis());
74751 resultingCall = assignToCapturedThis
74752 ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
74753 : initializer;
74754 }
74755 return ts.setOriginalNode(resultingCall, node);
74756 }
74757 return ts.visitEachChild(node, visitor, context);
74758 }
74759 /**
74760 * Visits a NewExpression that contains a spread element.
74761 *
74762 * @param node A NewExpression node.
74763 */
74764 function visitNewExpression(node) {
74765 if (ts.some(node.arguments, ts.isSpreadElement)) {
74766 // We are here because we contain a SpreadElementExpression.
74767 // [source]
74768 // new C(...a)
74769 //
74770 // [output]
74771 // new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
74772 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
74773 return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)),
74774 /*typeArguments*/ undefined, []);
74775 }
74776 return ts.visitEachChild(node, visitor, context);
74777 }
74778 /**
74779 * Transforms an array of Expression nodes that contains a SpreadExpression.
74780 *
74781 * @param elements The array of Expression nodes.
74782 * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
74783 * @param multiLine A value indicating whether the result should be emitted on multiple lines.
74784 */
74785 function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
74786 // [source]
74787 // [a, ...b, c]
74788 //
74789 // [output]
74790 // [a].concat(b, [c])
74791 // Map spans of spread expressions into their expressions and spans of other
74792 // expressions into an array literal.
74793 var numElements = elements.length;
74794 var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
74795 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
74796 }));
74797 if (compilerOptions.downlevelIteration) {
74798 if (segments.length === 1) {
74799 var firstSegment = segments[0];
74800 if (ts.isCallExpression(firstSegment)
74801 && ts.isIdentifier(firstSegment.expression)
74802 && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
74803 && firstSegment.expression.escapedText === "___spread") {
74804 return segments[0];
74805 }
74806 }
74807 return ts.createSpreadHelper(context, segments);
74808 }
74809 else {
74810 if (segments.length === 1) {
74811 var firstElement = elements[0];
74812 return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 187 /* ArrayLiteralExpression */
74813 ? ts.createArraySlice(segments[0])
74814 : segments[0];
74815 }
74816 // Rewrite using the pattern <segment0>.concat(<segment1>, <segment2>, ...)
74817 return ts.createArrayConcat(segments.shift(), segments);
74818 }
74819 }
74820 function partitionSpread(node) {
74821 return ts.isSpreadElement(node)
74822 ? visitSpanOfSpreads
74823 : visitSpanOfNonSpreads;
74824 }
74825 function visitSpanOfSpreads(chunk) {
74826 return ts.map(chunk, visitExpressionOfSpread);
74827 }
74828 function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
74829 return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
74830 }
74831 function visitSpreadElement(node) {
74832 return ts.visitNode(node.expression, visitor, ts.isExpression);
74833 }
74834 /**
74835 * Transforms the expression of a SpreadExpression node.
74836 *
74837 * @param node A SpreadExpression node.
74838 */
74839 function visitExpressionOfSpread(node) {
74840 return ts.visitNode(node.expression, visitor, ts.isExpression);
74841 }
74842 /**
74843 * Visits a template literal.
74844 *
74845 * @param node A template literal.
74846 */
74847 function visitTemplateLiteral(node) {
74848 return ts.setTextRange(ts.createLiteral(node.text), node);
74849 }
74850 /**
74851 * Visits a string literal with an extended unicode escape.
74852 *
74853 * @param node A string literal.
74854 */
74855 function visitStringLiteral(node) {
74856 if (node.hasExtendedUnicodeEscape) {
74857 return ts.setTextRange(ts.createLiteral(node.text), node);
74858 }
74859 return node;
74860 }
74861 /**
74862 * Visits a binary or octal (ES6) numeric literal.
74863 *
74864 * @param node A string literal.
74865 */
74866 function visitNumericLiteral(node) {
74867 if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
74868 return ts.setTextRange(ts.createNumericLiteral(node.text), node);
74869 }
74870 return node;
74871 }
74872 /**
74873 * Visits a TaggedTemplateExpression node.
74874 *
74875 * @param node A TaggedTemplateExpression node.
74876 */
74877 function visitTaggedTemplateExpression(node) {
74878 // Visit the tag expression
74879 var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
74880 // Build up the template arguments and the raw and cooked strings for the template.
74881 // We start out with 'undefined' for the first argument and revisit later
74882 // to avoid walking over the template string twice and shifting all our arguments over after the fact.
74883 var templateArguments = [undefined];
74884 var cookedStrings = [];
74885 var rawStrings = [];
74886 var template = node.template;
74887 if (ts.isNoSubstitutionTemplateLiteral(template)) {
74888 cookedStrings.push(ts.createLiteral(template.text));
74889 rawStrings.push(getRawLiteral(template));
74890 }
74891 else {
74892 cookedStrings.push(ts.createLiteral(template.head.text));
74893 rawStrings.push(getRawLiteral(template.head));
74894 for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
74895 var templateSpan = _a[_i];
74896 cookedStrings.push(ts.createLiteral(templateSpan.literal.text));
74897 rawStrings.push(getRawLiteral(templateSpan.literal));
74898 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
74899 }
74900 }
74901 var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings));
74902 // Create a variable to cache the template object if we're in a module.
74903 // Do not do this in the global scope, as any variable we currently generate could conflict with
74904 // variables from outside of the current compilation. In the future, we can revisit this behavior.
74905 if (ts.isExternalModule(currentSourceFile)) {
74906 var tempVar = ts.createUniqueName("templateObject");
74907 recordTaggedTemplateString(tempVar);
74908 templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall));
74909 }
74910 else {
74911 templateArguments[0] = helperCall;
74912 }
74913 return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments);
74914 }
74915 /**
74916 * Creates an ES5 compatible literal from an ES6 template literal.
74917 *
74918 * @param node The ES6 template literal.
74919 */
74920 function getRawLiteral(node) {
74921 // Find original source text, since we need to emit the raw strings of the tagged template.
74922 // The raw strings contain the (escaped) strings of what the user wrote.
74923 // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
74924 var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
74925 // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
74926 // thus we need to remove those characters.
74927 // First template piece starts with "`", others with "}"
74928 // Last template piece ends with "`", others with "${"
74929 var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
74930 text = text.substring(1, text.length - (isLast ? 1 : 2));
74931 // Newline normalization:
74932 // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
74933 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
74934 text = text.replace(/\r\n?/g, "\n");
74935 return ts.setTextRange(ts.createLiteral(text), node);
74936 }
74937 /**
74938 * Visits a TemplateExpression node.
74939 *
74940 * @param node A TemplateExpression node.
74941 */
74942 function visitTemplateExpression(node) {
74943 var expressions = [];
74944 addTemplateHead(expressions, node);
74945 addTemplateSpans(expressions, node);
74946 // createAdd will check if each expression binds less closely than binary '+'.
74947 // If it does, it wraps the expression in parentheses. Otherwise, something like
74948 // `abc${ 1 << 2 }`
74949 // becomes
74950 // "abc" + 1 << 2 + ""
74951 // which is really
74952 // ("abc" + 1) << (2 + "")
74953 // rather than
74954 // "abc" + (1 << 2) + ""
74955 var expression = ts.reduceLeft(expressions, ts.createAdd);
74956 if (ts.nodeIsSynthesized(expression)) {
74957 expression.pos = node.pos;
74958 expression.end = node.end;
74959 }
74960 return expression;
74961 }
74962 /**
74963 * Gets a value indicating whether we need to include the head of a TemplateExpression.
74964 *
74965 * @param node A TemplateExpression node.
74966 */
74967 function shouldAddTemplateHead(node) {
74968 // If this expression has an empty head literal and the first template span has a non-empty
74969 // literal, then emitting the empty head literal is not necessary.
74970 // `${ foo } and ${ bar }`
74971 // can be emitted as
74972 // foo + " and " + bar
74973 // This is because it is only required that one of the first two operands in the emit
74974 // output must be a string literal, so that the other operand and all following operands
74975 // are forced into strings.
74976 //
74977 // If the first template span has an empty literal, then the head must still be emitted.
74978 // `${ foo }${ bar }`
74979 // must still be emitted as
74980 // "" + foo + bar
74981 // There is always atleast one templateSpan in this code path, since
74982 // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
74983 ts.Debug.assert(node.templateSpans.length !== 0);
74984 return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
74985 }
74986 /**
74987 * Adds the head of a TemplateExpression to an array of expressions.
74988 *
74989 * @param expressions An array of expressions.
74990 * @param node A TemplateExpression node.
74991 */
74992 function addTemplateHead(expressions, node) {
74993 if (!shouldAddTemplateHead(node)) {
74994 return;
74995 }
74996 expressions.push(ts.createLiteral(node.head.text));
74997 }
74998 /**
74999 * Visits and adds the template spans of a TemplateExpression to an array of expressions.
75000 *
75001 * @param expressions An array of expressions.
75002 * @param node A TemplateExpression node.
75003 */
75004 function addTemplateSpans(expressions, node) {
75005 for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
75006 var span = _a[_i];
75007 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
75008 // Only emit if the literal is non-empty.
75009 // The binary '+' operator is left-associative, so the first string concatenation
75010 // with the head will force the result up to this point to be a string.
75011 // Emitting a '+ ""' has no semantic effect for middles and tails.
75012 if (span.literal.text.length !== 0) {
75013 expressions.push(ts.createLiteral(span.literal.text));
75014 }
75015 }
75016 }
75017 /**
75018 * Visits the `super` keyword
75019 */
75020 function visitSuperKeyword(isExpressionOfCall) {
75021 return hierarchyFacts & 8 /* NonStaticClassElement */
75022 && !isExpressionOfCall
75023 ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype")
75024 : ts.createFileLevelUniqueName("_super");
75025 }
75026 function visitMetaProperty(node) {
75027 if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") {
75028 hierarchyFacts |= 8192 /* NewTarget */;
75029 return ts.createFileLevelUniqueName("_newTarget");
75030 }
75031 return node;
75032 }
75033 /**
75034 * Called by the printer just before a node is printed.
75035 *
75036 * @param hint A hint as to the intended usage of the node.
75037 * @param node The node to be printed.
75038 * @param emitCallback The callback used to emit the node.
75039 */
75040 function onEmitNode(hint, node, emitCallback) {
75041 if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
75042 // If we are tracking a captured `this`, keep track of the enclosing function.
75043 var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
75044 ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
75045 : 65 /* FunctionIncludes */);
75046 previousOnEmitNode(hint, node, emitCallback);
75047 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
75048 return;
75049 }
75050 previousOnEmitNode(hint, node, emitCallback);
75051 }
75052 /**
75053 * Enables a more costly code path for substitutions when we determine a source file
75054 * contains block-scoped bindings (e.g. `let` or `const`).
75055 */
75056 function enableSubstitutionsForBlockScopedBindings() {
75057 if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
75058 enabledSubstitutions |= 2 /* BlockScopedBindings */;
75059 context.enableSubstitution(72 /* Identifier */);
75060 }
75061 }
75062 /**
75063 * Enables a more costly code path for substitutions when we determine a source file
75064 * contains a captured `this`.
75065 */
75066 function enableSubstitutionsForCapturedThis() {
75067 if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
75068 enabledSubstitutions |= 1 /* CapturedThis */;
75069 context.enableSubstitution(100 /* ThisKeyword */);
75070 context.enableEmitNotification(157 /* Constructor */);
75071 context.enableEmitNotification(156 /* MethodDeclaration */);
75072 context.enableEmitNotification(158 /* GetAccessor */);
75073 context.enableEmitNotification(159 /* SetAccessor */);
75074 context.enableEmitNotification(197 /* ArrowFunction */);
75075 context.enableEmitNotification(196 /* FunctionExpression */);
75076 context.enableEmitNotification(239 /* FunctionDeclaration */);
75077 }
75078 }
75079 /**
75080 * Hooks node substitutions.
75081 *
75082 * @param hint The context for the emitter.
75083 * @param node The node to substitute.
75084 */
75085 function onSubstituteNode(hint, node) {
75086 node = previousOnSubstituteNode(hint, node);
75087 if (hint === 1 /* Expression */) {
75088 return substituteExpression(node);
75089 }
75090 if (ts.isIdentifier(node)) {
75091 return substituteIdentifier(node);
75092 }
75093 return node;
75094 }
75095 /**
75096 * Hooks substitutions for non-expression identifiers.
75097 */
75098 function substituteIdentifier(node) {
75099 // Only substitute the identifier if we have enabled substitutions for block-scoped
75100 // bindings.
75101 if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
75102 var original = ts.getParseTreeNode(node, ts.isIdentifier);
75103 if (original && isNameOfDeclarationWithCollidingName(original)) {
75104 return ts.setTextRange(ts.getGeneratedNameForNode(original), node);
75105 }
75106 }
75107 return node;
75108 }
75109 /**
75110 * Determines whether a name is the name of a declaration with a colliding name.
75111 * NOTE: This function expects to be called with an original source tree node.
75112 *
75113 * @param node An original source tree node.
75114 */
75115 function isNameOfDeclarationWithCollidingName(node) {
75116 switch (node.parent.kind) {
75117 case 186 /* BindingElement */:
75118 case 240 /* ClassDeclaration */:
75119 case 243 /* EnumDeclaration */:
75120 case 237 /* VariableDeclaration */:
75121 return node.parent.name === node
75122 && resolver.isDeclarationWithCollidingName(node.parent);
75123 }
75124 return false;
75125 }
75126 /**
75127 * Substitutes an expression.
75128 *
75129 * @param node An Expression node.
75130 */
75131 function substituteExpression(node) {
75132 switch (node.kind) {
75133 case 72 /* Identifier */:
75134 return substituteExpressionIdentifier(node);
75135 case 100 /* ThisKeyword */:
75136 return substituteThisKeyword(node);
75137 }
75138 return node;
75139 }
75140 /**
75141 * Substitutes an expression identifier.
75142 *
75143 * @param node An Identifier node.
75144 */
75145 function substituteExpressionIdentifier(node) {
75146 if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
75147 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
75148 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
75149 return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
75150 }
75151 }
75152 return node;
75153 }
75154 function isPartOfClassBody(declaration, node) {
75155 var currentNode = ts.getParseTreeNode(node);
75156 if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
75157 // if the node has no correlation to a parse tree node, its definitely not
75158 // part of the body.
75159 // if the node is outside of the document range of the declaration, its
75160 // definitely not part of the body.
75161 return false;
75162 }
75163 var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
75164 while (currentNode) {
75165 if (currentNode === blockScope || currentNode === declaration) {
75166 // if we are in the enclosing block scope of the declaration, we are definitely
75167 // not inside the class body.
75168 return false;
75169 }
75170 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
75171 return true;
75172 }
75173 currentNode = currentNode.parent;
75174 }
75175 return false;
75176 }
75177 /**
75178 * Substitutes `this` when contained within an arrow function.
75179 *
75180 * @param node The ThisKeyword node.
75181 */
75182 function substituteThisKeyword(node) {
75183 if (enabledSubstitutions & 1 /* CapturedThis */
75184 && hierarchyFacts & 16 /* CapturesThis */) {
75185 return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node);
75186 }
75187 return node;
75188 }
75189 function getClassMemberPrefix(node, member) {
75190 return ts.hasModifier(member, 32 /* Static */)
75191 ? ts.getInternalName(node)
75192 : ts.createPropertyAccess(ts.getInternalName(node), "prototype");
75193 }
75194 function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
75195 if (!constructor || !hasExtendsClause) {
75196 return false;
75197 }
75198 if (ts.some(constructor.parameters)) {
75199 return false;
75200 }
75201 var statement = ts.firstOrUndefined(constructor.body.statements);
75202 if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 221 /* ExpressionStatement */) {
75203 return false;
75204 }
75205 var statementExpression = statement.expression;
75206 if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 191 /* CallExpression */) {
75207 return false;
75208 }
75209 var callTarget = statementExpression.expression;
75210 if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 98 /* SuperKeyword */) {
75211 return false;
75212 }
75213 var callArgument = ts.singleOrUndefined(statementExpression.arguments);
75214 if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 208 /* SpreadElement */) {
75215 return false;
75216 }
75217 var expression = callArgument.expression;
75218 return ts.isIdentifier(expression) && expression.escapedText === "arguments";
75219 }
75220 }
75221 ts.transformES2015 = transformES2015;
75222 function createExtendsHelper(context, name) {
75223 context.requestEmitHelper(ts.extendsHelper);
75224 return ts.createCall(ts.getHelperName("__extends"),
75225 /*typeArguments*/ undefined, [
75226 name,
75227 ts.createFileLevelUniqueName("_super")
75228 ]);
75229 }
75230 function createTemplateObjectHelper(context, cooked, raw) {
75231 context.requestEmitHelper(ts.templateObjectHelper);
75232 return ts.createCall(ts.getHelperName("__makeTemplateObject"),
75233 /*typeArguments*/ undefined, [
75234 cooked,
75235 raw
75236 ]);
75237 }
75238 ts.extendsHelper = {
75239 name: "typescript:extends",
75240 scoped: false,
75241 priority: 0,
75242 text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
75243 };
75244 ts.templateObjectHelper = {
75245 name: "typescript:makeTemplateObject",
75246 scoped: false,
75247 priority: 0,
75248 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 };"
75249 };
75250})(ts || (ts = {}));
75251/*@internal*/
75252var ts;
75253(function (ts) {
75254 /**
75255 * Transforms ES5 syntax into ES3 syntax.
75256 *
75257 * @param context Context and state information for the transformation.
75258 */
75259 function transformES5(context) {
75260 var compilerOptions = context.getCompilerOptions();
75261 // enable emit notification only if using --jsx preserve or react-native
75262 var previousOnEmitNode;
75263 var noSubstitution;
75264 if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
75265 previousOnEmitNode = context.onEmitNode;
75266 context.onEmitNode = onEmitNode;
75267 context.enableEmitNotification(262 /* JsxOpeningElement */);
75268 context.enableEmitNotification(263 /* JsxClosingElement */);
75269 context.enableEmitNotification(261 /* JsxSelfClosingElement */);
75270 noSubstitution = [];
75271 }
75272 var previousOnSubstituteNode = context.onSubstituteNode;
75273 context.onSubstituteNode = onSubstituteNode;
75274 context.enableSubstitution(189 /* PropertyAccessExpression */);
75275 context.enableSubstitution(275 /* PropertyAssignment */);
75276 return ts.chainBundle(transformSourceFile);
75277 /**
75278 * Transforms an ES5 source file to ES3.
75279 *
75280 * @param node A SourceFile
75281 */
75282 function transformSourceFile(node) {
75283 return node;
75284 }
75285 /**
75286 * Called by the printer just before a node is printed.
75287 *
75288 * @param hint A hint as to the intended usage of the node.
75289 * @param node The node to emit.
75290 * @param emitCallback A callback used to emit the node.
75291 */
75292 function onEmitNode(hint, node, emitCallback) {
75293 switch (node.kind) {
75294 case 262 /* JsxOpeningElement */:
75295 case 263 /* JsxClosingElement */:
75296 case 261 /* JsxSelfClosingElement */:
75297 var tagName = node.tagName;
75298 noSubstitution[ts.getOriginalNodeId(tagName)] = true;
75299 break;
75300 }
75301 previousOnEmitNode(hint, node, emitCallback);
75302 }
75303 /**
75304 * Hooks node substitutions.
75305 *
75306 * @param hint A hint as to the intended usage of the node.
75307 * @param node The node to substitute.
75308 */
75309 function onSubstituteNode(hint, node) {
75310 if (node.id && noSubstitution && noSubstitution[node.id]) {
75311 return previousOnSubstituteNode(hint, node);
75312 }
75313 node = previousOnSubstituteNode(hint, node);
75314 if (ts.isPropertyAccessExpression(node)) {
75315 return substitutePropertyAccessExpression(node);
75316 }
75317 else if (ts.isPropertyAssignment(node)) {
75318 return substitutePropertyAssignment(node);
75319 }
75320 return node;
75321 }
75322 /**
75323 * Substitutes a PropertyAccessExpression whose name is a reserved word.
75324 *
75325 * @param node A PropertyAccessExpression
75326 */
75327 function substitutePropertyAccessExpression(node) {
75328 var literalName = trySubstituteReservedName(node.name);
75329 if (literalName) {
75330 return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
75331 }
75332 return node;
75333 }
75334 /**
75335 * Substitutes a PropertyAssignment whose name is a reserved word.
75336 *
75337 * @param node A PropertyAssignment
75338 */
75339 function substitutePropertyAssignment(node) {
75340 var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
75341 if (literalName) {
75342 return ts.updatePropertyAssignment(node, literalName, node.initializer);
75343 }
75344 return node;
75345 }
75346 /**
75347 * If an identifier name is a reserved word, returns a string literal for the name.
75348 *
75349 * @param name An Identifier
75350 */
75351 function trySubstituteReservedName(name) {
75352 var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
75353 if (token !== undefined && token >= 73 /* FirstReservedWord */ && token <= 108 /* LastReservedWord */) {
75354 return ts.setTextRange(ts.createLiteral(name), name);
75355 }
75356 return undefined;
75357 }
75358 }
75359 ts.transformES5 = transformES5;
75360})(ts || (ts = {}));
75361// Transforms generator functions into a compatible ES5 representation with similar runtime
75362// semantics. This is accomplished by first transforming the body of each generator
75363// function into an intermediate representation that is the compiled into a JavaScript
75364// switch statement.
75365//
75366// Many functions in this transformer will contain comments indicating the expected
75367// intermediate representation. For illustrative purposes, the following intermediate
75368// language is used to define this intermediate representation:
75369//
75370// .nop - Performs no operation.
75371// .local NAME, ... - Define local variable declarations.
75372// .mark LABEL - Mark the location of a label.
75373// .br LABEL - Jump to a label. If jumping out of a protected
75374// region, all .finally blocks are executed.
75375// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy.
75376// If jumping out of a protected region, all .finally
75377// blocks are executed.
75378// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey.
75379// If jumping out of a protected region, all .finally
75380// blocks are executed.
75381// .yield (x) - Yield the value of the optional expression `x`.
75382// Resume at the next label.
75383// .yieldstar (x) - Delegate yield to the value of the optional
75384// expression `x`. Resume at the next label.
75385// NOTE: `x` must be an Iterator, not an Iterable.
75386// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or
75387// "break" abrupt completions jump to the CONTINUE or
75388// BREAK labels, respectively.
75389// .endloop - Marks the end of a loop.
75390// .with (x) - Marks the beginning of a WithStatement block, using
75391// the supplied expression.
75392// .endwith - Marks the end of a WithStatement.
75393// .switch - Marks the beginning of a SwitchStatement.
75394// .endswitch - Marks the end of a SwitchStatement.
75395// .labeled NAME - Marks the beginning of a LabeledStatement with the
75396// supplied name.
75397// .endlabeled - Marks the end of a LabeledStatement.
75398// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the
75399// labels for each block.
75400// .catch (x) - Marks the beginning of a catch block.
75401// .finally - Marks the beginning of a finally block.
75402// .endfinally - Marks the end of a finally block.
75403// .endtry - Marks the end of a protected region.
75404// .throw (x) - Throws the value of the expression `x`.
75405// .return (x) - Returns the value of the expression `x`.
75406//
75407// In addition, the illustrative intermediate representation introduces some special
75408// variables:
75409//
75410// %sent% - Either returns the next value sent to the generator,
75411// returns the result of a delegated yield, or throws
75412// the exception sent to the generator.
75413// %error% - Returns the value of the current exception in a
75414// catch block.
75415//
75416// This intermediate representation is then compiled into JavaScript syntax. The resulting
75417// compilation output looks something like the following:
75418//
75419// function f() {
75420// var /*locals*/;
75421// /*functions*/
75422// return __generator(function (state) {
75423// switch (state.label) {
75424// /*cases per label*/
75425// }
75426// });
75427// }
75428//
75429// Each of the above instructions corresponds to JavaScript emit similar to the following:
75430//
75431// .local NAME | var NAME;
75432// -------------------------------|----------------------------------------------
75433// .mark LABEL | case LABEL:
75434// -------------------------------|----------------------------------------------
75435// .br LABEL | return [3 /*break*/, LABEL];
75436// -------------------------------|----------------------------------------------
75437// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL];
75438// -------------------------------|----------------------------------------------
75439// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL];
75440// -------------------------------|----------------------------------------------
75441// .yield (x) | return [4 /*yield*/, x];
75442// .mark RESUME | case RESUME:
75443// a = %sent%; | a = state.sent();
75444// -------------------------------|----------------------------------------------
75445// .yieldstar (x) | return [5 /*yield**/, x];
75446// .mark RESUME | case RESUME:
75447// a = %sent%; | a = state.sent();
75448// -------------------------------|----------------------------------------------
75449// .with (_a) | with (_a) {
75450// a(); | a();
75451// | }
75452// | state.label = LABEL;
75453// .mark LABEL | case LABEL:
75454// | with (_a) {
75455// b(); | b();
75456// | }
75457// .endwith |
75458// -------------------------------|----------------------------------------------
75459// | case 0:
75460// | state.trys = [];
75461// | ...
75462// .try TRY, CATCH, FINALLY, END |
75463// .mark TRY | case TRY:
75464// | state.trys.push([TRY, CATCH, FINALLY, END]);
75465// .nop |
75466// a(); | a();
75467// .br END | return [3 /*break*/, END];
75468// .catch (e) |
75469// .mark CATCH | case CATCH:
75470// | e = state.sent();
75471// b(); | b();
75472// .br END | return [3 /*break*/, END];
75473// .finally |
75474// .mark FINALLY | case FINALLY:
75475// c(); | c();
75476// .endfinally | return [7 /*endfinally*/];
75477// .endtry |
75478// .mark END | case END:
75479/*@internal*/
75480var ts;
75481(function (ts) {
75482 var OpCode;
75483 (function (OpCode) {
75484 OpCode[OpCode["Nop"] = 0] = "Nop";
75485 OpCode[OpCode["Statement"] = 1] = "Statement";
75486 OpCode[OpCode["Assign"] = 2] = "Assign";
75487 OpCode[OpCode["Break"] = 3] = "Break";
75488 OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
75489 OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
75490 OpCode[OpCode["Yield"] = 6] = "Yield";
75491 OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
75492 OpCode[OpCode["Return"] = 8] = "Return";
75493 OpCode[OpCode["Throw"] = 9] = "Throw";
75494 OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
75495 })(OpCode || (OpCode = {}));
75496 // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
75497 var BlockAction;
75498 (function (BlockAction) {
75499 BlockAction[BlockAction["Open"] = 0] = "Open";
75500 BlockAction[BlockAction["Close"] = 1] = "Close";
75501 })(BlockAction || (BlockAction = {}));
75502 // the kind for a generated code block in a FunctionBuilder
75503 var CodeBlockKind;
75504 (function (CodeBlockKind) {
75505 CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
75506 CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
75507 CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
75508 CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
75509 CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
75510 })(CodeBlockKind || (CodeBlockKind = {}));
75511 // the state for a generated code exception block
75512 var ExceptionBlockState;
75513 (function (ExceptionBlockState) {
75514 ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
75515 ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
75516 ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
75517 ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
75518 })(ExceptionBlockState || (ExceptionBlockState = {}));
75519 // NOTE: changes to this enum should be reflected in the __generator helper.
75520 var Instruction;
75521 (function (Instruction) {
75522 Instruction[Instruction["Next"] = 0] = "Next";
75523 Instruction[Instruction["Throw"] = 1] = "Throw";
75524 Instruction[Instruction["Return"] = 2] = "Return";
75525 Instruction[Instruction["Break"] = 3] = "Break";
75526 Instruction[Instruction["Yield"] = 4] = "Yield";
75527 Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
75528 Instruction[Instruction["Catch"] = 6] = "Catch";
75529 Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
75530 })(Instruction || (Instruction = {}));
75531 function getInstructionName(instruction) {
75532 switch (instruction) {
75533 case 2 /* Return */: return "return";
75534 case 3 /* Break */: return "break";
75535 case 4 /* Yield */: return "yield";
75536 case 5 /* YieldStar */: return "yield*";
75537 case 7 /* Endfinally */: return "endfinally";
75538 default: return undefined; // TODO: GH#18217
75539 }
75540 }
75541 function transformGenerators(context) {
75542 var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
75543 var compilerOptions = context.getCompilerOptions();
75544 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
75545 var resolver = context.getEmitResolver();
75546 var previousOnSubstituteNode = context.onSubstituteNode;
75547 context.onSubstituteNode = onSubstituteNode;
75548 var renamedCatchVariables;
75549 var renamedCatchVariableDeclarations;
75550 var inGeneratorFunctionBody;
75551 var inStatementContainingYield;
75552 // The following three arrays store information about generated code blocks.
75553 // All three arrays are correlated by their index. This approach is used over allocating
75554 // objects to store the same information to avoid GC overhead.
75555 //
75556 var blocks; // Information about the code block
75557 var blockOffsets; // The operation offset at which a code block begins or ends
75558 var blockActions; // Whether the code block is opened or closed
75559 var blockStack; // A stack of currently open code blocks
75560 // Labels are used to mark locations in the code that can be the target of a Break (jump)
75561 // operation. These are translated into case clauses in a switch statement.
75562 // The following two arrays are correlated by their index. This approach is used over
75563 // allocating objects to store the same information to avoid GC overhead.
75564 //
75565 var labelOffsets; // The operation offset at which the label is defined.
75566 var labelExpressions; // The NumericLiteral nodes bound to each label.
75567 var nextLabelId = 1; // The next label id to use.
75568 // Operations store information about generated code for the function body. This
75569 // Includes things like statements, assignments, breaks (jumps), and yields.
75570 // The following three arrays are correlated by their index. This approach is used over
75571 // allocating objects to store the same information to avoid GC overhead.
75572 //
75573 var operations; // The operation to perform.
75574 var operationArguments; // The arguments to the operation.
75575 var operationLocations; // The source map location for the operation.
75576 var state; // The name of the state object used by the generator at runtime.
75577 // The following variables store information used by the `build` function:
75578 //
75579 var blockIndex = 0; // The index of the current block.
75580 var labelNumber = 0; // The current label number.
75581 var labelNumbers;
75582 var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
75583 var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
75584 var clauses; // The case clauses generated for labels.
75585 var statements; // The statements for the current label.
75586 var exceptionBlockStack; // A stack of containing exception blocks.
75587 var currentExceptionBlock; // The current exception block.
75588 var withBlockStack; // A stack containing `with` blocks.
75589 return ts.chainBundle(transformSourceFile);
75590 function transformSourceFile(node) {
75591 if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) {
75592 return node;
75593 }
75594 var visited = ts.visitEachChild(node, visitor, context);
75595 ts.addEmitHelpers(visited, context.readEmitHelpers());
75596 return visited;
75597 }
75598 /**
75599 * Visits a node.
75600 *
75601 * @param node The node to visit.
75602 */
75603 function visitor(node) {
75604 var transformFlags = node.transformFlags;
75605 if (inStatementContainingYield) {
75606 return visitJavaScriptInStatementContainingYield(node);
75607 }
75608 else if (inGeneratorFunctionBody) {
75609 return visitJavaScriptInGeneratorFunctionBody(node);
75610 }
75611 else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
75612 return visitGenerator(node);
75613 }
75614 else if (transformFlags & 256 /* ContainsGenerator */) {
75615 return ts.visitEachChild(node, visitor, context);
75616 }
75617 else {
75618 return node;
75619 }
75620 }
75621 /**
75622 * Visits a node that is contained within a statement that contains yield.
75623 *
75624 * @param node The node to visit.
75625 */
75626 function visitJavaScriptInStatementContainingYield(node) {
75627 switch (node.kind) {
75628 case 223 /* DoStatement */:
75629 return visitDoStatement(node);
75630 case 224 /* WhileStatement */:
75631 return visitWhileStatement(node);
75632 case 232 /* SwitchStatement */:
75633 return visitSwitchStatement(node);
75634 case 233 /* LabeledStatement */:
75635 return visitLabeledStatement(node);
75636 default:
75637 return visitJavaScriptInGeneratorFunctionBody(node);
75638 }
75639 }
75640 /**
75641 * Visits a node that is contained within a generator function.
75642 *
75643 * @param node The node to visit.
75644 */
75645 function visitJavaScriptInGeneratorFunctionBody(node) {
75646 switch (node.kind) {
75647 case 239 /* FunctionDeclaration */:
75648 return visitFunctionDeclaration(node);
75649 case 196 /* FunctionExpression */:
75650 return visitFunctionExpression(node);
75651 case 158 /* GetAccessor */:
75652 case 159 /* SetAccessor */:
75653 return visitAccessorDeclaration(node);
75654 case 219 /* VariableStatement */:
75655 return visitVariableStatement(node);
75656 case 225 /* ForStatement */:
75657 return visitForStatement(node);
75658 case 226 /* ForInStatement */:
75659 return visitForInStatement(node);
75660 case 229 /* BreakStatement */:
75661 return visitBreakStatement(node);
75662 case 228 /* ContinueStatement */:
75663 return visitContinueStatement(node);
75664 case 230 /* ReturnStatement */:
75665 return visitReturnStatement(node);
75666 default:
75667 if (node.transformFlags & 131072 /* ContainsYield */) {
75668 return visitJavaScriptContainingYield(node);
75669 }
75670 else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) {
75671 return ts.visitEachChild(node, visitor, context);
75672 }
75673 else {
75674 return node;
75675 }
75676 }
75677 }
75678 /**
75679 * Visits a node that contains a YieldExpression.
75680 *
75681 * @param node The node to visit.
75682 */
75683 function visitJavaScriptContainingYield(node) {
75684 switch (node.kind) {
75685 case 204 /* BinaryExpression */:
75686 return visitBinaryExpression(node);
75687 case 205 /* ConditionalExpression */:
75688 return visitConditionalExpression(node);
75689 case 207 /* YieldExpression */:
75690 return visitYieldExpression(node);
75691 case 187 /* ArrayLiteralExpression */:
75692 return visitArrayLiteralExpression(node);
75693 case 188 /* ObjectLiteralExpression */:
75694 return visitObjectLiteralExpression(node);
75695 case 190 /* ElementAccessExpression */:
75696 return visitElementAccessExpression(node);
75697 case 191 /* CallExpression */:
75698 return visitCallExpression(node);
75699 case 192 /* NewExpression */:
75700 return visitNewExpression(node);
75701 default:
75702 return ts.visitEachChild(node, visitor, context);
75703 }
75704 }
75705 /**
75706 * Visits a generator function.
75707 *
75708 * @param node The node to visit.
75709 */
75710 function visitGenerator(node) {
75711 switch (node.kind) {
75712 case 239 /* FunctionDeclaration */:
75713 return visitFunctionDeclaration(node);
75714 case 196 /* FunctionExpression */:
75715 return visitFunctionExpression(node);
75716 default:
75717 return ts.Debug.failBadSyntaxKind(node);
75718 }
75719 }
75720 /**
75721 * Visits a function declaration.
75722 *
75723 * This will be called when one of the following conditions are met:
75724 * - The function declaration is a generator function.
75725 * - The function declaration is contained within the body of a generator function.
75726 *
75727 * @param node The node to visit.
75728 */
75729 function visitFunctionDeclaration(node) {
75730 // Currently, we only support generators that were originally async functions.
75731 if (node.asteriskToken) {
75732 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
75733 /*decorators*/ undefined, node.modifiers,
75734 /*asteriskToken*/ undefined, node.name,
75735 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
75736 /*type*/ undefined, transformGeneratorFunctionBody(node.body)),
75737 /*location*/ node), node);
75738 }
75739 else {
75740 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
75741 var savedInStatementContainingYield = inStatementContainingYield;
75742 inGeneratorFunctionBody = false;
75743 inStatementContainingYield = false;
75744 node = ts.visitEachChild(node, visitor, context);
75745 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
75746 inStatementContainingYield = savedInStatementContainingYield;
75747 }
75748 if (inGeneratorFunctionBody) {
75749 // Function declarations in a generator function body are hoisted
75750 // to the top of the lexical scope and elided from the current statement.
75751 hoistFunctionDeclaration(node);
75752 return undefined;
75753 }
75754 else {
75755 return node;
75756 }
75757 }
75758 /**
75759 * Visits a function expression.
75760 *
75761 * This will be called when one of the following conditions are met:
75762 * - The function expression is a generator function.
75763 * - The function expression is contained within the body of a generator function.
75764 *
75765 * @param node The node to visit.
75766 */
75767 function visitFunctionExpression(node) {
75768 // Currently, we only support generators that were originally async functions.
75769 if (node.asteriskToken) {
75770 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
75771 /*modifiers*/ undefined,
75772 /*asteriskToken*/ undefined, node.name,
75773 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
75774 /*type*/ undefined, transformGeneratorFunctionBody(node.body)),
75775 /*location*/ node), node);
75776 }
75777 else {
75778 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
75779 var savedInStatementContainingYield = inStatementContainingYield;
75780 inGeneratorFunctionBody = false;
75781 inStatementContainingYield = false;
75782 node = ts.visitEachChild(node, visitor, context);
75783 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
75784 inStatementContainingYield = savedInStatementContainingYield;
75785 }
75786 return node;
75787 }
75788 /**
75789 * Visits a get or set accessor declaration.
75790 *
75791 * This will be called when one of the following conditions are met:
75792 * - The accessor is contained within the body of a generator function.
75793 *
75794 * @param node The node to visit.
75795 */
75796 function visitAccessorDeclaration(node) {
75797 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
75798 var savedInStatementContainingYield = inStatementContainingYield;
75799 inGeneratorFunctionBody = false;
75800 inStatementContainingYield = false;
75801 node = ts.visitEachChild(node, visitor, context);
75802 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
75803 inStatementContainingYield = savedInStatementContainingYield;
75804 return node;
75805 }
75806 /**
75807 * Transforms the body of a generator function declaration.
75808 *
75809 * @param node The function body to transform.
75810 */
75811 function transformGeneratorFunctionBody(body) {
75812 // Save existing generator state
75813 var statements = [];
75814 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
75815 var savedInStatementContainingYield = inStatementContainingYield;
75816 var savedBlocks = blocks;
75817 var savedBlockOffsets = blockOffsets;
75818 var savedBlockActions = blockActions;
75819 var savedBlockStack = blockStack;
75820 var savedLabelOffsets = labelOffsets;
75821 var savedLabelExpressions = labelExpressions;
75822 var savedNextLabelId = nextLabelId;
75823 var savedOperations = operations;
75824 var savedOperationArguments = operationArguments;
75825 var savedOperationLocations = operationLocations;
75826 var savedState = state;
75827 // Initialize generator state
75828 inGeneratorFunctionBody = true;
75829 inStatementContainingYield = false;
75830 blocks = undefined;
75831 blockOffsets = undefined;
75832 blockActions = undefined;
75833 blockStack = undefined;
75834 labelOffsets = undefined;
75835 labelExpressions = undefined;
75836 nextLabelId = 1;
75837 operations = undefined;
75838 operationArguments = undefined;
75839 operationLocations = undefined;
75840 state = ts.createTempVariable(/*recordTempVariable*/ undefined);
75841 // Build the generator
75842 resumeLexicalEnvironment();
75843 var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
75844 transformAndEmitStatements(body.statements, statementOffset);
75845 var buildResult = build();
75846 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
75847 statements.push(ts.createReturn(buildResult));
75848 // Restore previous generator state
75849 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
75850 inStatementContainingYield = savedInStatementContainingYield;
75851 blocks = savedBlocks;
75852 blockOffsets = savedBlockOffsets;
75853 blockActions = savedBlockActions;
75854 blockStack = savedBlockStack;
75855 labelOffsets = savedLabelOffsets;
75856 labelExpressions = savedLabelExpressions;
75857 nextLabelId = savedNextLabelId;
75858 operations = savedOperations;
75859 operationArguments = savedOperationArguments;
75860 operationLocations = savedOperationLocations;
75861 state = savedState;
75862 return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
75863 }
75864 /**
75865 * Visits a variable statement.
75866 *
75867 * This will be called when one of the following conditions are met:
75868 * - The variable statement is contained within the body of a generator function.
75869 *
75870 * @param node The node to visit.
75871 */
75872 function visitVariableStatement(node) {
75873 if (node.transformFlags & 131072 /* ContainsYield */) {
75874 transformAndEmitVariableDeclarationList(node.declarationList);
75875 return undefined;
75876 }
75877 else {
75878 // Do not hoist custom prologues.
75879 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
75880 return node;
75881 }
75882 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
75883 var variable = _a[_i];
75884 hoistVariableDeclaration(variable.name);
75885 }
75886 var variables = ts.getInitializedVariables(node.declarationList);
75887 if (variables.length === 0) {
75888 return undefined;
75889 }
75890 return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
75891 }
75892 }
75893 /**
75894 * Visits a binary expression.
75895 *
75896 * This will be called when one of the following conditions are met:
75897 * - The node contains a YieldExpression.
75898 *
75899 * @param node The node to visit.
75900 */
75901 function visitBinaryExpression(node) {
75902 var assoc = ts.getExpressionAssociativity(node);
75903 switch (assoc) {
75904 case 0 /* Left */:
75905 return visitLeftAssociativeBinaryExpression(node);
75906 case 1 /* Right */:
75907 return visitRightAssociativeBinaryExpression(node);
75908 default:
75909 return ts.Debug.assertNever(assoc);
75910 }
75911 }
75912 function isCompoundAssignment(kind) {
75913 return kind >= 60 /* FirstCompoundAssignment */
75914 && kind <= 71 /* LastCompoundAssignment */;
75915 }
75916 function getOperatorForCompoundAssignment(kind) {
75917 switch (kind) {
75918 case 60 /* PlusEqualsToken */: return 38 /* PlusToken */;
75919 case 61 /* MinusEqualsToken */: return 39 /* MinusToken */;
75920 case 62 /* AsteriskEqualsToken */: return 40 /* AsteriskToken */;
75921 case 63 /* AsteriskAsteriskEqualsToken */: return 41 /* AsteriskAsteriskToken */;
75922 case 64 /* SlashEqualsToken */: return 42 /* SlashToken */;
75923 case 65 /* PercentEqualsToken */: return 43 /* PercentToken */;
75924 case 66 /* LessThanLessThanEqualsToken */: return 46 /* LessThanLessThanToken */;
75925 case 67 /* GreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanToken */;
75926 case 68 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanGreaterThanToken */;
75927 case 69 /* AmpersandEqualsToken */: return 49 /* AmpersandToken */;
75928 case 70 /* BarEqualsToken */: return 50 /* BarToken */;
75929 case 71 /* CaretEqualsToken */: return 51 /* CaretToken */;
75930 }
75931 }
75932 /**
75933 * Visits a right-associative binary expression containing `yield`.
75934 *
75935 * @param node The node to visit.
75936 */
75937 function visitRightAssociativeBinaryExpression(node) {
75938 var left = node.left, right = node.right;
75939 if (containsYield(right)) {
75940 var target = void 0;
75941 switch (left.kind) {
75942 case 189 /* PropertyAccessExpression */:
75943 // [source]
75944 // a.b = yield;
75945 //
75946 // [intermediate]
75947 // .local _a
75948 // _a = a;
75949 // .yield resumeLabel
75950 // .mark resumeLabel
75951 // _a.b = %sent%;
75952 target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
75953 break;
75954 case 190 /* ElementAccessExpression */:
75955 // [source]
75956 // a[b] = yield;
75957 //
75958 // [intermediate]
75959 // .local _a, _b
75960 // _a = a;
75961 // _b = b;
75962 // .yield resumeLabel
75963 // .mark resumeLabel
75964 // _a[_b] = %sent%;
75965 target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
75966 break;
75967 default:
75968 target = ts.visitNode(left, visitor, ts.isExpression);
75969 break;
75970 }
75971 var operator = node.operatorToken.kind;
75972 if (isCompoundAssignment(operator)) {
75973 return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
75974 }
75975 else {
75976 return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression));
75977 }
75978 }
75979 return ts.visitEachChild(node, visitor, context);
75980 }
75981 function visitLeftAssociativeBinaryExpression(node) {
75982 if (containsYield(node.right)) {
75983 if (ts.isLogicalOperator(node.operatorToken.kind)) {
75984 return visitLogicalBinaryExpression(node);
75985 }
75986 else if (node.operatorToken.kind === 27 /* CommaToken */) {
75987 return visitCommaExpression(node);
75988 }
75989 // [source]
75990 // a() + (yield) + c()
75991 //
75992 // [intermediate]
75993 // .local _a
75994 // _a = a();
75995 // .yield resumeLabel
75996 // _a + %sent% + c()
75997 var clone_5 = ts.getMutableClone(node);
75998 clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
75999 clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression);
76000 return clone_5;
76001 }
76002 return ts.visitEachChild(node, visitor, context);
76003 }
76004 /**
76005 * Visits a logical binary expression containing `yield`.
76006 *
76007 * @param node A node to visit.
76008 */
76009 function visitLogicalBinaryExpression(node) {
76010 // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
76011 // to be transformed as such:
76012 //
76013 // [source]
76014 // x = a() && yield;
76015 //
76016 // [intermediate]
76017 // .local _a
76018 // _a = a();
76019 // .brfalse resultLabel, (_a)
76020 // .yield resumeLabel
76021 // .mark resumeLabel
76022 // _a = %sent%;
76023 // .mark resultLabel
76024 // x = _a;
76025 //
76026 // [source]
76027 // x = a() || yield;
76028 //
76029 // [intermediate]
76030 // .local _a
76031 // _a = a();
76032 // .brtrue resultLabel, (_a)
76033 // .yield resumeLabel
76034 // .mark resumeLabel
76035 // _a = %sent%;
76036 // .mark resultLabel
76037 // x = _a;
76038 var resultLabel = defineLabel();
76039 var resultLocal = declareLocal();
76040 emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
76041 if (node.operatorToken.kind === 54 /* AmpersandAmpersandToken */) {
76042 // Logical `&&` shortcuts when the left-hand operand is falsey.
76043 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
76044 }
76045 else {
76046 // Logical `||` shortcuts when the left-hand operand is truthy.
76047 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
76048 }
76049 emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
76050 markLabel(resultLabel);
76051 return resultLocal;
76052 }
76053 /**
76054 * Visits a comma expression containing `yield`.
76055 *
76056 * @param node The node to visit.
76057 */
76058 function visitCommaExpression(node) {
76059 // [source]
76060 // x = a(), yield, b();
76061 //
76062 // [intermediate]
76063 // a();
76064 // .yield resumeLabel
76065 // .mark resumeLabel
76066 // x = %sent%, b();
76067 var pendingExpressions = [];
76068 visit(node.left);
76069 visit(node.right);
76070 return ts.inlineExpressions(pendingExpressions);
76071 function visit(node) {
76072 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
76073 visit(node.left);
76074 visit(node.right);
76075 }
76076 else {
76077 if (containsYield(node) && pendingExpressions.length > 0) {
76078 emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]);
76079 pendingExpressions = [];
76080 }
76081 pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
76082 }
76083 }
76084 }
76085 /**
76086 * Visits a conditional expression containing `yield`.
76087 *
76088 * @param node The node to visit.
76089 */
76090 function visitConditionalExpression(node) {
76091 // [source]
76092 // x = a() ? yield : b();
76093 //
76094 // [intermediate]
76095 // .local _a
76096 // .brfalse whenFalseLabel, (a())
76097 // .yield resumeLabel
76098 // .mark resumeLabel
76099 // _a = %sent%;
76100 // .br resultLabel
76101 // .mark whenFalseLabel
76102 // _a = b();
76103 // .mark resultLabel
76104 // x = _a;
76105 // We only need to perform a specific transformation if a `yield` expression exists
76106 // in either the `whenTrue` or `whenFalse` branches.
76107 // A `yield` in the condition will be handled by the normal visitor.
76108 if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
76109 var whenFalseLabel = defineLabel();
76110 var resultLabel = defineLabel();
76111 var resultLocal = declareLocal();
76112 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
76113 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
76114 emitBreak(resultLabel);
76115 markLabel(whenFalseLabel);
76116 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
76117 markLabel(resultLabel);
76118 return resultLocal;
76119 }
76120 return ts.visitEachChild(node, visitor, context);
76121 }
76122 /**
76123 * Visits a `yield` expression.
76124 *
76125 * @param node The node to visit.
76126 */
76127 function visitYieldExpression(node) {
76128 // [source]
76129 // x = yield a();
76130 //
76131 // [intermediate]
76132 // .yield resumeLabel, (a())
76133 // .mark resumeLabel
76134 // x = %sent%;
76135 var resumeLabel = defineLabel();
76136 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
76137 if (node.asteriskToken) {
76138 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
76139 ? ts.createValuesHelper(context, expression, /*location*/ node)
76140 : expression;
76141 emitYieldStar(iterator, /*location*/ node);
76142 }
76143 else {
76144 emitYield(expression, /*location*/ node);
76145 }
76146 markLabel(resumeLabel);
76147 return createGeneratorResume(/*location*/ node);
76148 }
76149 /**
76150 * Visits an ArrayLiteralExpression that contains a YieldExpression.
76151 *
76152 * @param node The node to visit.
76153 */
76154 function visitArrayLiteralExpression(node) {
76155 return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
76156 }
76157 /**
76158 * Visits an array of expressions containing one or more YieldExpression nodes
76159 * and returns an expression for the resulting value.
76160 *
76161 * @param elements The elements to visit.
76162 * @param multiLine Whether array literals created should be emitted on multiple lines.
76163 */
76164 function visitElements(elements, leadingElement, location, multiLine) {
76165 // [source]
76166 // ar = [1, yield, 2];
76167 //
76168 // [intermediate]
76169 // .local _a
76170 // _a = [1];
76171 // .yield resumeLabel
76172 // .mark resumeLabel
76173 // ar = _a.concat([%sent%, 2]);
76174 var numInitialElements = countInitialNodesWithoutYield(elements);
76175 var temp;
76176 if (numInitialElements > 0) {
76177 temp = declareLocal();
76178 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
76179 emitAssignment(temp, ts.createArrayLiteral(leadingElement
76180 ? [leadingElement].concat(initialElements) : initialElements));
76181 leadingElement = undefined;
76182 }
76183 var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
76184 return temp
76185 ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
76186 : ts.setTextRange(ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine), location);
76187 function reduceElement(expressions, element) {
76188 if (containsYield(element) && expressions.length > 0) {
76189 var hasAssignedTemp = temp !== undefined;
76190 if (!temp) {
76191 temp = declareLocal();
76192 }
76193 emitAssignment(temp, hasAssignedTemp
76194 ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
76195 : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine));
76196 leadingElement = undefined;
76197 expressions = [];
76198 }
76199 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
76200 return expressions;
76201 }
76202 }
76203 function visitObjectLiteralExpression(node) {
76204 // [source]
76205 // o = {
76206 // a: 1,
76207 // b: yield,
76208 // c: 2
76209 // };
76210 //
76211 // [intermediate]
76212 // .local _a
76213 // _a = {
76214 // a: 1
76215 // };
76216 // .yield resumeLabel
76217 // .mark resumeLabel
76218 // o = (_a.b = %sent%,
76219 // _a.c = 2,
76220 // _a);
76221 var properties = node.properties;
76222 var multiLine = node.multiLine;
76223 var numInitialProperties = countInitialNodesWithoutYield(properties);
76224 var temp = declareLocal();
76225 emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
76226 var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
76227 expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
76228 return ts.inlineExpressions(expressions);
76229 function reduceProperty(expressions, property) {
76230 if (containsYield(property) && expressions.length > 0) {
76231 emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions)));
76232 expressions = [];
76233 }
76234 var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp);
76235 var visited = ts.visitNode(expression, visitor, ts.isExpression);
76236 if (visited) {
76237 if (multiLine) {
76238 ts.startOnNewLine(visited);
76239 }
76240 expressions.push(visited);
76241 }
76242 return expressions;
76243 }
76244 }
76245 /**
76246 * Visits an ElementAccessExpression that contains a YieldExpression.
76247 *
76248 * @param node The node to visit.
76249 */
76250 function visitElementAccessExpression(node) {
76251 if (containsYield(node.argumentExpression)) {
76252 // [source]
76253 // a = x[yield];
76254 //
76255 // [intermediate]
76256 // .local _a
76257 // _a = x;
76258 // .yield resumeLabel
76259 // .mark resumeLabel
76260 // a = _a[%sent%]
76261 var clone_6 = ts.getMutableClone(node);
76262 clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
76263 clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
76264 return clone_6;
76265 }
76266 return ts.visitEachChild(node, visitor, context);
76267 }
76268 function visitCallExpression(node) {
76269 if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
76270 // [source]
76271 // a.b(1, yield, 2);
76272 //
76273 // [intermediate]
76274 // .local _a, _b, _c
76275 // _b = (_a = a).b;
76276 // _c = [1];
76277 // .yield resumeLabel
76278 // .mark resumeLabel
76279 // _b.apply(_a, _c.concat([%sent%, 2]));
76280 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
76281 return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments),
76282 /*location*/ node), node);
76283 }
76284 return ts.visitEachChild(node, visitor, context);
76285 }
76286 function visitNewExpression(node) {
76287 if (ts.forEach(node.arguments, containsYield)) {
76288 // [source]
76289 // new a.b(1, yield, 2);
76290 //
76291 // [intermediate]
76292 // .local _a, _b, _c
76293 // _b = (_a = a.b).bind;
76294 // _c = [1];
76295 // .yield resumeLabel
76296 // .mark resumeLabel
76297 // new (_b.apply(_a, _c.concat([%sent%, 2])));
76298 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
76299 return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments,
76300 /*leadingElement*/ ts.createVoidZero())),
76301 /*typeArguments*/ undefined, []), node), node);
76302 }
76303 return ts.visitEachChild(node, visitor, context);
76304 }
76305 function transformAndEmitStatements(statements, start) {
76306 if (start === void 0) { start = 0; }
76307 var numStatements = statements.length;
76308 for (var i = start; i < numStatements; i++) {
76309 transformAndEmitStatement(statements[i]);
76310 }
76311 }
76312 function transformAndEmitEmbeddedStatement(node) {
76313 if (ts.isBlock(node)) {
76314 transformAndEmitStatements(node.statements);
76315 }
76316 else {
76317 transformAndEmitStatement(node);
76318 }
76319 }
76320 function transformAndEmitStatement(node) {
76321 var savedInStatementContainingYield = inStatementContainingYield;
76322 if (!inStatementContainingYield) {
76323 inStatementContainingYield = containsYield(node);
76324 }
76325 transformAndEmitStatementWorker(node);
76326 inStatementContainingYield = savedInStatementContainingYield;
76327 }
76328 function transformAndEmitStatementWorker(node) {
76329 switch (node.kind) {
76330 case 218 /* Block */:
76331 return transformAndEmitBlock(node);
76332 case 221 /* ExpressionStatement */:
76333 return transformAndEmitExpressionStatement(node);
76334 case 222 /* IfStatement */:
76335 return transformAndEmitIfStatement(node);
76336 case 223 /* DoStatement */:
76337 return transformAndEmitDoStatement(node);
76338 case 224 /* WhileStatement */:
76339 return transformAndEmitWhileStatement(node);
76340 case 225 /* ForStatement */:
76341 return transformAndEmitForStatement(node);
76342 case 226 /* ForInStatement */:
76343 return transformAndEmitForInStatement(node);
76344 case 228 /* ContinueStatement */:
76345 return transformAndEmitContinueStatement(node);
76346 case 229 /* BreakStatement */:
76347 return transformAndEmitBreakStatement(node);
76348 case 230 /* ReturnStatement */:
76349 return transformAndEmitReturnStatement(node);
76350 case 231 /* WithStatement */:
76351 return transformAndEmitWithStatement(node);
76352 case 232 /* SwitchStatement */:
76353 return transformAndEmitSwitchStatement(node);
76354 case 233 /* LabeledStatement */:
76355 return transformAndEmitLabeledStatement(node);
76356 case 234 /* ThrowStatement */:
76357 return transformAndEmitThrowStatement(node);
76358 case 235 /* TryStatement */:
76359 return transformAndEmitTryStatement(node);
76360 default:
76361 return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76362 }
76363 }
76364 function transformAndEmitBlock(node) {
76365 if (containsYield(node)) {
76366 transformAndEmitStatements(node.statements);
76367 }
76368 else {
76369 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76370 }
76371 }
76372 function transformAndEmitExpressionStatement(node) {
76373 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76374 }
76375 function transformAndEmitVariableDeclarationList(node) {
76376 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
76377 var variable = _a[_i];
76378 var name = ts.getSynthesizedClone(variable.name);
76379 ts.setCommentRange(name, variable.name);
76380 hoistVariableDeclaration(name);
76381 }
76382 var variables = ts.getInitializedVariables(node);
76383 var numVariables = variables.length;
76384 var variablesWritten = 0;
76385 var pendingExpressions = [];
76386 while (variablesWritten < numVariables) {
76387 for (var i = variablesWritten; i < numVariables; i++) {
76388 var variable = variables[i];
76389 if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
76390 break;
76391 }
76392 pendingExpressions.push(transformInitializedVariable(variable));
76393 }
76394 if (pendingExpressions.length) {
76395 emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
76396 variablesWritten += pendingExpressions.length;
76397 pendingExpressions = [];
76398 }
76399 }
76400 return undefined;
76401 }
76402 function transformInitializedVariable(node) {
76403 return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
76404 }
76405 function transformAndEmitIfStatement(node) {
76406 if (containsYield(node)) {
76407 // [source]
76408 // if (x)
76409 // /*thenStatement*/
76410 // else
76411 // /*elseStatement*/
76412 //
76413 // [intermediate]
76414 // .brfalse elseLabel, (x)
76415 // /*thenStatement*/
76416 // .br endLabel
76417 // .mark elseLabel
76418 // /*elseStatement*/
76419 // .mark endLabel
76420 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
76421 var endLabel = defineLabel();
76422 var elseLabel = node.elseStatement ? defineLabel() : undefined;
76423 emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
76424 transformAndEmitEmbeddedStatement(node.thenStatement);
76425 if (node.elseStatement) {
76426 emitBreak(endLabel);
76427 markLabel(elseLabel);
76428 transformAndEmitEmbeddedStatement(node.elseStatement);
76429 }
76430 markLabel(endLabel);
76431 }
76432 else {
76433 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76434 }
76435 }
76436 else {
76437 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76438 }
76439 }
76440 function transformAndEmitDoStatement(node) {
76441 if (containsYield(node)) {
76442 // [source]
76443 // do {
76444 // /*body*/
76445 // }
76446 // while (i < 10);
76447 //
76448 // [intermediate]
76449 // .loop conditionLabel, endLabel
76450 // .mark loopLabel
76451 // /*body*/
76452 // .mark conditionLabel
76453 // .brtrue loopLabel, (i < 10)
76454 // .endloop
76455 // .mark endLabel
76456 var conditionLabel = defineLabel();
76457 var loopLabel = defineLabel();
76458 beginLoopBlock(/*continueLabel*/ conditionLabel);
76459 markLabel(loopLabel);
76460 transformAndEmitEmbeddedStatement(node.statement);
76461 markLabel(conditionLabel);
76462 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
76463 endLoopBlock();
76464 }
76465 else {
76466 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76467 }
76468 }
76469 function visitDoStatement(node) {
76470 if (inStatementContainingYield) {
76471 beginScriptLoopBlock();
76472 node = ts.visitEachChild(node, visitor, context);
76473 endLoopBlock();
76474 return node;
76475 }
76476 else {
76477 return ts.visitEachChild(node, visitor, context);
76478 }
76479 }
76480 function transformAndEmitWhileStatement(node) {
76481 if (containsYield(node)) {
76482 // [source]
76483 // while (i < 10) {
76484 // /*body*/
76485 // }
76486 //
76487 // [intermediate]
76488 // .loop loopLabel, endLabel
76489 // .mark loopLabel
76490 // .brfalse endLabel, (i < 10)
76491 // /*body*/
76492 // .br loopLabel
76493 // .endloop
76494 // .mark endLabel
76495 var loopLabel = defineLabel();
76496 var endLabel = beginLoopBlock(loopLabel);
76497 markLabel(loopLabel);
76498 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
76499 transformAndEmitEmbeddedStatement(node.statement);
76500 emitBreak(loopLabel);
76501 endLoopBlock();
76502 }
76503 else {
76504 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76505 }
76506 }
76507 function visitWhileStatement(node) {
76508 if (inStatementContainingYield) {
76509 beginScriptLoopBlock();
76510 node = ts.visitEachChild(node, visitor, context);
76511 endLoopBlock();
76512 return node;
76513 }
76514 else {
76515 return ts.visitEachChild(node, visitor, context);
76516 }
76517 }
76518 function transformAndEmitForStatement(node) {
76519 if (containsYield(node)) {
76520 // [source]
76521 // for (var i = 0; i < 10; i++) {
76522 // /*body*/
76523 // }
76524 //
76525 // [intermediate]
76526 // .local i
76527 // i = 0;
76528 // .loop incrementLabel, endLoopLabel
76529 // .mark conditionLabel
76530 // .brfalse endLoopLabel, (i < 10)
76531 // /*body*/
76532 // .mark incrementLabel
76533 // i++;
76534 // .br conditionLabel
76535 // .endloop
76536 // .mark endLoopLabel
76537 var conditionLabel = defineLabel();
76538 var incrementLabel = defineLabel();
76539 var endLabel = beginLoopBlock(incrementLabel);
76540 if (node.initializer) {
76541 var initializer = node.initializer;
76542 if (ts.isVariableDeclarationList(initializer)) {
76543 transformAndEmitVariableDeclarationList(initializer);
76544 }
76545 else {
76546 emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
76547 }
76548 }
76549 markLabel(conditionLabel);
76550 if (node.condition) {
76551 emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
76552 }
76553 transformAndEmitEmbeddedStatement(node.statement);
76554 markLabel(incrementLabel);
76555 if (node.incrementor) {
76556 emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
76557 }
76558 emitBreak(conditionLabel);
76559 endLoopBlock();
76560 }
76561 else {
76562 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76563 }
76564 }
76565 function visitForStatement(node) {
76566 if (inStatementContainingYield) {
76567 beginScriptLoopBlock();
76568 }
76569 var initializer = node.initializer;
76570 if (initializer && ts.isVariableDeclarationList(initializer)) {
76571 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
76572 var variable = _a[_i];
76573 hoistVariableDeclaration(variable.name);
76574 }
76575 var variables = ts.getInitializedVariables(initializer);
76576 node = ts.updateFor(node, variables.length > 0
76577 ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable))
76578 : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
76579 }
76580 else {
76581 node = ts.visitEachChild(node, visitor, context);
76582 }
76583 if (inStatementContainingYield) {
76584 endLoopBlock();
76585 }
76586 return node;
76587 }
76588 function transformAndEmitForInStatement(node) {
76589 // TODO(rbuckton): Source map locations
76590 if (containsYield(node)) {
76591 // [source]
76592 // for (var p in o) {
76593 // /*body*/
76594 // }
76595 //
76596 // [intermediate]
76597 // .local _a, _b, _i
76598 // _a = [];
76599 // for (_b in o) _a.push(_b);
76600 // _i = 0;
76601 // .loop incrementLabel, endLoopLabel
76602 // .mark conditionLabel
76603 // .brfalse endLoopLabel, (_i < _a.length)
76604 // p = _a[_i];
76605 // /*body*/
76606 // .mark incrementLabel
76607 // _b++;
76608 // .br conditionLabel
76609 // .endloop
76610 // .mark endLoopLabel
76611 var keysArray = declareLocal(); // _a
76612 var key = declareLocal(); // _b
76613 var keysIndex = ts.createLoopVariable(); // _i
76614 var initializer = node.initializer;
76615 hoistVariableDeclaration(keysIndex);
76616 emitAssignment(keysArray, ts.createArrayLiteral());
76617 emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"),
76618 /*typeArguments*/ undefined, [key]))));
76619 emitAssignment(keysIndex, ts.createLiteral(0));
76620 var conditionLabel = defineLabel();
76621 var incrementLabel = defineLabel();
76622 var endLabel = beginLoopBlock(incrementLabel);
76623 markLabel(conditionLabel);
76624 emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length")));
76625 var variable = void 0;
76626 if (ts.isVariableDeclarationList(initializer)) {
76627 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
76628 var variable_1 = _a[_i];
76629 hoistVariableDeclaration(variable_1.name);
76630 }
76631 variable = ts.getSynthesizedClone(initializer.declarations[0].name);
76632 }
76633 else {
76634 variable = ts.visitNode(initializer, visitor, ts.isExpression);
76635 ts.Debug.assert(ts.isLeftHandSideExpression(variable));
76636 }
76637 emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex));
76638 transformAndEmitEmbeddedStatement(node.statement);
76639 markLabel(incrementLabel);
76640 emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex)));
76641 emitBreak(conditionLabel);
76642 endLoopBlock();
76643 }
76644 else {
76645 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76646 }
76647 }
76648 function visitForInStatement(node) {
76649 // [source]
76650 // for (var x in a) {
76651 // /*body*/
76652 // }
76653 //
76654 // [intermediate]
76655 // .local x
76656 // .loop
76657 // for (x in a) {
76658 // /*body*/
76659 // }
76660 // .endloop
76661 if (inStatementContainingYield) {
76662 beginScriptLoopBlock();
76663 }
76664 var initializer = node.initializer;
76665 if (ts.isVariableDeclarationList(initializer)) {
76666 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
76667 var variable = _a[_i];
76668 hoistVariableDeclaration(variable.name);
76669 }
76670 node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
76671 }
76672 else {
76673 node = ts.visitEachChild(node, visitor, context);
76674 }
76675 if (inStatementContainingYield) {
76676 endLoopBlock();
76677 }
76678 return node;
76679 }
76680 function transformAndEmitContinueStatement(node) {
76681 var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
76682 if (label > 0) {
76683 emitBreak(label, /*location*/ node);
76684 }
76685 else {
76686 // invalid continue without a containing loop. Leave the node as is, per #17875.
76687 emitStatement(node);
76688 }
76689 }
76690 function visitContinueStatement(node) {
76691 if (inStatementContainingYield) {
76692 var label = findContinueTarget(node.label && ts.idText(node.label));
76693 if (label > 0) {
76694 return createInlineBreak(label, /*location*/ node);
76695 }
76696 }
76697 return ts.visitEachChild(node, visitor, context);
76698 }
76699 function transformAndEmitBreakStatement(node) {
76700 var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
76701 if (label > 0) {
76702 emitBreak(label, /*location*/ node);
76703 }
76704 else {
76705 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
76706 emitStatement(node);
76707 }
76708 }
76709 function visitBreakStatement(node) {
76710 if (inStatementContainingYield) {
76711 var label = findBreakTarget(node.label && ts.idText(node.label));
76712 if (label > 0) {
76713 return createInlineBreak(label, /*location*/ node);
76714 }
76715 }
76716 return ts.visitEachChild(node, visitor, context);
76717 }
76718 function transformAndEmitReturnStatement(node) {
76719 emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression),
76720 /*location*/ node);
76721 }
76722 function visitReturnStatement(node) {
76723 return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression),
76724 /*location*/ node);
76725 }
76726 function transformAndEmitWithStatement(node) {
76727 if (containsYield(node)) {
76728 // [source]
76729 // with (x) {
76730 // /*body*/
76731 // }
76732 //
76733 // [intermediate]
76734 // .with (x)
76735 // /*body*/
76736 // .endwith
76737 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
76738 transformAndEmitEmbeddedStatement(node.statement);
76739 endWithBlock();
76740 }
76741 else {
76742 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76743 }
76744 }
76745 function transformAndEmitSwitchStatement(node) {
76746 if (containsYield(node.caseBlock)) {
76747 // [source]
76748 // switch (x) {
76749 // case a:
76750 // /*caseStatements*/
76751 // case b:
76752 // /*caseStatements*/
76753 // default:
76754 // /*defaultStatements*/
76755 // }
76756 //
76757 // [intermediate]
76758 // .local _a
76759 // .switch endLabel
76760 // _a = x;
76761 // switch (_a) {
76762 // case a:
76763 // .br clauseLabels[0]
76764 // }
76765 // switch (_a) {
76766 // case b:
76767 // .br clauseLabels[1]
76768 // }
76769 // .br clauseLabels[2]
76770 // .mark clauseLabels[0]
76771 // /*caseStatements*/
76772 // .mark clauseLabels[1]
76773 // /*caseStatements*/
76774 // .mark clauseLabels[2]
76775 // /*caseStatements*/
76776 // .endswitch
76777 // .mark endLabel
76778 var caseBlock = node.caseBlock;
76779 var numClauses = caseBlock.clauses.length;
76780 var endLabel = beginSwitchBlock();
76781 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
76782 // Create labels for each clause and find the index of the first default clause.
76783 var clauseLabels = [];
76784 var defaultClauseIndex = -1;
76785 for (var i = 0; i < numClauses; i++) {
76786 var clause = caseBlock.clauses[i];
76787 clauseLabels.push(defineLabel());
76788 if (clause.kind === 272 /* DefaultClause */ && defaultClauseIndex === -1) {
76789 defaultClauseIndex = i;
76790 }
76791 }
76792 // Emit switch statements for each run of case clauses either from the first case
76793 // clause or the next case clause with a `yield` in its expression, up to the next
76794 // case clause with a `yield` in its expression.
76795 var clausesWritten = 0;
76796 var pendingClauses = [];
76797 while (clausesWritten < numClauses) {
76798 var defaultClausesSkipped = 0;
76799 for (var i = clausesWritten; i < numClauses; i++) {
76800 var clause = caseBlock.clauses[i];
76801 if (clause.kind === 271 /* CaseClause */) {
76802 if (containsYield(clause.expression) && pendingClauses.length > 0) {
76803 break;
76804 }
76805 pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
76806 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
76807 ]));
76808 }
76809 else {
76810 defaultClausesSkipped++;
76811 }
76812 }
76813 if (pendingClauses.length) {
76814 emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses)));
76815 clausesWritten += pendingClauses.length;
76816 pendingClauses = [];
76817 }
76818 if (defaultClausesSkipped > 0) {
76819 clausesWritten += defaultClausesSkipped;
76820 defaultClausesSkipped = 0;
76821 }
76822 }
76823 if (defaultClauseIndex >= 0) {
76824 emitBreak(clauseLabels[defaultClauseIndex]);
76825 }
76826 else {
76827 emitBreak(endLabel);
76828 }
76829 for (var i = 0; i < numClauses; i++) {
76830 markLabel(clauseLabels[i]);
76831 transformAndEmitStatements(caseBlock.clauses[i].statements);
76832 }
76833 endSwitchBlock();
76834 }
76835 else {
76836 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76837 }
76838 }
76839 function visitSwitchStatement(node) {
76840 if (inStatementContainingYield) {
76841 beginScriptSwitchBlock();
76842 }
76843 node = ts.visitEachChild(node, visitor, context);
76844 if (inStatementContainingYield) {
76845 endSwitchBlock();
76846 }
76847 return node;
76848 }
76849 function transformAndEmitLabeledStatement(node) {
76850 if (containsYield(node)) {
76851 // [source]
76852 // x: {
76853 // /*body*/
76854 // }
76855 //
76856 // [intermediate]
76857 // .labeled "x", endLabel
76858 // /*body*/
76859 // .endlabeled
76860 // .mark endLabel
76861 beginLabeledBlock(ts.idText(node.label));
76862 transformAndEmitEmbeddedStatement(node.statement);
76863 endLabeledBlock();
76864 }
76865 else {
76866 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
76867 }
76868 }
76869 function visitLabeledStatement(node) {
76870 if (inStatementContainingYield) {
76871 beginScriptLabeledBlock(ts.idText(node.label));
76872 }
76873 node = ts.visitEachChild(node, visitor, context);
76874 if (inStatementContainingYield) {
76875 endLabeledBlock();
76876 }
76877 return node;
76878 }
76879 function transformAndEmitThrowStatement(node) {
76880 emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression),
76881 /*location*/ node);
76882 }
76883 function transformAndEmitTryStatement(node) {
76884 if (containsYield(node)) {
76885 // [source]
76886 // try {
76887 // /*tryBlock*/
76888 // }
76889 // catch (e) {
76890 // /*catchBlock*/
76891 // }
76892 // finally {
76893 // /*finallyBlock*/
76894 // }
76895 //
76896 // [intermediate]
76897 // .local _a
76898 // .try tryLabel, catchLabel, finallyLabel, endLabel
76899 // .mark tryLabel
76900 // .nop
76901 // /*tryBlock*/
76902 // .br endLabel
76903 // .catch
76904 // .mark catchLabel
76905 // _a = %error%;
76906 // /*catchBlock*/
76907 // .br endLabel
76908 // .finally
76909 // .mark finallyLabel
76910 // /*finallyBlock*/
76911 // .endfinally
76912 // .endtry
76913 // .mark endLabel
76914 beginExceptionBlock();
76915 transformAndEmitEmbeddedStatement(node.tryBlock);
76916 if (node.catchClause) {
76917 beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
76918 transformAndEmitEmbeddedStatement(node.catchClause.block);
76919 }
76920 if (node.finallyBlock) {
76921 beginFinallyBlock();
76922 transformAndEmitEmbeddedStatement(node.finallyBlock);
76923 }
76924 endExceptionBlock();
76925 }
76926 else {
76927 emitStatement(ts.visitEachChild(node, visitor, context));
76928 }
76929 }
76930 function containsYield(node) {
76931 return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0;
76932 }
76933 function countInitialNodesWithoutYield(nodes) {
76934 var numNodes = nodes.length;
76935 for (var i = 0; i < numNodes; i++) {
76936 if (containsYield(nodes[i])) {
76937 return i;
76938 }
76939 }
76940 return -1;
76941 }
76942 function onSubstituteNode(hint, node) {
76943 node = previousOnSubstituteNode(hint, node);
76944 if (hint === 1 /* Expression */) {
76945 return substituteExpression(node);
76946 }
76947 return node;
76948 }
76949 function substituteExpression(node) {
76950 if (ts.isIdentifier(node)) {
76951 return substituteExpressionIdentifier(node);
76952 }
76953 return node;
76954 }
76955 function substituteExpressionIdentifier(node) {
76956 if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
76957 var original = ts.getOriginalNode(node);
76958 if (ts.isIdentifier(original) && original.parent) {
76959 var declaration = resolver.getReferencedValueDeclaration(original);
76960 if (declaration) {
76961 var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
76962 if (name) {
76963 var clone_7 = ts.getMutableClone(name);
76964 ts.setSourceMapRange(clone_7, node);
76965 ts.setCommentRange(clone_7, node);
76966 return clone_7;
76967 }
76968 }
76969 }
76970 }
76971 return node;
76972 }
76973 function cacheExpression(node) {
76974 var temp;
76975 if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
76976 return node;
76977 }
76978 temp = ts.createTempVariable(hoistVariableDeclaration);
76979 emitAssignment(temp, node, /*location*/ node);
76980 return temp;
76981 }
76982 function declareLocal(name) {
76983 var temp = name
76984 ? ts.createUniqueName(name)
76985 : ts.createTempVariable(/*recordTempVariable*/ undefined);
76986 hoistVariableDeclaration(temp);
76987 return temp;
76988 }
76989 /**
76990 * Defines a label, uses as the target of a Break operation.
76991 */
76992 function defineLabel() {
76993 if (!labelOffsets) {
76994 labelOffsets = [];
76995 }
76996 var label = nextLabelId;
76997 nextLabelId++;
76998 labelOffsets[label] = -1;
76999 return label;
77000 }
77001 /**
77002 * Marks the current operation with the specified label.
77003 */
77004 function markLabel(label) {
77005 ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
77006 labelOffsets[label] = operations ? operations.length : 0;
77007 }
77008 /**
77009 * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
77010 *
77011 * @param block Information about the block.
77012 */
77013 function beginBlock(block) {
77014 if (!blocks) {
77015 blocks = [];
77016 blockActions = [];
77017 blockOffsets = [];
77018 blockStack = [];
77019 }
77020 var index = blockActions.length;
77021 blockActions[index] = 0 /* Open */;
77022 blockOffsets[index] = operations ? operations.length : 0;
77023 blocks[index] = block;
77024 blockStack.push(block);
77025 return index;
77026 }
77027 /**
77028 * Ends the current block operation.
77029 */
77030 function endBlock() {
77031 var block = peekBlock();
77032 if (block === undefined)
77033 return ts.Debug.fail("beginBlock was never called.");
77034 var index = blockActions.length;
77035 blockActions[index] = 1 /* Close */;
77036 blockOffsets[index] = operations ? operations.length : 0;
77037 blocks[index] = block;
77038 blockStack.pop();
77039 return block;
77040 }
77041 /**
77042 * Gets the current open block.
77043 */
77044 function peekBlock() {
77045 return ts.lastOrUndefined(blockStack);
77046 }
77047 /**
77048 * Gets the kind of the current open block.
77049 */
77050 function peekBlockKind() {
77051 var block = peekBlock();
77052 return block && block.kind;
77053 }
77054 /**
77055 * Begins a code block for a generated `with` statement.
77056 *
77057 * @param expression An identifier representing expression for the `with` block.
77058 */
77059 function beginWithBlock(expression) {
77060 var startLabel = defineLabel();
77061 var endLabel = defineLabel();
77062 markLabel(startLabel);
77063 beginBlock({
77064 kind: 1 /* With */,
77065 expression: expression,
77066 startLabel: startLabel,
77067 endLabel: endLabel
77068 });
77069 }
77070 /**
77071 * Ends a code block for a generated `with` statement.
77072 */
77073 function endWithBlock() {
77074 ts.Debug.assert(peekBlockKind() === 1 /* With */);
77075 var block = endBlock();
77076 markLabel(block.endLabel);
77077 }
77078 /**
77079 * Begins a code block for a generated `try` statement.
77080 */
77081 function beginExceptionBlock() {
77082 var startLabel = defineLabel();
77083 var endLabel = defineLabel();
77084 markLabel(startLabel);
77085 beginBlock({
77086 kind: 0 /* Exception */,
77087 state: 0 /* Try */,
77088 startLabel: startLabel,
77089 endLabel: endLabel
77090 });
77091 emitNop();
77092 return endLabel;
77093 }
77094 /**
77095 * Enters the `catch` clause of a generated `try` statement.
77096 *
77097 * @param variable The catch variable.
77098 */
77099 function beginCatchBlock(variable) {
77100 ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
77101 // generated identifiers should already be unique within a file
77102 var name;
77103 if (ts.isGeneratedIdentifier(variable.name)) {
77104 name = variable.name;
77105 hoistVariableDeclaration(variable.name);
77106 }
77107 else {
77108 var text = ts.idText(variable.name);
77109 name = declareLocal(text);
77110 if (!renamedCatchVariables) {
77111 renamedCatchVariables = ts.createMap();
77112 renamedCatchVariableDeclarations = [];
77113 context.enableSubstitution(72 /* Identifier */);
77114 }
77115 renamedCatchVariables.set(text, true);
77116 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
77117 }
77118 var exception = peekBlock();
77119 ts.Debug.assert(exception.state < 1 /* Catch */);
77120 var endLabel = exception.endLabel;
77121 emitBreak(endLabel);
77122 var catchLabel = defineLabel();
77123 markLabel(catchLabel);
77124 exception.state = 1 /* Catch */;
77125 exception.catchVariable = name;
77126 exception.catchLabel = catchLabel;
77127 emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, []));
77128 emitNop();
77129 }
77130 /**
77131 * Enters the `finally` block of a generated `try` statement.
77132 */
77133 function beginFinallyBlock() {
77134 ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
77135 var exception = peekBlock();
77136 ts.Debug.assert(exception.state < 2 /* Finally */);
77137 var endLabel = exception.endLabel;
77138 emitBreak(endLabel);
77139 var finallyLabel = defineLabel();
77140 markLabel(finallyLabel);
77141 exception.state = 2 /* Finally */;
77142 exception.finallyLabel = finallyLabel;
77143 }
77144 /**
77145 * Ends the code block for a generated `try` statement.
77146 */
77147 function endExceptionBlock() {
77148 ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
77149 var exception = endBlock();
77150 var state = exception.state;
77151 if (state < 2 /* Finally */) {
77152 emitBreak(exception.endLabel);
77153 }
77154 else {
77155 emitEndfinally();
77156 }
77157 markLabel(exception.endLabel);
77158 emitNop();
77159 exception.state = 3 /* Done */;
77160 }
77161 /**
77162 * Begins a code block that supports `break` or `continue` statements that are defined in
77163 * the source tree and not from generated code.
77164 *
77165 * @param labelText Names from containing labeled statements.
77166 */
77167 function beginScriptLoopBlock() {
77168 beginBlock({
77169 kind: 3 /* Loop */,
77170 isScript: true,
77171 breakLabel: -1,
77172 continueLabel: -1
77173 });
77174 }
77175 /**
77176 * Begins a code block that supports `break` or `continue` statements that are defined in
77177 * generated code. Returns a label used to mark the operation to which to jump when a
77178 * `break` statement targets this block.
77179 *
77180 * @param continueLabel A Label used to mark the operation to which to jump when a
77181 * `continue` statement targets this block.
77182 */
77183 function beginLoopBlock(continueLabel) {
77184 var breakLabel = defineLabel();
77185 beginBlock({
77186 kind: 3 /* Loop */,
77187 isScript: false,
77188 breakLabel: breakLabel,
77189 continueLabel: continueLabel,
77190 });
77191 return breakLabel;
77192 }
77193 /**
77194 * Ends a code block that supports `break` or `continue` statements that are defined in
77195 * generated code or in the source tree.
77196 */
77197 function endLoopBlock() {
77198 ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
77199 var block = endBlock();
77200 var breakLabel = block.breakLabel;
77201 if (!block.isScript) {
77202 markLabel(breakLabel);
77203 }
77204 }
77205 /**
77206 * Begins a code block that supports `break` statements that are defined in the source
77207 * tree and not from generated code.
77208 *
77209 */
77210 function beginScriptSwitchBlock() {
77211 beginBlock({
77212 kind: 2 /* Switch */,
77213 isScript: true,
77214 breakLabel: -1
77215 });
77216 }
77217 /**
77218 * Begins a code block that supports `break` statements that are defined in generated code.
77219 * Returns a label used to mark the operation to which to jump when a `break` statement
77220 * targets this block.
77221 */
77222 function beginSwitchBlock() {
77223 var breakLabel = defineLabel();
77224 beginBlock({
77225 kind: 2 /* Switch */,
77226 isScript: false,
77227 breakLabel: breakLabel,
77228 });
77229 return breakLabel;
77230 }
77231 /**
77232 * Ends a code block that supports `break` statements that are defined in generated code.
77233 */
77234 function endSwitchBlock() {
77235 ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
77236 var block = endBlock();
77237 var breakLabel = block.breakLabel;
77238 if (!block.isScript) {
77239 markLabel(breakLabel);
77240 }
77241 }
77242 function beginScriptLabeledBlock(labelText) {
77243 beginBlock({
77244 kind: 4 /* Labeled */,
77245 isScript: true,
77246 labelText: labelText,
77247 breakLabel: -1
77248 });
77249 }
77250 function beginLabeledBlock(labelText) {
77251 var breakLabel = defineLabel();
77252 beginBlock({
77253 kind: 4 /* Labeled */,
77254 isScript: false,
77255 labelText: labelText,
77256 breakLabel: breakLabel
77257 });
77258 }
77259 function endLabeledBlock() {
77260 ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
77261 var block = endBlock();
77262 if (!block.isScript) {
77263 markLabel(block.breakLabel);
77264 }
77265 }
77266 /**
77267 * Indicates whether the provided block supports `break` statements.
77268 *
77269 * @param block A code block.
77270 */
77271 function supportsUnlabeledBreak(block) {
77272 return block.kind === 2 /* Switch */
77273 || block.kind === 3 /* Loop */;
77274 }
77275 /**
77276 * Indicates whether the provided block supports `break` statements with labels.
77277 *
77278 * @param block A code block.
77279 */
77280 function supportsLabeledBreakOrContinue(block) {
77281 return block.kind === 4 /* Labeled */;
77282 }
77283 /**
77284 * Indicates whether the provided block supports `continue` statements.
77285 *
77286 * @param block A code block.
77287 */
77288 function supportsUnlabeledContinue(block) {
77289 return block.kind === 3 /* Loop */;
77290 }
77291 function hasImmediateContainingLabeledBlock(labelText, start) {
77292 for (var j = start; j >= 0; j--) {
77293 var containingBlock = blockStack[j];
77294 if (supportsLabeledBreakOrContinue(containingBlock)) {
77295 if (containingBlock.labelText === labelText) {
77296 return true;
77297 }
77298 }
77299 else {
77300 break;
77301 }
77302 }
77303 return false;
77304 }
77305 /**
77306 * Finds the label that is the target for a `break` statement.
77307 *
77308 * @param labelText An optional name of a containing labeled statement.
77309 */
77310 function findBreakTarget(labelText) {
77311 if (blockStack) {
77312 if (labelText) {
77313 for (var i = blockStack.length - 1; i >= 0; i--) {
77314 var block = blockStack[i];
77315 if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
77316 return block.breakLabel;
77317 }
77318 else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
77319 return block.breakLabel;
77320 }
77321 }
77322 }
77323 else {
77324 for (var i = blockStack.length - 1; i >= 0; i--) {
77325 var block = blockStack[i];
77326 if (supportsUnlabeledBreak(block)) {
77327 return block.breakLabel;
77328 }
77329 }
77330 }
77331 }
77332 return 0;
77333 }
77334 /**
77335 * Finds the label that is the target for a `continue` statement.
77336 *
77337 * @param labelText An optional name of a containing labeled statement.
77338 */
77339 function findContinueTarget(labelText) {
77340 if (blockStack) {
77341 if (labelText) {
77342 for (var i = blockStack.length - 1; i >= 0; i--) {
77343 var block = blockStack[i];
77344 if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
77345 return block.continueLabel;
77346 }
77347 }
77348 }
77349 else {
77350 for (var i = blockStack.length - 1; i >= 0; i--) {
77351 var block = blockStack[i];
77352 if (supportsUnlabeledContinue(block)) {
77353 return block.continueLabel;
77354 }
77355 }
77356 }
77357 }
77358 return 0;
77359 }
77360 /**
77361 * Creates an expression that can be used to indicate the value for a label.
77362 *
77363 * @param label A label.
77364 */
77365 function createLabel(label) {
77366 if (label !== undefined && label > 0) {
77367 if (labelExpressions === undefined) {
77368 labelExpressions = [];
77369 }
77370 var expression = ts.createLiteral(-1);
77371 if (labelExpressions[label] === undefined) {
77372 labelExpressions[label] = [expression];
77373 }
77374 else {
77375 labelExpressions[label].push(expression);
77376 }
77377 return expression;
77378 }
77379 return ts.createOmittedExpression();
77380 }
77381 /**
77382 * Creates a numeric literal for the provided instruction.
77383 */
77384 function createInstruction(instruction) {
77385 var literal = ts.createLiteral(instruction);
77386 ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
77387 return literal;
77388 }
77389 /**
77390 * Creates a statement that can be used indicate a Break operation to the provided label.
77391 *
77392 * @param label A label.
77393 * @param location An optional source map location for the statement.
77394 */
77395 function createInlineBreak(label, location) {
77396 ts.Debug.assertLessThan(0, label, "Invalid label");
77397 return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
77398 createInstruction(3 /* Break */),
77399 createLabel(label)
77400 ])), location);
77401 }
77402 /**
77403 * Creates a statement that can be used indicate a Return operation.
77404 *
77405 * @param expression The expression for the return statement.
77406 * @param location An optional source map location for the statement.
77407 */
77408 function createInlineReturn(expression, location) {
77409 return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
77410 ? [createInstruction(2 /* Return */), expression]
77411 : [createInstruction(2 /* Return */)])), location);
77412 }
77413 /**
77414 * Creates an expression that can be used to resume from a Yield operation.
77415 */
77416 function createGeneratorResume(location) {
77417 return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"),
77418 /*typeArguments*/ undefined, []), location);
77419 }
77420 /**
77421 * Emits an empty instruction.
77422 */
77423 function emitNop() {
77424 emitWorker(0 /* Nop */);
77425 }
77426 /**
77427 * Emits a Statement.
77428 *
77429 * @param node A statement.
77430 */
77431 function emitStatement(node) {
77432 if (node) {
77433 emitWorker(1 /* Statement */, [node]);
77434 }
77435 else {
77436 emitNop();
77437 }
77438 }
77439 /**
77440 * Emits an Assignment operation.
77441 *
77442 * @param left The left-hand side of the assignment.
77443 * @param right The right-hand side of the assignment.
77444 * @param location An optional source map location for the assignment.
77445 */
77446 function emitAssignment(left, right, location) {
77447 emitWorker(2 /* Assign */, [left, right], location);
77448 }
77449 /**
77450 * Emits a Break operation to the specified label.
77451 *
77452 * @param label A label.
77453 * @param location An optional source map location for the assignment.
77454 */
77455 function emitBreak(label, location) {
77456 emitWorker(3 /* Break */, [label], location);
77457 }
77458 /**
77459 * Emits a Break operation to the specified label when a condition evaluates to a truthy
77460 * value at runtime.
77461 *
77462 * @param label A label.
77463 * @param condition The condition.
77464 * @param location An optional source map location for the assignment.
77465 */
77466 function emitBreakWhenTrue(label, condition, location) {
77467 emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
77468 }
77469 /**
77470 * Emits a Break to the specified label when a condition evaluates to a falsey value at
77471 * runtime.
77472 *
77473 * @param label A label.
77474 * @param condition The condition.
77475 * @param location An optional source map location for the assignment.
77476 */
77477 function emitBreakWhenFalse(label, condition, location) {
77478 emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
77479 }
77480 /**
77481 * Emits a YieldStar operation for the provided expression.
77482 *
77483 * @param expression An optional value for the yield operation.
77484 * @param location An optional source map location for the assignment.
77485 */
77486 function emitYieldStar(expression, location) {
77487 emitWorker(7 /* YieldStar */, [expression], location);
77488 }
77489 /**
77490 * Emits a Yield operation for the provided expression.
77491 *
77492 * @param expression An optional value for the yield operation.
77493 * @param location An optional source map location for the assignment.
77494 */
77495 function emitYield(expression, location) {
77496 emitWorker(6 /* Yield */, [expression], location);
77497 }
77498 /**
77499 * Emits a Return operation for the provided expression.
77500 *
77501 * @param expression An optional value for the operation.
77502 * @param location An optional source map location for the assignment.
77503 */
77504 function emitReturn(expression, location) {
77505 emitWorker(8 /* Return */, [expression], location);
77506 }
77507 /**
77508 * Emits a Throw operation for the provided expression.
77509 *
77510 * @param expression A value for the operation.
77511 * @param location An optional source map location for the assignment.
77512 */
77513 function emitThrow(expression, location) {
77514 emitWorker(9 /* Throw */, [expression], location);
77515 }
77516 /**
77517 * Emits an Endfinally operation. This is used to handle `finally` block semantics.
77518 */
77519 function emitEndfinally() {
77520 emitWorker(10 /* Endfinally */);
77521 }
77522 /**
77523 * Emits an operation.
77524 *
77525 * @param code The OpCode for the operation.
77526 * @param args The optional arguments for the operation.
77527 */
77528 function emitWorker(code, args, location) {
77529 if (operations === undefined) {
77530 operations = [];
77531 operationArguments = [];
77532 operationLocations = [];
77533 }
77534 if (labelOffsets === undefined) {
77535 // mark entry point
77536 markLabel(defineLabel());
77537 }
77538 var operationIndex = operations.length;
77539 operations[operationIndex] = code;
77540 operationArguments[operationIndex] = args;
77541 operationLocations[operationIndex] = location;
77542 }
77543 /**
77544 * Builds the generator function body.
77545 */
77546 function build() {
77547 blockIndex = 0;
77548 labelNumber = 0;
77549 labelNumbers = undefined;
77550 lastOperationWasAbrupt = false;
77551 lastOperationWasCompletion = false;
77552 clauses = undefined;
77553 statements = undefined;
77554 exceptionBlockStack = undefined;
77555 currentExceptionBlock = undefined;
77556 withBlockStack = undefined;
77557 var buildResult = buildStatements();
77558 return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(
77559 /*modifiers*/ undefined,
77560 /*asteriskToken*/ undefined,
77561 /*name*/ undefined,
77562 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)],
77563 /*type*/ undefined, ts.createBlock(buildResult,
77564 /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
77565 }
77566 /**
77567 * Builds the statements for the generator function body.
77568 */
77569 function buildStatements() {
77570 if (operations) {
77571 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
77572 writeOperation(operationIndex);
77573 }
77574 flushFinalLabel(operations.length);
77575 }
77576 else {
77577 flushFinalLabel(0);
77578 }
77579 if (clauses) {
77580 var labelExpression = ts.createPropertyAccess(state, "label");
77581 var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses));
77582 return [ts.startOnNewLine(switchStatement)];
77583 }
77584 if (statements) {
77585 return statements;
77586 }
77587 return [];
77588 }
77589 /**
77590 * Flush the current label and advance to a new label.
77591 */
77592 function flushLabel() {
77593 if (!statements) {
77594 return;
77595 }
77596 appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
77597 lastOperationWasAbrupt = false;
77598 lastOperationWasCompletion = false;
77599 labelNumber++;
77600 }
77601 /**
77602 * Flush the final label of the generator function body.
77603 */
77604 function flushFinalLabel(operationIndex) {
77605 if (isFinalLabelReachable(operationIndex)) {
77606 tryEnterLabel(operationIndex);
77607 withBlockStack = undefined;
77608 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
77609 }
77610 if (statements && clauses) {
77611 appendLabel(/*markLabelEnd*/ false);
77612 }
77613 updateLabelExpressions();
77614 }
77615 /**
77616 * Tests whether the final label of the generator function body
77617 * is reachable by user code.
77618 */
77619 function isFinalLabelReachable(operationIndex) {
77620 // if the last operation was *not* a completion (return/throw) then
77621 // the final label is reachable.
77622 if (!lastOperationWasCompletion) {
77623 return true;
77624 }
77625 // if there are no labels defined or referenced, then the final label is
77626 // not reachable.
77627 if (!labelOffsets || !labelExpressions) {
77628 return false;
77629 }
77630 // if the label for this offset is referenced, then the final label
77631 // is reachable.
77632 for (var label = 0; label < labelOffsets.length; label++) {
77633 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
77634 return true;
77635 }
77636 }
77637 return false;
77638 }
77639 /**
77640 * Appends a case clause for the last label and sets the new label.
77641 *
77642 * @param markLabelEnd Indicates that the transition between labels was a fall-through
77643 * from a previous case clause and the change in labels should be
77644 * reflected on the `state` object.
77645 */
77646 function appendLabel(markLabelEnd) {
77647 if (!clauses) {
77648 clauses = [];
77649 }
77650 if (statements) {
77651 if (withBlockStack) {
77652 // The previous label was nested inside one or more `with` blocks, so we
77653 // surround the statements in generated `with` blocks to create the same environment.
77654 for (var i = withBlockStack.length - 1; i >= 0; i--) {
77655 var withBlock = withBlockStack[i];
77656 statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))];
77657 }
77658 }
77659 if (currentExceptionBlock) {
77660 // The previous label was nested inside of an exception block, so we must
77661 // indicate entry into a protected region by pushing the label numbers
77662 // for each block in the protected region.
77663 var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
77664 statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"),
77665 /*typeArguments*/ undefined, [
77666 ts.createArrayLiteral([
77667 createLabel(startLabel),
77668 createLabel(catchLabel),
77669 createLabel(finallyLabel),
77670 createLabel(endLabel)
77671 ])
77672 ])));
77673 currentExceptionBlock = undefined;
77674 }
77675 if (markLabelEnd) {
77676 // The case clause for the last label falls through to this label, so we
77677 // add an assignment statement to reflect the change in labels.
77678 statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1))));
77679 }
77680 }
77681 clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || []));
77682 statements = undefined;
77683 }
77684 /**
77685 * Tries to enter into a new label at the current operation index.
77686 */
77687 function tryEnterLabel(operationIndex) {
77688 if (!labelOffsets) {
77689 return;
77690 }
77691 for (var label = 0; label < labelOffsets.length; label++) {
77692 if (labelOffsets[label] === operationIndex) {
77693 flushLabel();
77694 if (labelNumbers === undefined) {
77695 labelNumbers = [];
77696 }
77697 if (labelNumbers[labelNumber] === undefined) {
77698 labelNumbers[labelNumber] = [label];
77699 }
77700 else {
77701 labelNumbers[labelNumber].push(label);
77702 }
77703 }
77704 }
77705 }
77706 /**
77707 * Updates literal expressions for labels with actual label numbers.
77708 */
77709 function updateLabelExpressions() {
77710 if (labelExpressions !== undefined && labelNumbers !== undefined) {
77711 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
77712 var labels = labelNumbers[labelNumber_1];
77713 if (labels !== undefined) {
77714 for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
77715 var label = labels_1[_i];
77716 var expressions = labelExpressions[label];
77717 if (expressions !== undefined) {
77718 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
77719 var expression = expressions_1[_a];
77720 expression.text = String(labelNumber_1);
77721 }
77722 }
77723 }
77724 }
77725 }
77726 }
77727 }
77728 /**
77729 * Tries to enter or leave a code block.
77730 */
77731 function tryEnterOrLeaveBlock(operationIndex) {
77732 if (blocks) {
77733 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
77734 var block = blocks[blockIndex];
77735 var blockAction = blockActions[blockIndex];
77736 switch (block.kind) {
77737 case 0 /* Exception */:
77738 if (blockAction === 0 /* Open */) {
77739 if (!exceptionBlockStack) {
77740 exceptionBlockStack = [];
77741 }
77742 if (!statements) {
77743 statements = [];
77744 }
77745 exceptionBlockStack.push(currentExceptionBlock);
77746 currentExceptionBlock = block;
77747 }
77748 else if (blockAction === 1 /* Close */) {
77749 currentExceptionBlock = exceptionBlockStack.pop();
77750 }
77751 break;
77752 case 1 /* With */:
77753 if (blockAction === 0 /* Open */) {
77754 if (!withBlockStack) {
77755 withBlockStack = [];
77756 }
77757 withBlockStack.push(block);
77758 }
77759 else if (blockAction === 1 /* Close */) {
77760 withBlockStack.pop();
77761 }
77762 break;
77763 // default: do nothing
77764 }
77765 }
77766 }
77767 }
77768 /**
77769 * Writes an operation as a statement to the current label's statement list.
77770 *
77771 * @param operation The OpCode of the operation
77772 */
77773 function writeOperation(operationIndex) {
77774 tryEnterLabel(operationIndex);
77775 tryEnterOrLeaveBlock(operationIndex);
77776 // early termination, nothing else to process in this label
77777 if (lastOperationWasAbrupt) {
77778 return;
77779 }
77780 lastOperationWasAbrupt = false;
77781 lastOperationWasCompletion = false;
77782 var opcode = operations[operationIndex];
77783 if (opcode === 0 /* Nop */) {
77784 return;
77785 }
77786 else if (opcode === 10 /* Endfinally */) {
77787 return writeEndfinally();
77788 }
77789 var args = operationArguments[operationIndex];
77790 if (opcode === 1 /* Statement */) {
77791 return writeStatement(args[0]);
77792 }
77793 var location = operationLocations[operationIndex];
77794 switch (opcode) {
77795 case 2 /* Assign */:
77796 return writeAssign(args[0], args[1], location);
77797 case 3 /* Break */:
77798 return writeBreak(args[0], location);
77799 case 4 /* BreakWhenTrue */:
77800 return writeBreakWhenTrue(args[0], args[1], location);
77801 case 5 /* BreakWhenFalse */:
77802 return writeBreakWhenFalse(args[0], args[1], location);
77803 case 6 /* Yield */:
77804 return writeYield(args[0], location);
77805 case 7 /* YieldStar */:
77806 return writeYieldStar(args[0], location);
77807 case 8 /* Return */:
77808 return writeReturn(args[0], location);
77809 case 9 /* Throw */:
77810 return writeThrow(args[0], location);
77811 }
77812 }
77813 /**
77814 * Writes a statement to the current label's statement list.
77815 *
77816 * @param statement A statement to write.
77817 */
77818 function writeStatement(statement) {
77819 if (statement) {
77820 if (!statements) {
77821 statements = [statement];
77822 }
77823 else {
77824 statements.push(statement);
77825 }
77826 }
77827 }
77828 /**
77829 * Writes an Assign operation to the current label's statement list.
77830 *
77831 * @param left The left-hand side of the assignment.
77832 * @param right The right-hand side of the assignment.
77833 * @param operationLocation The source map location for the operation.
77834 */
77835 function writeAssign(left, right, operationLocation) {
77836 writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation));
77837 }
77838 /**
77839 * Writes a Throw operation to the current label's statement list.
77840 *
77841 * @param expression The value to throw.
77842 * @param operationLocation The source map location for the operation.
77843 */
77844 function writeThrow(expression, operationLocation) {
77845 lastOperationWasAbrupt = true;
77846 lastOperationWasCompletion = true;
77847 writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation));
77848 }
77849 /**
77850 * Writes a Return operation to the current label's statement list.
77851 *
77852 * @param expression The value to return.
77853 * @param operationLocation The source map location for the operation.
77854 */
77855 function writeReturn(expression, operationLocation) {
77856 lastOperationWasAbrupt = true;
77857 lastOperationWasCompletion = true;
77858 writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
77859 ? [createInstruction(2 /* Return */), expression]
77860 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
77861 }
77862 /**
77863 * Writes a Break operation to the current label's statement list.
77864 *
77865 * @param label The label for the Break.
77866 * @param operationLocation The source map location for the operation.
77867 */
77868 function writeBreak(label, operationLocation) {
77869 lastOperationWasAbrupt = true;
77870 writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
77871 createInstruction(3 /* Break */),
77872 createLabel(label)
77873 ])), operationLocation), 384 /* NoTokenSourceMaps */));
77874 }
77875 /**
77876 * Writes a BreakWhenTrue operation to the current label's statement list.
77877 *
77878 * @param label The label for the Break.
77879 * @param condition The condition for the Break.
77880 * @param operationLocation The source map location for the operation.
77881 */
77882 function writeBreakWhenTrue(label, condition, operationLocation) {
77883 writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
77884 createInstruction(3 /* Break */),
77885 createLabel(label)
77886 ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
77887 }
77888 /**
77889 * Writes a BreakWhenFalse operation to the current label's statement list.
77890 *
77891 * @param label The label for the Break.
77892 * @param condition The condition for the Break.
77893 * @param operationLocation The source map location for the operation.
77894 */
77895 function writeBreakWhenFalse(label, condition, operationLocation) {
77896 writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
77897 createInstruction(3 /* Break */),
77898 createLabel(label)
77899 ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
77900 }
77901 /**
77902 * Writes a Yield operation to the current label's statement list.
77903 *
77904 * @param expression The expression to yield.
77905 * @param operationLocation The source map location for the operation.
77906 */
77907 function writeYield(expression, operationLocation) {
77908 lastOperationWasAbrupt = true;
77909 writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
77910 ? [createInstruction(4 /* Yield */), expression]
77911 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
77912 }
77913 /**
77914 * Writes a YieldStar instruction to the current label's statement list.
77915 *
77916 * @param expression The expression to yield.
77917 * @param operationLocation The source map location for the operation.
77918 */
77919 function writeYieldStar(expression, operationLocation) {
77920 lastOperationWasAbrupt = true;
77921 writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
77922 createInstruction(5 /* YieldStar */),
77923 expression
77924 ])), operationLocation), 384 /* NoTokenSourceMaps */));
77925 }
77926 /**
77927 * Writes an Endfinally instruction to the current label's statement list.
77928 */
77929 function writeEndfinally() {
77930 lastOperationWasAbrupt = true;
77931 writeStatement(ts.createReturn(ts.createArrayLiteral([
77932 createInstruction(7 /* Endfinally */)
77933 ])));
77934 }
77935 }
77936 ts.transformGenerators = transformGenerators;
77937 function createGeneratorHelper(context, body) {
77938 context.requestEmitHelper(ts.generatorHelper);
77939 return ts.createCall(ts.getHelperName("__generator"),
77940 /*typeArguments*/ undefined, [ts.createThis(), body]);
77941 }
77942 // The __generator helper is used by down-level transformations to emulate the runtime
77943 // semantics of an ES2015 generator function. When called, this helper returns an
77944 // object that implements the Iterator protocol, in that it has `next`, `return`, and
77945 // `throw` methods that step through the generator when invoked.
77946 //
77947 // parameters:
77948 // @param thisArg The value to use as the `this` binding for the transformed generator body.
77949 // @param body A function that acts as the transformed generator body.
77950 //
77951 // variables:
77952 // _ Persistent state for the generator that is shared between the helper and the
77953 // generator body. The state object has the following members:
77954 // sent() - A method that returns or throws the current completion value.
77955 // label - The next point at which to resume evaluation of the generator body.
77956 // trys - A stack of protected regions (try/catch/finally blocks).
77957 // ops - A stack of pending instructions when inside of a finally block.
77958 // f A value indicating whether the generator is executing.
77959 // y An iterator to delegate for a yield*.
77960 // t A temporary variable that holds one of the following values (note that these
77961 // cases do not overlap):
77962 // - The completion value when resuming from a `yield` or `yield*`.
77963 // - The error value for a catch block.
77964 // - The current protected region (array of try/catch/finally/end labels).
77965 // - The verb (`next`, `throw`, or `return` method) to delegate to the expression
77966 // of a `yield*`.
77967 // - The result of evaluating the verb delegated to the expression of a `yield*`.
77968 //
77969 // functions:
77970 // verb(n) Creates a bound callback to the `step` function for opcode `n`.
77971 // step(op) Evaluates opcodes in a generator body until execution is suspended or
77972 // completed.
77973 //
77974 // The __generator helper understands a limited set of instructions:
77975 // 0: next(value?) - Start or resume the generator with the specified value.
77976 // 1: throw(error) - Resume the generator with an exception. If the generator is
77977 // suspended inside of one or more protected regions, evaluates
77978 // any intervening finally blocks between the current label and
77979 // the nearest catch block or function boundary. If uncaught, the
77980 // exception is thrown to the caller.
77981 // 2: return(value?) - Resume the generator as if with a return. If the generator is
77982 // suspended inside of one or more protected regions, evaluates any
77983 // intervening finally blocks.
77984 // 3: break(label) - Jump to the specified label. If the label is outside of the
77985 // current protected region, evaluates any intervening finally
77986 // blocks.
77987 // 4: yield(value?) - Yield execution to the caller with an optional value. When
77988 // resumed, the generator will continue at the next label.
77989 // 5: yield*(value) - Delegates evaluation to the supplied iterator. When
77990 // delegation completes, the generator will continue at the next
77991 // label.
77992 // 6: catch(error) - Handles an exception thrown from within the generator body. If
77993 // the current label is inside of one or more protected regions,
77994 // evaluates any intervening finally blocks between the current
77995 // label and the nearest catch block or function boundary. If
77996 // uncaught, the exception is thrown to the caller.
77997 // 7: endfinally - Ends a finally block, resuming the last instruction prior to
77998 // entering a finally block.
77999 //
78000 // For examples of how these are used, see the comments in ./transformers/generators.ts
78001 ts.generatorHelper = {
78002 name: "typescript:generator",
78003 scoped: false,
78004 priority: 6,
78005 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 };"
78006 };
78007})(ts || (ts = {}));
78008/*@internal*/
78009var ts;
78010(function (ts) {
78011 function transformModule(context) {
78012 function getTransformModuleDelegate(moduleKind) {
78013 switch (moduleKind) {
78014 case ts.ModuleKind.AMD: return transformAMDModule;
78015 case ts.ModuleKind.UMD: return transformUMDModule;
78016 default: return transformCommonJSModule;
78017 }
78018 }
78019 var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
78020 var compilerOptions = context.getCompilerOptions();
78021 var resolver = context.getEmitResolver();
78022 var host = context.getEmitHost();
78023 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
78024 var moduleKind = ts.getEmitModuleKind(compilerOptions);
78025 var previousOnSubstituteNode = context.onSubstituteNode;
78026 var previousOnEmitNode = context.onEmitNode;
78027 context.onSubstituteNode = onSubstituteNode;
78028 context.onEmitNode = onEmitNode;
78029 context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
78030 context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
78031 context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
78032 context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
78033 context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
78034 context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
78035 var moduleInfoMap = []; // The ExternalModuleInfo for each file.
78036 var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
78037 var currentSourceFile; // The current file.
78038 var currentModuleInfo; // The ExternalModuleInfo for the current file.
78039 var noSubstitution; // Set of nodes for which substitution rules should be ignored.
78040 var needUMDDynamicImportHelper;
78041 return ts.chainBundle(transformSourceFile);
78042 /**
78043 * Transforms the module aspects of a SourceFile.
78044 *
78045 * @param node The SourceFile node.
78046 */
78047 function transformSourceFile(node) {
78048 if (node.isDeclarationFile ||
78049 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
78050 node.transformFlags & 524288 /* ContainsDynamicImport */ ||
78051 (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
78052 return node;
78053 }
78054 currentSourceFile = node;
78055 currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
78056 moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
78057 // Perform the transformation.
78058 var transformModule = getTransformModuleDelegate(moduleKind);
78059 var updated = transformModule(node);
78060 currentSourceFile = undefined;
78061 currentModuleInfo = undefined;
78062 needUMDDynamicImportHelper = false;
78063 return ts.aggregateTransformFlags(updated);
78064 }
78065 function shouldEmitUnderscoreUnderscoreESModule() {
78066 if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
78067 return true;
78068 }
78069 return false;
78070 }
78071 /**
78072 * Transforms a SourceFile into a CommonJS module.
78073 *
78074 * @param node The SourceFile node.
78075 */
78076 function transformCommonJSModule(node) {
78077 startLexicalEnvironment();
78078 var statements = [];
78079 var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
78080 var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
78081 if (shouldEmitUnderscoreUnderscoreESModule()) {
78082 ts.append(statements, createUnderscoreUnderscoreESModule());
78083 }
78084 ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
78085 ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
78086 addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
78087 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
78088 var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
78089 if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
78090 // If we have any `export * from ...` declarations
78091 // we need to inform the emitter to add the __export helper.
78092 ts.addEmitHelper(updated, exportStarHelper);
78093 }
78094 ts.addEmitHelpers(updated, context.readEmitHelpers());
78095 return updated;
78096 }
78097 /**
78098 * Transforms a SourceFile into an AMD module.
78099 *
78100 * @param node The SourceFile node.
78101 */
78102 function transformAMDModule(node) {
78103 var define = ts.createIdentifier("define");
78104 var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
78105 var jsonSourceFile = ts.isJsonSourceFile(node) && node;
78106 // An AMD define function has the following shape:
78107 //
78108 // define(id?, dependencies?, factory);
78109 //
78110 // This has the shape of the following:
78111 //
78112 // define(name, ["module1", "module2"], function (module1Alias) { ... }
78113 //
78114 // The location of the alias in the parameter list in the factory function needs to
78115 // match the position of the module name in the dependency list.
78116 //
78117 // To ensure this is true in cases of modules with no aliases, e.g.:
78118 //
78119 // import "module"
78120 //
78121 // or
78122 //
78123 // /// <amd-dependency path= "a.css" />
78124 //
78125 // we need to add modules without alias names to the end of the dependencies list
78126 var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
78127 // Create an updated SourceFile:
78128 //
78129 // define(moduleName?, ["module1", "module2"], function ...
78130 var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
78131 ts.createExpressionStatement(ts.createCall(define,
78132 /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([
78133 // Add the dependency array argument:
78134 //
78135 // ["require", "exports", module1", "module2", ...]
78136 ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [
78137 ts.createLiteral("require"),
78138 ts.createLiteral("exports")
78139 ].concat(aliasedModuleNames, unaliasedModuleNames)),
78140 // Add the module body function argument:
78141 //
78142 // function (require, exports, module1, module2) ...
78143 jsonSourceFile ?
78144 jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() :
78145 ts.createFunctionExpression(
78146 /*modifiers*/ undefined,
78147 /*asteriskToken*/ undefined,
78148 /*name*/ undefined,
78149 /*typeParameters*/ undefined, [
78150 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
78151 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
78152 ].concat(importAliasNames),
78153 /*type*/ undefined, transformAsynchronousModuleBody(node))
78154 ])))
78155 ]),
78156 /*location*/ node.statements));
78157 ts.addEmitHelpers(updated, context.readEmitHelpers());
78158 return updated;
78159 }
78160 /**
78161 * Transforms a SourceFile into a UMD module.
78162 *
78163 * @param node The SourceFile node.
78164 */
78165 function transformUMDModule(node) {
78166 var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
78167 var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
78168 var umdHeader = ts.createFunctionExpression(
78169 /*modifiers*/ undefined,
78170 /*asteriskToken*/ undefined,
78171 /*name*/ undefined,
78172 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")],
78173 /*type*/ undefined, ts.setTextRange(ts.createBlock([
78174 ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([
78175 ts.createVariableStatement(
78176 /*modifiers*/ undefined, [
78177 ts.createVariableDeclaration("v",
78178 /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"),
78179 /*typeArguments*/ undefined, [
78180 ts.createIdentifier("require"),
78181 ts.createIdentifier("exports")
78182 ]))
78183 ]),
78184 ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */)
78185 ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([
78186 ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"),
78187 /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([
78188 ts.createArrayLiteral([
78189 ts.createLiteral("require"),
78190 ts.createLiteral("exports")
78191 ].concat(aliasedModuleNames, unaliasedModuleNames)),
78192 ts.createIdentifier("factory")
78193 ])))
78194 ])))
78195 ],
78196 /*multiLine*/ true),
78197 /*location*/ undefined));
78198 // Create an updated SourceFile:
78199 //
78200 // (function (factory) {
78201 // if (typeof module === "object" && typeof module.exports === "object") {
78202 // var v = factory(require, exports);
78203 // if (v !== undefined) module.exports = v;
78204 // }
78205 // else if (typeof define === 'function' && define.amd) {
78206 // define(["require", "exports"], factory);
78207 // }
78208 // })(function ...)
78209 var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
78210 ts.createExpressionStatement(ts.createCall(umdHeader,
78211 /*typeArguments*/ undefined, [
78212 // Add the module body function argument:
78213 //
78214 // function (require, exports) ...
78215 ts.createFunctionExpression(
78216 /*modifiers*/ undefined,
78217 /*asteriskToken*/ undefined,
78218 /*name*/ undefined,
78219 /*typeParameters*/ undefined, [
78220 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
78221 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
78222 ].concat(importAliasNames),
78223 /*type*/ undefined, transformAsynchronousModuleBody(node))
78224 ]))
78225 ]),
78226 /*location*/ node.statements));
78227 ts.addEmitHelpers(updated, context.readEmitHelpers());
78228 return updated;
78229 }
78230 /**
78231 * Collect the additional asynchronous dependencies for the module.
78232 *
78233 * @param node The source file.
78234 * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
78235 */
78236 function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
78237 // names of modules with corresponding parameter in the factory function
78238 var aliasedModuleNames = [];
78239 // names of modules with no corresponding parameters in factory function
78240 var unaliasedModuleNames = [];
78241 // names of the parameters in the factory function; these
78242 // parameters need to match the indexes of the corresponding
78243 // module names in aliasedModuleNames.
78244 var importAliasNames = [];
78245 // Fill in amd-dependency tags
78246 for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
78247 var amdDependency = _a[_i];
78248 if (amdDependency.name) {
78249 aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
78250 importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
78251 }
78252 else {
78253 unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
78254 }
78255 }
78256 for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
78257 var importNode = _c[_b];
78258 // Find the name of the external module
78259 var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
78260 // Find the name of the module alias, if there is one
78261 var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
78262 // It is possible that externalModuleName is undefined if it is not string literal.
78263 // This can happen in the invalid import syntax.
78264 // E.g : "import * from alias from 'someLib';"
78265 if (externalModuleName) {
78266 if (includeNonAmdDependencies && importAliasName) {
78267 // Set emitFlags on the name of the classDeclaration
78268 // This is so that when printer will not substitute the identifier
78269 ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
78270 aliasedModuleNames.push(externalModuleName);
78271 importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
78272 }
78273 else {
78274 unaliasedModuleNames.push(externalModuleName);
78275 }
78276 }
78277 }
78278 return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
78279 }
78280 function getAMDImportExpressionForImport(node) {
78281 if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) {
78282 return undefined;
78283 }
78284 var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217
78285 var expr = getHelperExpressionForImport(node, name);
78286 if (expr === name) {
78287 return undefined;
78288 }
78289 return ts.createExpressionStatement(ts.createAssignment(name, expr));
78290 }
78291 /**
78292 * Transforms a SourceFile into an AMD or UMD module body.
78293 *
78294 * @param node The SourceFile node.
78295 */
78296 function transformAsynchronousModuleBody(node) {
78297 startLexicalEnvironment();
78298 var statements = [];
78299 var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
78300 if (shouldEmitUnderscoreUnderscoreESModule()) {
78301 ts.append(statements, createUnderscoreUnderscoreESModule());
78302 }
78303 // Visit each statement of the module body.
78304 ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
78305 if (moduleKind === ts.ModuleKind.AMD) {
78306 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
78307 }
78308 ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
78309 // Append the 'export =' statement if provided.
78310 addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
78311 // End the lexical environment for the module body
78312 // and merge any new lexical declarations.
78313 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
78314 var body = ts.createBlock(statements, /*multiLine*/ true);
78315 if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
78316 // If we have any `export * from ...` declarations
78317 // we need to inform the emitter to add the __export helper.
78318 ts.addEmitHelper(body, exportStarHelper);
78319 }
78320 if (needUMDDynamicImportHelper) {
78321 ts.addEmitHelper(body, dynamicImportUMDHelper);
78322 }
78323 return body;
78324 }
78325 /**
78326 * Adds the down-level representation of `export=` to the statement list if one exists
78327 * in the source file.
78328 *
78329 * @param statements The Statement list to modify.
78330 * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
78331 * return statement.
78332 */
78333 function addExportEqualsIfNeeded(statements, emitAsReturn) {
78334 if (currentModuleInfo.exportEquals) {
78335 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
78336 if (expressionResult) {
78337 if (emitAsReturn) {
78338 var statement = ts.createReturn(expressionResult);
78339 ts.setTextRange(statement, currentModuleInfo.exportEquals);
78340 ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
78341 statements.push(statement);
78342 }
78343 else {
78344 var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult));
78345 ts.setTextRange(statement, currentModuleInfo.exportEquals);
78346 ts.setEmitFlags(statement, 1536 /* NoComments */);
78347 statements.push(statement);
78348 }
78349 }
78350 }
78351 }
78352 //
78353 // Top-Level Source Element Visitors
78354 //
78355 /**
78356 * Visits a node at the top level of the source file.
78357 *
78358 * @param node The node to visit.
78359 */
78360 function sourceElementVisitor(node) {
78361 switch (node.kind) {
78362 case 249 /* ImportDeclaration */:
78363 return visitImportDeclaration(node);
78364 case 248 /* ImportEqualsDeclaration */:
78365 return visitImportEqualsDeclaration(node);
78366 case 255 /* ExportDeclaration */:
78367 return visitExportDeclaration(node);
78368 case 254 /* ExportAssignment */:
78369 return visitExportAssignment(node);
78370 case 219 /* VariableStatement */:
78371 return visitVariableStatement(node);
78372 case 239 /* FunctionDeclaration */:
78373 return visitFunctionDeclaration(node);
78374 case 240 /* ClassDeclaration */:
78375 return visitClassDeclaration(node);
78376 case 315 /* MergeDeclarationMarker */:
78377 return visitMergeDeclarationMarker(node);
78378 case 316 /* EndOfDeclarationMarker */:
78379 return visitEndOfDeclarationMarker(node);
78380 default:
78381 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
78382 }
78383 }
78384 function moduleExpressionElementVisitor(node) {
78385 // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
78386 // as export/import statements are only transformed at the top level of a file.
78387 if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) {
78388 return node;
78389 }
78390 if (ts.isImportCall(node)) {
78391 return visitImportCallExpression(node);
78392 }
78393 else if (ts.isDestructuringAssignment(node)) {
78394 return visitDestructuringAssignment(node);
78395 }
78396 else {
78397 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
78398 }
78399 }
78400 function destructuringNeedsFlattening(node) {
78401 if (ts.isObjectLiteralExpression(node)) {
78402 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
78403 var elem = _a[_i];
78404 switch (elem.kind) {
78405 case 275 /* PropertyAssignment */:
78406 if (destructuringNeedsFlattening(elem.initializer)) {
78407 return true;
78408 }
78409 break;
78410 case 276 /* ShorthandPropertyAssignment */:
78411 if (destructuringNeedsFlattening(elem.name)) {
78412 return true;
78413 }
78414 break;
78415 case 277 /* SpreadAssignment */:
78416 if (destructuringNeedsFlattening(elem.expression)) {
78417 return true;
78418 }
78419 break;
78420 case 156 /* MethodDeclaration */:
78421 case 158 /* GetAccessor */:
78422 case 159 /* SetAccessor */:
78423 return false;
78424 default: ts.Debug.assertNever(elem, "Unhandled object member kind");
78425 }
78426 }
78427 }
78428 else if (ts.isArrayLiteralExpression(node)) {
78429 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
78430 var elem = _c[_b];
78431 if (ts.isSpreadElement(elem)) {
78432 if (destructuringNeedsFlattening(elem.expression)) {
78433 return true;
78434 }
78435 }
78436 else if (destructuringNeedsFlattening(elem)) {
78437 return true;
78438 }
78439 }
78440 }
78441 else if (ts.isIdentifier(node)) {
78442 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
78443 }
78444 return false;
78445 }
78446 function visitDestructuringAssignment(node) {
78447 if (destructuringNeedsFlattening(node.left)) {
78448 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
78449 }
78450 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
78451 }
78452 function visitImportCallExpression(node) {
78453 var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
78454 var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */);
78455 switch (compilerOptions.module) {
78456 case ts.ModuleKind.AMD:
78457 return createImportCallExpressionAMD(argument, containsLexicalThis);
78458 case ts.ModuleKind.UMD:
78459 return createImportCallExpressionUMD(argument, containsLexicalThis);
78460 case ts.ModuleKind.CommonJS:
78461 default:
78462 return createImportCallExpressionCommonJS(argument, containsLexicalThis);
78463 }
78464 }
78465 function createImportCallExpressionUMD(arg, containsLexicalThis) {
78466 // (function (factory) {
78467 // ... (regular UMD)
78468 // }
78469 // })(function (require, exports, useSyncRequire) {
78470 // "use strict";
78471 // Object.defineProperty(exports, "__esModule", { value: true });
78472 // var __syncRequire = typeof module === "object" && typeof module.exports === "object";
78473 // var __resolved = new Promise(function (resolve) { resolve(); });
78474 // .....
78475 // __syncRequire
78476 // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
78477 // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
78478 // });
78479 needUMDDynamicImportHelper = true;
78480 if (ts.isSimpleCopiableExpression(arg)) {
78481 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */);
78482 return ts.createConditional(
78483 /*condition*/ ts.createIdentifier("__syncRequire"),
78484 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis),
78485 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
78486 }
78487 else {
78488 var temp = ts.createTempVariable(hoistVariableDeclaration);
78489 return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(
78490 /*condition*/ ts.createIdentifier("__syncRequire"),
78491 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis),
78492 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
78493 }
78494 }
78495 function createImportCallExpressionAMD(arg, containsLexicalThis) {
78496 // improt("./blah")
78497 // emit as
78498 // define(["require", "exports", "blah"], function (require, exports) {
78499 // ...
78500 // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
78501 // });
78502 var resolve = ts.createUniqueName("resolve");
78503 var reject = ts.createUniqueName("reject");
78504 var parameters = [
78505 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
78506 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
78507 ];
78508 var body = ts.createBlock([
78509 ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"),
78510 /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject]))
78511 ]);
78512 var func;
78513 if (languageVersion >= 2 /* ES2015 */) {
78514 func = ts.createArrowFunction(
78515 /*modifiers*/ undefined,
78516 /*typeParameters*/ undefined, parameters,
78517 /*type*/ undefined,
78518 /*equalsGreaterThanToken*/ undefined, body);
78519 }
78520 else {
78521 func = ts.createFunctionExpression(
78522 /*modifiers*/ undefined,
78523 /*asteriskToken*/ undefined,
78524 /*name*/ undefined,
78525 /*typeParameters*/ undefined, parameters,
78526 /*type*/ undefined, body);
78527 // if there is a lexical 'this' in the import call arguments, ensure we indicate
78528 // that this new function expression indicates it captures 'this' so that the
78529 // es2015 transformer will properly substitute 'this' with '_this'.
78530 if (containsLexicalThis) {
78531 ts.setEmitFlags(func, 8 /* CapturesThis */);
78532 }
78533 }
78534 var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
78535 if (compilerOptions.esModuleInterop) {
78536 context.requestEmitHelper(ts.importStarHelper);
78537 return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
78538 }
78539 return promise;
78540 }
78541 function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
78542 // import("./blah")
78543 // emit as
78544 // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
78545 // We have to wrap require in then callback so that require is done in asynchronously
78546 // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
78547 var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
78548 var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
78549 if (compilerOptions.esModuleInterop) {
78550 context.requestEmitHelper(ts.importStarHelper);
78551 requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
78552 }
78553 var func;
78554 if (languageVersion >= 2 /* ES2015 */) {
78555 func = ts.createArrowFunction(
78556 /*modifiers*/ undefined,
78557 /*typeParameters*/ undefined,
78558 /*parameters*/ [],
78559 /*type*/ undefined,
78560 /*equalsGreaterThanToken*/ undefined, requireCall);
78561 }
78562 else {
78563 func = ts.createFunctionExpression(
78564 /*modifiers*/ undefined,
78565 /*asteriskToken*/ undefined,
78566 /*name*/ undefined,
78567 /*typeParameters*/ undefined,
78568 /*parameters*/ [],
78569 /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)]));
78570 // if there is a lexical 'this' in the import call arguments, ensure we indicate
78571 // that this new function expression indicates it captures 'this' so that the
78572 // es2015 transformer will properly substitute 'this' with '_this'.
78573 if (containsLexicalThis) {
78574 ts.setEmitFlags(func, 8 /* CapturesThis */);
78575 }
78576 }
78577 return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
78578 }
78579 function getHelperExpressionForImport(node, innerExpr) {
78580 if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
78581 return innerExpr;
78582 }
78583 if (ts.getImportNeedsImportStarHelper(node)) {
78584 context.requestEmitHelper(ts.importStarHelper);
78585 return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
78586 }
78587 if (ts.getImportNeedsImportDefaultHelper(node)) {
78588 context.requestEmitHelper(ts.importDefaultHelper);
78589 return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
78590 }
78591 return innerExpr;
78592 }
78593 /**
78594 * Visits an ImportDeclaration node.
78595 *
78596 * @param node The node to visit.
78597 */
78598 function visitImportDeclaration(node) {
78599 var statements;
78600 var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
78601 if (moduleKind !== ts.ModuleKind.AMD) {
78602 if (!node.importClause) {
78603 // import "mod";
78604 return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node);
78605 }
78606 else {
78607 var variables = [];
78608 if (namespaceDeclaration && !ts.isDefaultImport(node)) {
78609 // import * as n from "mod";
78610 variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
78611 /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
78612 }
78613 else {
78614 // import d from "mod";
78615 // import { x, y } from "mod";
78616 // import d, { x, y } from "mod";
78617 // import d, * as n from "mod";
78618 variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node),
78619 /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
78620 if (namespaceDeclaration && ts.isDefaultImport(node)) {
78621 variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
78622 /*type*/ undefined, ts.getGeneratedNameForNode(node)));
78623 }
78624 }
78625 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
78626 /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)),
78627 /*location*/ node),
78628 /*original*/ node));
78629 }
78630 }
78631 else if (namespaceDeclaration && ts.isDefaultImport(node)) {
78632 // import d, * as n from "mod";
78633 statements = ts.append(statements, ts.createVariableStatement(
78634 /*modifiers*/ undefined, ts.createVariableDeclarationList([
78635 ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
78636 /*type*/ undefined, ts.getGeneratedNameForNode(node)),
78637 /*location*/ node),
78638 /*original*/ node)
78639 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
78640 }
78641 if (hasAssociatedEndOfDeclarationMarker(node)) {
78642 // Defer exports until we encounter an EndOfDeclarationMarker node
78643 var id = ts.getOriginalNodeId(node);
78644 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
78645 }
78646 else {
78647 statements = appendExportsOfImportDeclaration(statements, node);
78648 }
78649 return ts.singleOrMany(statements);
78650 }
78651 /**
78652 * Creates a `require()` call to import an external module.
78653 *
78654 * @param importNode The declararation to import.
78655 */
78656 function createRequireCall(importNode) {
78657 var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
78658 var args = [];
78659 if (moduleName) {
78660 args.push(moduleName);
78661 }
78662 return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
78663 }
78664 /**
78665 * Visits an ImportEqualsDeclaration node.
78666 *
78667 * @param node The node to visit.
78668 */
78669 function visitImportEqualsDeclaration(node) {
78670 ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
78671 var statements;
78672 if (moduleKind !== ts.ModuleKind.AMD) {
78673 if (ts.hasModifier(node, 1 /* Export */)) {
78674 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
78675 }
78676 else {
78677 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
78678 /*modifiers*/ undefined, ts.createVariableDeclarationList([
78679 ts.createVariableDeclaration(ts.getSynthesizedClone(node.name),
78680 /*type*/ undefined, createRequireCall(node))
78681 ],
78682 /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
78683 }
78684 }
78685 else {
78686 if (ts.hasModifier(node, 1 /* Export */)) {
78687 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node));
78688 }
78689 }
78690 if (hasAssociatedEndOfDeclarationMarker(node)) {
78691 // Defer exports until we encounter an EndOfDeclarationMarker node
78692 var id = ts.getOriginalNodeId(node);
78693 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
78694 }
78695 else {
78696 statements = appendExportsOfImportEqualsDeclaration(statements, node);
78697 }
78698 return ts.singleOrMany(statements);
78699 }
78700 /**
78701 * Visits an ExportDeclaration node.
78702 *
78703 * @param The node to visit.
78704 */
78705 function visitExportDeclaration(node) {
78706 if (!node.moduleSpecifier) {
78707 // Elide export declarations with no module specifier as they are handled
78708 // elsewhere.
78709 return undefined;
78710 }
78711 var generatedName = ts.getGeneratedNameForNode(node);
78712 if (node.exportClause) {
78713 var statements = [];
78714 // export { x, y } from "mod";
78715 if (moduleKind !== ts.ModuleKind.AMD) {
78716 statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
78717 /*modifiers*/ undefined, ts.createVariableDeclarationList([
78718 ts.createVariableDeclaration(generatedName,
78719 /*type*/ undefined, createRequireCall(node))
78720 ])),
78721 /*location*/ node),
78722 /* original */ node));
78723 }
78724 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
78725 var specifier = _a[_i];
78726 var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
78727 statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier));
78728 }
78729 return ts.singleOrMany(statements);
78730 }
78731 else {
78732 // export * from "mod";
78733 return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
78734 }
78735 }
78736 /**
78737 * Visits an ExportAssignment node.
78738 *
78739 * @param node The node to visit.
78740 */
78741 function visitExportAssignment(node) {
78742 if (node.isExportEquals) {
78743 return undefined;
78744 }
78745 var statements;
78746 var original = node.original;
78747 if (original && hasAssociatedEndOfDeclarationMarker(original)) {
78748 // Defer exports until we encounter an EndOfDeclarationMarker node
78749 var id = ts.getOriginalNodeId(node);
78750 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
78751 }
78752 else {
78753 statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
78754 }
78755 return ts.singleOrMany(statements);
78756 }
78757 /**
78758 * Visits a FunctionDeclaration node.
78759 *
78760 * @param node The node to visit.
78761 */
78762 function visitFunctionDeclaration(node) {
78763 var statements;
78764 if (ts.hasModifier(node, 1 /* Export */)) {
78765 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
78766 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
78767 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor),
78768 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)),
78769 /*location*/ node),
78770 /*original*/ node));
78771 }
78772 else {
78773 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
78774 }
78775 if (hasAssociatedEndOfDeclarationMarker(node)) {
78776 // Defer exports until we encounter an EndOfDeclarationMarker node
78777 var id = ts.getOriginalNodeId(node);
78778 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
78779 }
78780 else {
78781 statements = appendExportsOfHoistedDeclaration(statements, node);
78782 }
78783 return ts.singleOrMany(statements);
78784 }
78785 /**
78786 * Visits a ClassDeclaration node.
78787 *
78788 * @param node The node to visit.
78789 */
78790 function visitClassDeclaration(node) {
78791 var statements;
78792 if (ts.hasModifier(node, 1 /* Export */)) {
78793 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
78794 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
78795 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
78796 }
78797 else {
78798 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
78799 }
78800 if (hasAssociatedEndOfDeclarationMarker(node)) {
78801 // Defer exports until we encounter an EndOfDeclarationMarker node
78802 var id = ts.getOriginalNodeId(node);
78803 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
78804 }
78805 else {
78806 statements = appendExportsOfHoistedDeclaration(statements, node);
78807 }
78808 return ts.singleOrMany(statements);
78809 }
78810 /**
78811 * Visits a VariableStatement node.
78812 *
78813 * @param node The node to visit.
78814 */
78815 function visitVariableStatement(node) {
78816 var statements;
78817 var variables;
78818 var expressions;
78819 if (ts.hasModifier(node, 1 /* Export */)) {
78820 var modifiers = void 0;
78821 // If we're exporting these variables, then these just become assignments to 'exports.x'.
78822 // We only want to emit assignments for variables with initializers.
78823 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
78824 var variable = _a[_i];
78825 if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
78826 if (!modifiers) {
78827 modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
78828 }
78829 variables = ts.append(variables, variable);
78830 }
78831 else if (variable.initializer) {
78832 expressions = ts.append(expressions, transformInitializedVariable(variable));
78833 }
78834 }
78835 if (variables) {
78836 statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
78837 }
78838 if (expressions) {
78839 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node));
78840 }
78841 }
78842 else {
78843 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
78844 }
78845 if (hasAssociatedEndOfDeclarationMarker(node)) {
78846 // Defer exports until we encounter an EndOfDeclarationMarker node
78847 var id = ts.getOriginalNodeId(node);
78848 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
78849 }
78850 else {
78851 statements = appendExportsOfVariableStatement(statements, node);
78852 }
78853 return ts.singleOrMany(statements);
78854 }
78855 function createAllExportExpressions(name, value, location) {
78856 var exportedNames = getExports(name);
78857 if (exportedNames) {
78858 // For each additional export of the declaration, apply an export assignment.
78859 var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
78860 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
78861 var exportName = exportedNames_1[_i];
78862 // Mark the node to prevent triggering substitution.
78863 ts.setEmitFlags(expression, 4 /* NoSubstitution */);
78864 expression = createExportExpression(exportName, expression, /*location*/ location);
78865 }
78866 return expression;
78867 }
78868 return ts.createAssignment(name, value);
78869 }
78870 /**
78871 * Transforms an exported variable with an initializer into an expression.
78872 *
78873 * @param node The node to transform.
78874 */
78875 function transformInitializedVariable(node) {
78876 if (ts.isBindingPattern(node.name)) {
78877 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor),
78878 /*visitor*/ undefined, context, 0 /* All */,
78879 /*needsValue*/ false, createAllExportExpressions);
78880 }
78881 else {
78882 return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name),
78883 /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor));
78884 }
78885 }
78886 /**
78887 * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
78888 * and transformed declaration.
78889 *
78890 * @param node The node to visit.
78891 */
78892 function visitMergeDeclarationMarker(node) {
78893 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
78894 // declaration we do not emit a leading variable declaration. To preserve the
78895 // begin/end semantics of the declararation and to properly handle exports
78896 // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
78897 //
78898 // To balance the declaration, add the exports of the elided variable
78899 // statement.
78900 if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) {
78901 var id = ts.getOriginalNodeId(node);
78902 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
78903 }
78904 return node;
78905 }
78906 /**
78907 * Determines whether a node has an associated EndOfDeclarationMarker.
78908 *
78909 * @param node The node to test.
78910 */
78911 function hasAssociatedEndOfDeclarationMarker(node) {
78912 return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
78913 }
78914 /**
78915 * Visits a DeclarationMarker used as a placeholder for the end of a transformed
78916 * declaration.
78917 *
78918 * @param node The node to visit.
78919 */
78920 function visitEndOfDeclarationMarker(node) {
78921 // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
78922 // end of the transformed declaration. We use this marker to emit any deferred exports
78923 // of the declaration.
78924 var id = ts.getOriginalNodeId(node);
78925 var statements = deferredExports[id];
78926 if (statements) {
78927 delete deferredExports[id];
78928 return ts.append(statements, node);
78929 }
78930 return node;
78931 }
78932 /**
78933 * Appends the exports of an ImportDeclaration to a statement list, returning the
78934 * statement list.
78935 *
78936 * @param statements A statement list to which the down-level export statements are to be
78937 * appended. If `statements` is `undefined`, a new array is allocated if statements are
78938 * appended.
78939 * @param decl The declaration whose exports are to be recorded.
78940 */
78941 function appendExportsOfImportDeclaration(statements, decl) {
78942 if (currentModuleInfo.exportEquals) {
78943 return statements;
78944 }
78945 var importClause = decl.importClause;
78946 if (!importClause) {
78947 return statements;
78948 }
78949 if (importClause.name) {
78950 statements = appendExportsOfDeclaration(statements, importClause);
78951 }
78952 var namedBindings = importClause.namedBindings;
78953 if (namedBindings) {
78954 switch (namedBindings.kind) {
78955 case 251 /* NamespaceImport */:
78956 statements = appendExportsOfDeclaration(statements, namedBindings);
78957 break;
78958 case 252 /* NamedImports */:
78959 for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
78960 var importBinding = _a[_i];
78961 statements = appendExportsOfDeclaration(statements, importBinding);
78962 }
78963 break;
78964 }
78965 }
78966 return statements;
78967 }
78968 /**
78969 * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
78970 * statement list.
78971 *
78972 * @param statements A statement list to which the down-level export statements are to be
78973 * appended. If `statements` is `undefined`, a new array is allocated if statements are
78974 * appended.
78975 * @param decl The declaration whose exports are to be recorded.
78976 */
78977 function appendExportsOfImportEqualsDeclaration(statements, decl) {
78978 if (currentModuleInfo.exportEquals) {
78979 return statements;
78980 }
78981 return appendExportsOfDeclaration(statements, decl);
78982 }
78983 /**
78984 * Appends the exports of a VariableStatement to a statement list, returning the statement
78985 * list.
78986 *
78987 * @param statements A statement list to which the down-level export statements are to be
78988 * appended. If `statements` is `undefined`, a new array is allocated if statements are
78989 * appended.
78990 * @param node The VariableStatement whose exports are to be recorded.
78991 */
78992 function appendExportsOfVariableStatement(statements, node) {
78993 if (currentModuleInfo.exportEquals) {
78994 return statements;
78995 }
78996 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
78997 var decl = _a[_i];
78998 statements = appendExportsOfBindingElement(statements, decl);
78999 }
79000 return statements;
79001 }
79002 /**
79003 * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
79004 * returning the statement list.
79005 *
79006 * @param statements A statement list to which the down-level export statements are to be
79007 * appended. If `statements` is `undefined`, a new array is allocated if statements are
79008 * appended.
79009 * @param decl The declaration whose exports are to be recorded.
79010 */
79011 function appendExportsOfBindingElement(statements, decl) {
79012 if (currentModuleInfo.exportEquals) {
79013 return statements;
79014 }
79015 if (ts.isBindingPattern(decl.name)) {
79016 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
79017 var element = _a[_i];
79018 if (!ts.isOmittedExpression(element)) {
79019 statements = appendExportsOfBindingElement(statements, element);
79020 }
79021 }
79022 }
79023 else if (!ts.isGeneratedIdentifier(decl.name)) {
79024 statements = appendExportsOfDeclaration(statements, decl);
79025 }
79026 return statements;
79027 }
79028 /**
79029 * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
79030 * returning the statement list.
79031 *
79032 * @param statements A statement list to which the down-level export statements are to be
79033 * appended. If `statements` is `undefined`, a new array is allocated if statements are
79034 * appended.
79035 * @param decl The declaration whose exports are to be recorded.
79036 */
79037 function appendExportsOfHoistedDeclaration(statements, decl) {
79038 if (currentModuleInfo.exportEquals) {
79039 return statements;
79040 }
79041 if (ts.hasModifier(decl, 1 /* Export */)) {
79042 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl);
79043 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
79044 }
79045 if (decl.name) {
79046 statements = appendExportsOfDeclaration(statements, decl);
79047 }
79048 return statements;
79049 }
79050 /**
79051 * Appends the exports of a declaration to a statement list, returning the statement list.
79052 *
79053 * @param statements A statement list to which the down-level export statements are to be
79054 * appended. If `statements` is `undefined`, a new array is allocated if statements are
79055 * appended.
79056 * @param decl The declaration to export.
79057 */
79058 function appendExportsOfDeclaration(statements, decl) {
79059 var name = ts.getDeclarationName(decl);
79060 var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
79061 if (exportSpecifiers) {
79062 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
79063 var exportSpecifier = exportSpecifiers_1[_i];
79064 statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name);
79065 }
79066 }
79067 return statements;
79068 }
79069 /**
79070 * Appends the down-level representation of an export to a statement list, returning the
79071 * statement list.
79072 *
79073 * @param statements A statement list to which the down-level export statements are to be
79074 * appended. If `statements` is `undefined`, a new array is allocated if statements are
79075 * appended.
79076 * @param exportName The name of the export.
79077 * @param expression The expression to export.
79078 * @param location The location to use for source maps and comments for the export.
79079 * @param allowComments Whether to allow comments on the export.
79080 */
79081 function appendExportStatement(statements, exportName, expression, location, allowComments) {
79082 statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments));
79083 return statements;
79084 }
79085 function createUnderscoreUnderscoreESModule() {
79086 var statement;
79087 if (languageVersion === 0 /* ES3 */) {
79088 statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true)));
79089 }
79090 else {
79091 statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
79092 /*typeArguments*/ undefined, [
79093 ts.createIdentifier("exports"),
79094 ts.createLiteral("__esModule"),
79095 ts.createObjectLiteral([
79096 ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true))
79097 ])
79098 ]));
79099 }
79100 ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
79101 return statement;
79102 }
79103 /**
79104 * Creates a call to the current file's export function to export a value.
79105 *
79106 * @param name The bound name of the export.
79107 * @param value The exported value.
79108 * @param location The location to use for source maps and comments for the export.
79109 * @param allowComments An optional value indicating whether to emit comments for the statement.
79110 */
79111 function createExportStatement(name, value, location, allowComments) {
79112 var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location);
79113 ts.startOnNewLine(statement);
79114 if (!allowComments) {
79115 ts.setEmitFlags(statement, 1536 /* NoComments */);
79116 }
79117 return statement;
79118 }
79119 /**
79120 * Creates a call to the current file's export function to export a value.
79121 *
79122 * @param name The bound name of the export.
79123 * @param value The exported value.
79124 * @param location The location to use for source maps and comments for the export.
79125 */
79126 function createExportExpression(name, value, location) {
79127 return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location);
79128 }
79129 //
79130 // Modifier Visitors
79131 //
79132 /**
79133 * Visit nodes to elide module-specific modifiers.
79134 *
79135 * @param node The node to visit.
79136 */
79137 function modifierVisitor(node) {
79138 // Elide module-specific modifiers.
79139 switch (node.kind) {
79140 case 85 /* ExportKeyword */:
79141 case 80 /* DefaultKeyword */:
79142 return undefined;
79143 }
79144 return node;
79145 }
79146 //
79147 // Emit Notification
79148 //
79149 /**
79150 * Hook for node emit notifications.
79151 *
79152 * @param hint A hint as to the intended usage of the node.
79153 * @param node The node to emit.
79154 * @param emit A callback used to emit the node in the printer.
79155 */
79156 function onEmitNode(hint, node, emitCallback) {
79157 if (node.kind === 284 /* SourceFile */) {
79158 currentSourceFile = node;
79159 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
79160 noSubstitution = [];
79161 previousOnEmitNode(hint, node, emitCallback);
79162 currentSourceFile = undefined;
79163 currentModuleInfo = undefined;
79164 noSubstitution = undefined;
79165 }
79166 else {
79167 previousOnEmitNode(hint, node, emitCallback);
79168 }
79169 }
79170 //
79171 // Substitutions
79172 //
79173 /**
79174 * Hooks node substitutions.
79175 *
79176 * @param hint A hint as to the intended usage of the node.
79177 * @param node The node to substitute.
79178 */
79179 function onSubstituteNode(hint, node) {
79180 node = previousOnSubstituteNode(hint, node);
79181 if (node.id && noSubstitution[node.id]) {
79182 return node;
79183 }
79184 if (hint === 1 /* Expression */) {
79185 return substituteExpression(node);
79186 }
79187 else if (ts.isShorthandPropertyAssignment(node)) {
79188 return substituteShorthandPropertyAssignment(node);
79189 }
79190 return node;
79191 }
79192 /**
79193 * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
79194 * or exported symbol.
79195 *
79196 * @param node The node to substitute.
79197 */
79198 function substituteShorthandPropertyAssignment(node) {
79199 var name = node.name;
79200 var exportedOrImportedName = substituteExpressionIdentifier(name);
79201 if (exportedOrImportedName !== name) {
79202 // A shorthand property with an assignment initializer is probably part of a
79203 // destructuring assignment
79204 if (node.objectAssignmentInitializer) {
79205 var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
79206 return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
79207 }
79208 return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node);
79209 }
79210 return node;
79211 }
79212 /**
79213 * Substitution for an Expression that may contain an imported or exported symbol.
79214 *
79215 * @param node The node to substitute.
79216 */
79217 function substituteExpression(node) {
79218 switch (node.kind) {
79219 case 72 /* Identifier */:
79220 return substituteExpressionIdentifier(node);
79221 case 204 /* BinaryExpression */:
79222 return substituteBinaryExpression(node);
79223 case 203 /* PostfixUnaryExpression */:
79224 case 202 /* PrefixUnaryExpression */:
79225 return substituteUnaryExpression(node);
79226 }
79227 return node;
79228 }
79229 /**
79230 * Substitution for an Identifier expression that may contain an imported or exported
79231 * symbol.
79232 *
79233 * @param node The node to substitute.
79234 */
79235 function substituteExpressionIdentifier(node) {
79236 if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
79237 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
79238 if (externalHelpersModuleName) {
79239 return ts.createPropertyAccess(externalHelpersModuleName, node);
79240 }
79241 return node;
79242 }
79243 if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
79244 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
79245 if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
79246 return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
79247 /*location*/ node);
79248 }
79249 var importDeclaration = resolver.getReferencedImportDeclaration(node);
79250 if (importDeclaration) {
79251 if (ts.isImportClause(importDeclaration)) {
79252 return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")),
79253 /*location*/ node);
79254 }
79255 else if (ts.isImportSpecifier(importDeclaration)) {
79256 var name = importDeclaration.propertyName || importDeclaration.name;
79257 return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)),
79258 /*location*/ node);
79259 }
79260 }
79261 }
79262 return node;
79263 }
79264 /**
79265 * Substitution for a BinaryExpression that may contain an imported or exported symbol.
79266 *
79267 * @param node The node to substitute.
79268 */
79269 function substituteBinaryExpression(node) {
79270 // When we see an assignment expression whose left-hand side is an exported symbol,
79271 // we should ensure all exports of that symbol are updated with the correct value.
79272 //
79273 // - We do not substitute generated identifiers for any reason.
79274 // - We do not substitute identifiers tagged with the LocalName flag.
79275 // - We do not substitute identifiers that were originally the name of an enum or
79276 // namespace due to how they are transformed in TypeScript.
79277 // - We only substitute identifiers that are exported at the top level.
79278 if (ts.isAssignmentOperator(node.operatorToken.kind)
79279 && ts.isIdentifier(node.left)
79280 && !ts.isGeneratedIdentifier(node.left)
79281 && !ts.isLocalName(node.left)
79282 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
79283 var exportedNames = getExports(node.left);
79284 if (exportedNames) {
79285 // For each additional export of the declaration, apply an export assignment.
79286 var expression = node;
79287 for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
79288 var exportName = exportedNames_2[_i];
79289 // Mark the node to prevent triggering this rule again.
79290 noSubstitution[ts.getNodeId(expression)] = true;
79291 expression = createExportExpression(exportName, expression, /*location*/ node);
79292 }
79293 return expression;
79294 }
79295 }
79296 return node;
79297 }
79298 /**
79299 * Substitution for a UnaryExpression that may contain an imported or exported symbol.
79300 *
79301 * @param node The node to substitute.
79302 */
79303 function substituteUnaryExpression(node) {
79304 // When we see a prefix or postfix increment expression whose operand is an exported
79305 // symbol, we should ensure all exports of that symbol are updated with the correct
79306 // value.
79307 //
79308 // - We do not substitute generated identifiers for any reason.
79309 // - We do not substitute identifiers tagged with the LocalName flag.
79310 // - We do not substitute identifiers that were originally the name of an enum or
79311 // namespace due to how they are transformed in TypeScript.
79312 // - We only substitute identifiers that are exported at the top level.
79313 if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */)
79314 && ts.isIdentifier(node.operand)
79315 && !ts.isGeneratedIdentifier(node.operand)
79316 && !ts.isLocalName(node.operand)
79317 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
79318 var exportedNames = getExports(node.operand);
79319 if (exportedNames) {
79320 var expression = node.kind === 203 /* PostfixUnaryExpression */
79321 ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 44 /* PlusPlusToken */ ? 60 /* PlusEqualsToken */ : 61 /* MinusEqualsToken */), ts.createLiteral(1)),
79322 /*location*/ node)
79323 : node;
79324 for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
79325 var exportName = exportedNames_3[_i];
79326 // Mark the node to prevent triggering this rule again.
79327 noSubstitution[ts.getNodeId(expression)] = true;
79328 expression = createExportExpression(exportName, expression);
79329 }
79330 return expression;
79331 }
79332 }
79333 return node;
79334 }
79335 /**
79336 * Gets the additional exports of a name.
79337 *
79338 * @param name The name.
79339 */
79340 function getExports(name) {
79341 if (!ts.isGeneratedIdentifier(name)) {
79342 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
79343 || resolver.getReferencedValueDeclaration(name);
79344 if (valueDeclaration) {
79345 return currentModuleInfo
79346 && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
79347 }
79348 }
79349 }
79350 }
79351 ts.transformModule = transformModule;
79352 // emit output for the __export helper function
79353 var exportStarHelper = {
79354 name: "typescript:export-star",
79355 scoped: true,
79356 text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }"
79357 };
79358 function createExportStarHelper(context, module) {
79359 var compilerOptions = context.getCompilerOptions();
79360 return compilerOptions.importHelpers
79361 ? ts.createCall(ts.getHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")])
79362 : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]);
79363 }
79364 // emit helper for dynamic import
79365 var dynamicImportUMDHelper = {
79366 name: "typescript:dynamicimport-sync-require",
79367 scoped: true,
79368 text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
79369 };
79370 // emit helper for `import * as Name from "foo"`
79371 ts.importStarHelper = {
79372 name: "typescript:commonjsimportstar",
79373 scoped: false,
79374 text: "\nvar __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 (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
79375 };
79376 // emit helper for `import Name from "foo"`
79377 ts.importDefaultHelper = {
79378 name: "typescript:commonjsimportdefault",
79379 scoped: false,
79380 text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
79381 };
79382})(ts || (ts = {}));
79383/*@internal*/
79384var ts;
79385(function (ts) {
79386 function transformSystemModule(context) {
79387 var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
79388 var compilerOptions = context.getCompilerOptions();
79389 var resolver = context.getEmitResolver();
79390 var host = context.getEmitHost();
79391 var previousOnSubstituteNode = context.onSubstituteNode;
79392 var previousOnEmitNode = context.onEmitNode;
79393 context.onSubstituteNode = onSubstituteNode;
79394 context.onEmitNode = onEmitNode;
79395 context.enableSubstitution(72 /* Identifier */); // Substitutes expression identifiers for imported symbols.
79396 context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
79397 context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
79398 context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
79399 context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
79400 context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
79401 var moduleInfoMap = []; // The ExternalModuleInfo for each file.
79402 var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
79403 var exportFunctionsMap = []; // The export function associated with a source file.
79404 var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
79405 var currentSourceFile; // The current file.
79406 var moduleInfo; // ExternalModuleInfo for the current file.
79407 var exportFunction; // The export function for the current file.
79408 var contextObject; // The context object for the current file.
79409 var hoistedStatements;
79410 var enclosingBlockScopedContainer;
79411 var noSubstitution; // Set of nodes for which substitution rules should be ignored.
79412 return ts.chainBundle(transformSourceFile);
79413 /**
79414 * Transforms the module aspects of a SourceFile.
79415 *
79416 * @param node The SourceFile node.
79417 */
79418 function transformSourceFile(node) {
79419 if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) {
79420 return node;
79421 }
79422 var id = ts.getOriginalNodeId(node);
79423 currentSourceFile = node;
79424 enclosingBlockScopedContainer = node;
79425 // System modules have the following shape:
79426 //
79427 // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
79428 //
79429 // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
79430 // is used to publish exported values. 'exports' returns its 'value' argument so in
79431 // most cases expressions that mutate exported values can be rewritten as:
79432 //
79433 // expr -> exports('name', expr)
79434 //
79435 // The only exception in this rule is postfix unary operators,
79436 // see comment to 'substitutePostfixUnaryExpression' for more details
79437 // Collect information about the external module and dependency groups.
79438 moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
79439 // Make sure that the name of the 'exports' function does not conflict with
79440 // existing identifiers.
79441 exportFunction = ts.createUniqueName("exports");
79442 exportFunctionsMap[id] = exportFunction;
79443 contextObject = ts.createUniqueName("context");
79444 // Add the body of the module.
79445 var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
79446 var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
79447 var moduleBodyFunction = ts.createFunctionExpression(
79448 /*modifiers*/ undefined,
79449 /*asteriskToken*/ undefined,
79450 /*name*/ undefined,
79451 /*typeParameters*/ undefined, [
79452 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
79453 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
79454 ],
79455 /*type*/ undefined, moduleBodyBlock);
79456 // Write the call to `System.register`
79457 // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
79458 // So the helper will be emit at the correct position instead of at the top of the source-file
79459 var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
79460 var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
79461 var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
79462 ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"),
79463 /*typeArguments*/ undefined, moduleName
79464 ? [moduleName, dependencies, moduleBodyFunction]
79465 : [dependencies, moduleBodyFunction]))
79466 ]), node.statements)), 1024 /* NoTrailingComments */);
79467 if (!(compilerOptions.outFile || compilerOptions.out)) {
79468 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
79469 }
79470 if (noSubstitution) {
79471 noSubstitutionMap[id] = noSubstitution;
79472 noSubstitution = undefined;
79473 }
79474 currentSourceFile = undefined;
79475 moduleInfo = undefined;
79476 exportFunction = undefined;
79477 contextObject = undefined;
79478 hoistedStatements = undefined;
79479 enclosingBlockScopedContainer = undefined;
79480 return ts.aggregateTransformFlags(updated);
79481 }
79482 /**
79483 * Collects the dependency groups for this files imports.
79484 *
79485 * @param externalImports The imports for the file.
79486 */
79487 function collectDependencyGroups(externalImports) {
79488 var groupIndices = ts.createMap();
79489 var dependencyGroups = [];
79490 for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
79491 var externalImport = externalImports_1[_i];
79492 var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
79493 if (externalModuleName) {
79494 var text = externalModuleName.text;
79495 var groupIndex = groupIndices.get(text);
79496 if (groupIndex !== undefined) {
79497 // deduplicate/group entries in dependency list by the dependency name
79498 dependencyGroups[groupIndex].externalImports.push(externalImport);
79499 }
79500 else {
79501 groupIndices.set(text, dependencyGroups.length);
79502 dependencyGroups.push({
79503 name: externalModuleName,
79504 externalImports: [externalImport]
79505 });
79506 }
79507 }
79508 }
79509 return dependencyGroups;
79510 }
79511 /**
79512 * Adds the statements for the module body function for the source file.
79513 *
79514 * @param node The source file for the module.
79515 * @param dependencyGroups The grouped dependencies of the module.
79516 */
79517 function createSystemModuleBody(node, dependencyGroups) {
79518 // Shape of the body in system modules:
79519 //
79520 // function (exports) {
79521 // <list of local aliases for imports>
79522 // <hoisted variable declarations>
79523 // <hoisted function declarations>
79524 // return {
79525 // setters: [
79526 // <list of setter function for imports>
79527 // ],
79528 // execute: function() {
79529 // <module statements>
79530 // }
79531 // }
79532 // <temp declarations>
79533 // }
79534 //
79535 // i.e:
79536 //
79537 // import {x} from 'file1'
79538 // var y = 1;
79539 // export function foo() { return y + x(); }
79540 // console.log(y);
79541 //
79542 // Will be transformed to:
79543 //
79544 // function(exports) {
79545 // function foo() { return y + file_1.x(); }
79546 // exports("foo", foo);
79547 // var file_1, y;
79548 // return {
79549 // setters: [
79550 // function(v) { file_1 = v }
79551 // ],
79552 // execute(): function() {
79553 // y = 1;
79554 // console.log(y);
79555 // }
79556 // };
79557 // }
79558 var statements = [];
79559 // We start a new lexical environment in this function body, but *not* in the
79560 // body of the execute function. This allows us to emit temporary declarations
79561 // only in the outer module body and not in the inner one.
79562 startLexicalEnvironment();
79563 // Add any prologue directives.
79564 var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
79565 var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
79566 // var __moduleName = context_1 && context_1.id;
79567 statements.push(ts.createVariableStatement(
79568 /*modifiers*/ undefined, ts.createVariableDeclarationList([
79569 ts.createVariableDeclaration("__moduleName",
79570 /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id")))
79571 ])));
79572 // Visit the synthetic external helpers import declaration if present
79573 ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
79574 // Visit the statements of the source file, emitting any transformations into
79575 // the `executeStatements` array. We do this *before* we fill the `setters` array
79576 // as we both emit transformations as well as aggregate some data used when creating
79577 // setters. This allows us to reduce the number of times we need to loop through the
79578 // statements of the source file.
79579 var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
79580 // Emit early exports for function declarations.
79581 ts.addRange(statements, hoistedStatements);
79582 // We emit hoisted variables early to align roughly with our previous emit output.
79583 // Two key differences in this approach are:
79584 // - Temporary variables will appear at the top rather than at the bottom of the file
79585 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79586 var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
79587 var moduleObject = ts.createObjectLiteral([
79588 ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
79589 ts.createPropertyAssignment("execute", ts.createFunctionExpression(
79590 /*modifiers*/ undefined,
79591 /*asteriskToken*/ undefined,
79592 /*name*/ undefined,
79593 /*typeParameters*/ undefined,
79594 /*parameters*/ [],
79595 /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true)))
79596 ]);
79597 moduleObject.multiLine = true;
79598 statements.push(ts.createReturn(moduleObject));
79599 return ts.createBlock(statements, /*multiLine*/ true);
79600 }
79601 /**
79602 * Adds an exportStar function to a statement list if it is needed for the file.
79603 *
79604 * @param statements A statement list.
79605 */
79606 function addExportStarIfNeeded(statements) {
79607 if (!moduleInfo.hasExportStarsToExportValues) {
79608 return;
79609 }
79610 // when resolving exports local exported entries/indirect exported entries in the module
79611 // should always win over entries with similar names that were added via star exports
79612 // to support this we store names of local/indirect exported entries in a set.
79613 // this set is used to filter names brought by star expors.
79614 // local names set should only be added if we have anything exported
79615 if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
79616 // no exported declarations (export var ...) or export specifiers (export {x})
79617 // check if we have any non star export declarations.
79618 var hasExportDeclarationWithExportClause = false;
79619 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
79620 var externalImport = _a[_i];
79621 if (externalImport.kind === 255 /* ExportDeclaration */ && externalImport.exportClause) {
79622 hasExportDeclarationWithExportClause = true;
79623 break;
79624 }
79625 }
79626 if (!hasExportDeclarationWithExportClause) {
79627 // we still need to emit exportStar helper
79628 var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
79629 statements.push(exportStarFunction_1);
79630 return exportStarFunction_1.name;
79631 }
79632 }
79633 var exportedNames = [];
79634 if (moduleInfo.exportedNames) {
79635 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
79636 var exportedLocalName = _c[_b];
79637 if (exportedLocalName.escapedText === "default") {
79638 continue;
79639 }
79640 // write name of exported declaration, i.e 'export var x...'
79641 exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue()));
79642 }
79643 }
79644 for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) {
79645 var externalImport = _e[_d];
79646 if (externalImport.kind !== 255 /* ExportDeclaration */) {
79647 continue;
79648 }
79649 if (!externalImport.exportClause) {
79650 // export * from ...
79651 continue;
79652 }
79653 for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) {
79654 var element = _g[_f];
79655 // write name of indirectly exported entry, i.e. 'export {x} from ...'
79656 exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue()));
79657 }
79658 }
79659 var exportedNamesStorageRef = ts.createUniqueName("exportedNames");
79660 statements.push(ts.createVariableStatement(
79661 /*modifiers*/ undefined, ts.createVariableDeclarationList([
79662 ts.createVariableDeclaration(exportedNamesStorageRef,
79663 /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true))
79664 ])));
79665 var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
79666 statements.push(exportStarFunction);
79667 return exportStarFunction.name;
79668 }
79669 /**
79670 * Creates an exportStar function for the file, with an optional set of excluded local
79671 * names.
79672 *
79673 * @param localNames An optional reference to an object containing a set of excluded local
79674 * names.
79675 */
79676 function createExportStarFunction(localNames) {
79677 var exportStarFunction = ts.createUniqueName("exportStar");
79678 var m = ts.createIdentifier("m");
79679 var n = ts.createIdentifier("n");
79680 var exports = ts.createIdentifier("exports");
79681 var condition = ts.createStrictInequality(n, ts.createLiteral("default"));
79682 if (localNames) {
79683 condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"),
79684 /*typeArguments*/ undefined, [n])));
79685 }
79686 return ts.createFunctionDeclaration(
79687 /*decorators*/ undefined,
79688 /*modifiers*/ undefined,
79689 /*asteriskToken*/ undefined, exportStarFunction,
79690 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)],
79691 /*type*/ undefined, ts.createBlock([
79692 ts.createVariableStatement(
79693 /*modifiers*/ undefined, ts.createVariableDeclarationList([
79694 ts.createVariableDeclaration(exports,
79695 /*type*/ undefined, ts.createObjectLiteral([]))
79696 ])),
79697 ts.createForIn(ts.createVariableDeclarationList([
79698 ts.createVariableDeclaration(n, /*type*/ undefined)
79699 ]), m, ts.createBlock([
79700 ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */)
79701 ])),
79702 ts.createExpressionStatement(ts.createCall(exportFunction,
79703 /*typeArguments*/ undefined, [exports]))
79704 ], /*multiline*/ true));
79705 }
79706 /**
79707 * Creates an array setter callbacks for each dependency group.
79708 *
79709 * @param exportStarFunction A reference to an exportStarFunction for the file.
79710 * @param dependencyGroups An array of grouped dependencies.
79711 */
79712 function createSettersArray(exportStarFunction, dependencyGroups) {
79713 var setters = [];
79714 for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
79715 var group_1 = dependencyGroups_1[_i];
79716 // derive a unique name for parameter from the first named entry in the group
79717 var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
79718 var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
79719 var statements = [];
79720 for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) {
79721 var entry = _b[_a];
79722 var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217
79723 switch (entry.kind) {
79724 case 249 /* ImportDeclaration */:
79725 if (!entry.importClause) {
79726 // 'import "..."' case
79727 // module is imported only for side-effects, no emit required
79728 break;
79729 }
79730 // falls through
79731 case 248 /* ImportEqualsDeclaration */:
79732 ts.Debug.assert(importVariableName !== undefined);
79733 // save import into the local
79734 statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName)));
79735 break;
79736 case 255 /* ExportDeclaration */:
79737 ts.Debug.assert(importVariableName !== undefined);
79738 if (entry.exportClause) {
79739 // export {a, b as c} from 'foo'
79740 //
79741 // emit as:
79742 //
79743 // exports_({
79744 // "a": _["a"],
79745 // "c": _["b"]
79746 // });
79747 var properties = [];
79748 for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
79749 var e = _d[_c];
79750 properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name)))));
79751 }
79752 statements.push(ts.createExpressionStatement(ts.createCall(exportFunction,
79753 /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)])));
79754 }
79755 else {
79756 // export * from 'foo'
79757 //
79758 // emit as:
79759 //
79760 // exportStar(foo_1_1);
79761 statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction,
79762 /*typeArguments*/ undefined, [parameterName])));
79763 }
79764 break;
79765 }
79766 }
79767 setters.push(ts.createFunctionExpression(
79768 /*modifiers*/ undefined,
79769 /*asteriskToken*/ undefined,
79770 /*name*/ undefined,
79771 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
79772 /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true)));
79773 }
79774 return ts.createArrayLiteral(setters, /*multiLine*/ true);
79775 }
79776 //
79777 // Top-level Source Element Visitors
79778 //
79779 /**
79780 * Visit source elements at the top-level of a module.
79781 *
79782 * @param node The node to visit.
79783 */
79784 function sourceElementVisitor(node) {
79785 switch (node.kind) {
79786 case 249 /* ImportDeclaration */:
79787 return visitImportDeclaration(node);
79788 case 248 /* ImportEqualsDeclaration */:
79789 return visitImportEqualsDeclaration(node);
79790 case 255 /* ExportDeclaration */:
79791 // ExportDeclarations are elided as they are handled via
79792 // `appendExportsOfDeclaration`.
79793 return undefined;
79794 case 254 /* ExportAssignment */:
79795 return visitExportAssignment(node);
79796 default:
79797 return nestedElementVisitor(node);
79798 }
79799 }
79800 /**
79801 * Visits an ImportDeclaration node.
79802 *
79803 * @param node The node to visit.
79804 */
79805 function visitImportDeclaration(node) {
79806 var statements;
79807 if (node.importClause) {
79808 hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
79809 }
79810 if (hasAssociatedEndOfDeclarationMarker(node)) {
79811 // Defer exports until we encounter an EndOfDeclarationMarker node
79812 var id = ts.getOriginalNodeId(node);
79813 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
79814 }
79815 else {
79816 statements = appendExportsOfImportDeclaration(statements, node);
79817 }
79818 return ts.singleOrMany(statements);
79819 }
79820 /**
79821 * Visits an ImportEqualsDeclaration node.
79822 *
79823 * @param node The node to visit.
79824 */
79825 function visitImportEqualsDeclaration(node) {
79826 ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
79827 var statements;
79828 hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
79829 if (hasAssociatedEndOfDeclarationMarker(node)) {
79830 // Defer exports until we encounter an EndOfDeclarationMarker node
79831 var id = ts.getOriginalNodeId(node);
79832 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
79833 }
79834 else {
79835 statements = appendExportsOfImportEqualsDeclaration(statements, node);
79836 }
79837 return ts.singleOrMany(statements);
79838 }
79839 /**
79840 * Visits an ExportAssignment node.
79841 *
79842 * @param node The node to visit.
79843 */
79844 function visitExportAssignment(node) {
79845 if (node.isExportEquals) {
79846 // Elide `export=` as it is illegal in a SystemJS module.
79847 return undefined;
79848 }
79849 var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
79850 var original = node.original;
79851 if (original && hasAssociatedEndOfDeclarationMarker(original)) {
79852 // Defer exports until we encounter an EndOfDeclarationMarker node
79853 var id = ts.getOriginalNodeId(node);
79854 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true);
79855 }
79856 else {
79857 return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true);
79858 }
79859 }
79860 /**
79861 * Visits a FunctionDeclaration, hoisting it to the outer module body function.
79862 *
79863 * @param node The node to visit.
79864 */
79865 function visitFunctionDeclaration(node) {
79866 if (ts.hasModifier(node, 1 /* Export */)) {
79867 hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
79868 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration),
79869 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
79870 }
79871 else {
79872 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
79873 }
79874 if (hasAssociatedEndOfDeclarationMarker(node)) {
79875 // Defer exports until we encounter an EndOfDeclarationMarker node
79876 var id = ts.getOriginalNodeId(node);
79877 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
79878 }
79879 else {
79880 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
79881 }
79882 return undefined;
79883 }
79884 /**
79885 * Visits a ClassDeclaration, hoisting its name to the outer module body function.
79886 *
79887 * @param node The node to visit.
79888 */
79889 function visitClassDeclaration(node) {
79890 var statements;
79891 // Hoist the name of the class declaration to the outer module body function.
79892 var name = ts.getLocalName(node);
79893 hoistVariableDeclaration(name);
79894 // Rewrite the class declaration into an assignment of a class expression.
79895 statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(
79896 /*modifiers*/ undefined, node.name,
79897 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
79898 if (hasAssociatedEndOfDeclarationMarker(node)) {
79899 // Defer exports until we encounter an EndOfDeclarationMarker node
79900 var id = ts.getOriginalNodeId(node);
79901 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
79902 }
79903 else {
79904 statements = appendExportsOfHoistedDeclaration(statements, node);
79905 }
79906 return ts.singleOrMany(statements);
79907 }
79908 /**
79909 * Visits a variable statement, hoisting declared names to the top-level module body.
79910 * Each declaration is rewritten into an assignment expression.
79911 *
79912 * @param node The node to visit.
79913 */
79914 function visitVariableStatement(node) {
79915 if (!shouldHoistVariableDeclarationList(node.declarationList)) {
79916 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
79917 }
79918 var expressions;
79919 var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */);
79920 var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
79921 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
79922 var variable = _a[_i];
79923 if (variable.initializer) {
79924 expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
79925 }
79926 else {
79927 hoistBindingElement(variable);
79928 }
79929 }
79930 var statements;
79931 if (expressions) {
79932 statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node));
79933 }
79934 if (isMarkedDeclaration) {
79935 // Defer exports until we encounter an EndOfDeclarationMarker node
79936 var id = ts.getOriginalNodeId(node);
79937 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
79938 }
79939 else {
79940 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
79941 }
79942 return ts.singleOrMany(statements);
79943 }
79944 /**
79945 * Hoists the declared names of a VariableDeclaration or BindingElement.
79946 *
79947 * @param node The declaration to hoist.
79948 */
79949 function hoistBindingElement(node) {
79950 if (ts.isBindingPattern(node.name)) {
79951 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
79952 var element = _a[_i];
79953 if (!ts.isOmittedExpression(element)) {
79954 hoistBindingElement(element);
79955 }
79956 }
79957 }
79958 else {
79959 hoistVariableDeclaration(ts.getSynthesizedClone(node.name));
79960 }
79961 }
79962 /**
79963 * Determines whether a VariableDeclarationList should be hoisted.
79964 *
79965 * @param node The node to test.
79966 */
79967 function shouldHoistVariableDeclarationList(node) {
79968 // hoist only non-block scoped declarations or block scoped declarations parented by source file
79969 return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
79970 && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
79971 || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
79972 }
79973 /**
79974 * Transform an initialized variable declaration into an expression.
79975 *
79976 * @param node The node to transform.
79977 * @param isExportedDeclaration A value indicating whether the variable is exported.
79978 */
79979 function transformInitializedVariable(node, isExportedDeclaration) {
79980 var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
79981 return ts.isBindingPattern(node.name)
79982 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */,
79983 /*needsValue*/ false, createAssignment)
79984 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
79985 }
79986 /**
79987 * Creates an assignment expression for an exported variable declaration.
79988 *
79989 * @param name The name of the variable.
79990 * @param value The value of the variable's initializer.
79991 * @param location The source map location for the assignment.
79992 */
79993 function createExportedVariableAssignment(name, value, location) {
79994 return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
79995 }
79996 /**
79997 * Creates an assignment expression for a non-exported variable declaration.
79998 *
79999 * @param name The name of the variable.
80000 * @param value The value of the variable's initializer.
80001 * @param location The source map location for the assignment.
80002 */
80003 function createNonExportedVariableAssignment(name, value, location) {
80004 return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
80005 }
80006 /**
80007 * Creates an assignment expression for a variable declaration.
80008 *
80009 * @param name The name of the variable.
80010 * @param value The value of the variable's initializer.
80011 * @param location The source map location for the assignment.
80012 * @param isExportedDeclaration A value indicating whether the variable is exported.
80013 */
80014 function createVariableAssignment(name, value, location, isExportedDeclaration) {
80015 hoistVariableDeclaration(ts.getSynthesizedClone(name));
80016 return isExportedDeclaration
80017 ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)))
80018 : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location));
80019 }
80020 /**
80021 * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
80022 * and transformed declaration.
80023 *
80024 * @param node The node to visit.
80025 */
80026 function visitMergeDeclarationMarker(node) {
80027 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
80028 // declaration we do not emit a leading variable declaration. To preserve the
80029 // begin/end semantics of the declararation and to properly handle exports
80030 // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
80031 //
80032 // To balance the declaration, we defer the exports of the elided variable
80033 // statement until we visit this declaration's `EndOfDeclarationMarker`.
80034 if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 219 /* VariableStatement */) {
80035 var id = ts.getOriginalNodeId(node);
80036 var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */);
80037 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
80038 }
80039 return node;
80040 }
80041 /**
80042 * Determines whether a node has an associated EndOfDeclarationMarker.
80043 *
80044 * @param node The node to test.
80045 */
80046 function hasAssociatedEndOfDeclarationMarker(node) {
80047 return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
80048 }
80049 /**
80050 * Visits a DeclarationMarker used as a placeholder for the end of a transformed
80051 * declaration.
80052 *
80053 * @param node The node to visit.
80054 */
80055 function visitEndOfDeclarationMarker(node) {
80056 // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
80057 // end of the transformed declaration. We use this marker to emit any deferred exports
80058 // of the declaration.
80059 var id = ts.getOriginalNodeId(node);
80060 var statements = deferredExports[id];
80061 if (statements) {
80062 delete deferredExports[id];
80063 return ts.append(statements, node);
80064 }
80065 else {
80066 var original = ts.getOriginalNode(node);
80067 if (ts.isModuleOrEnumDeclaration(original)) {
80068 return ts.append(appendExportsOfDeclaration(statements, original), node);
80069 }
80070 }
80071 return node;
80072 }
80073 /**
80074 * Appends the exports of an ImportDeclaration to a statement list, returning the
80075 * statement list.
80076 *
80077 * @param statements A statement list to which the down-level export statements are to be
80078 * appended. If `statements` is `undefined`, a new array is allocated if statements are
80079 * appended.
80080 * @param decl The declaration whose exports are to be recorded.
80081 */
80082 function appendExportsOfImportDeclaration(statements, decl) {
80083 if (moduleInfo.exportEquals) {
80084 return statements;
80085 }
80086 var importClause = decl.importClause;
80087 if (!importClause) {
80088 return statements;
80089 }
80090 if (importClause.name) {
80091 statements = appendExportsOfDeclaration(statements, importClause);
80092 }
80093 var namedBindings = importClause.namedBindings;
80094 if (namedBindings) {
80095 switch (namedBindings.kind) {
80096 case 251 /* NamespaceImport */:
80097 statements = appendExportsOfDeclaration(statements, namedBindings);
80098 break;
80099 case 252 /* NamedImports */:
80100 for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
80101 var importBinding = _a[_i];
80102 statements = appendExportsOfDeclaration(statements, importBinding);
80103 }
80104 break;
80105 }
80106 }
80107 return statements;
80108 }
80109 /**
80110 * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
80111 * statement list.
80112 *
80113 * @param statements A statement list to which the down-level export statements are to be
80114 * appended. If `statements` is `undefined`, a new array is allocated if statements are
80115 * appended.
80116 * @param decl The declaration whose exports are to be recorded.
80117 */
80118 function appendExportsOfImportEqualsDeclaration(statements, decl) {
80119 if (moduleInfo.exportEquals) {
80120 return statements;
80121 }
80122 return appendExportsOfDeclaration(statements, decl);
80123 }
80124 /**
80125 * Appends the exports of a VariableStatement to a statement list, returning the statement
80126 * list.
80127 *
80128 * @param statements A statement list to which the down-level export statements are to be
80129 * appended. If `statements` is `undefined`, a new array is allocated if statements are
80130 * appended.
80131 * @param node The VariableStatement whose exports are to be recorded.
80132 * @param exportSelf A value indicating whether to also export each VariableDeclaration of
80133 * `nodes` declaration list.
80134 */
80135 function appendExportsOfVariableStatement(statements, node, exportSelf) {
80136 if (moduleInfo.exportEquals) {
80137 return statements;
80138 }
80139 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
80140 var decl = _a[_i];
80141 if (decl.initializer || exportSelf) {
80142 statements = appendExportsOfBindingElement(statements, decl, exportSelf);
80143 }
80144 }
80145 return statements;
80146 }
80147 /**
80148 * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
80149 * returning the statement list.
80150 *
80151 * @param statements A statement list to which the down-level export statements are to be
80152 * appended. If `statements` is `undefined`, a new array is allocated if statements are
80153 * appended.
80154 * @param decl The declaration whose exports are to be recorded.
80155 * @param exportSelf A value indicating whether to also export the declaration itself.
80156 */
80157 function appendExportsOfBindingElement(statements, decl, exportSelf) {
80158 if (moduleInfo.exportEquals) {
80159 return statements;
80160 }
80161 if (ts.isBindingPattern(decl.name)) {
80162 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
80163 var element = _a[_i];
80164 if (!ts.isOmittedExpression(element)) {
80165 statements = appendExportsOfBindingElement(statements, element, exportSelf);
80166 }
80167 }
80168 }
80169 else if (!ts.isGeneratedIdentifier(decl.name)) {
80170 var excludeName = void 0;
80171 if (exportSelf) {
80172 statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl));
80173 excludeName = ts.idText(decl.name);
80174 }
80175 statements = appendExportsOfDeclaration(statements, decl, excludeName);
80176 }
80177 return statements;
80178 }
80179 /**
80180 * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
80181 * returning the statement list.
80182 *
80183 * @param statements A statement list to which the down-level export statements are to be
80184 * appended. If `statements` is `undefined`, a new array is allocated if statements are
80185 * appended.
80186 * @param decl The declaration whose exports are to be recorded.
80187 */
80188 function appendExportsOfHoistedDeclaration(statements, decl) {
80189 if (moduleInfo.exportEquals) {
80190 return statements;
80191 }
80192 var excludeName;
80193 if (ts.hasModifier(decl, 1 /* Export */)) {
80194 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name;
80195 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl));
80196 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
80197 }
80198 if (decl.name) {
80199 statements = appendExportsOfDeclaration(statements, decl, excludeName);
80200 }
80201 return statements;
80202 }
80203 /**
80204 * Appends the exports of a declaration to a statement list, returning the statement list.
80205 *
80206 * @param statements A statement list to which the down-level export statements are to be
80207 * appended. If `statements` is `undefined`, a new array is allocated if statements are
80208 * appended.
80209 * @param decl The declaration to export.
80210 * @param excludeName An optional name to exclude from exports.
80211 */
80212 function appendExportsOfDeclaration(statements, decl, excludeName) {
80213 if (moduleInfo.exportEquals) {
80214 return statements;
80215 }
80216 var name = ts.getDeclarationName(decl);
80217 var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
80218 if (exportSpecifiers) {
80219 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
80220 var exportSpecifier = exportSpecifiers_2[_i];
80221 if (exportSpecifier.name.escapedText !== excludeName) {
80222 statements = appendExportStatement(statements, exportSpecifier.name, name);
80223 }
80224 }
80225 }
80226 return statements;
80227 }
80228 /**
80229 * Appends the down-level representation of an export to a statement list, returning the
80230 * statement list.
80231 *
80232 * @param statements A statement list to which the down-level export statements are to be
80233 * appended. If `statements` is `undefined`, a new array is allocated if statements are
80234 * appended.
80235 * @param exportName The name of the export.
80236 * @param expression The expression to export.
80237 * @param allowComments Whether to allow comments on the export.
80238 */
80239 function appendExportStatement(statements, exportName, expression, allowComments) {
80240 statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
80241 return statements;
80242 }
80243 /**
80244 * Creates a call to the current file's export function to export a value.
80245 *
80246 * @param name The bound name of the export.
80247 * @param value The exported value.
80248 * @param allowComments An optional value indicating whether to emit comments for the statement.
80249 */
80250 function createExportStatement(name, value, allowComments) {
80251 var statement = ts.createExpressionStatement(createExportExpression(name, value));
80252 ts.startOnNewLine(statement);
80253 if (!allowComments) {
80254 ts.setEmitFlags(statement, 1536 /* NoComments */);
80255 }
80256 return statement;
80257 }
80258 /**
80259 * Creates a call to the current file's export function to export a value.
80260 *
80261 * @param name The bound name of the export.
80262 * @param value The exported value.
80263 */
80264 function createExportExpression(name, value) {
80265 var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name;
80266 ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
80267 return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
80268 }
80269 //
80270 // Top-Level or Nested Source Element Visitors
80271 //
80272 /**
80273 * Visit nested elements at the top-level of a module.
80274 *
80275 * @param node The node to visit.
80276 */
80277 function nestedElementVisitor(node) {
80278 switch (node.kind) {
80279 case 219 /* VariableStatement */:
80280 return visitVariableStatement(node);
80281 case 239 /* FunctionDeclaration */:
80282 return visitFunctionDeclaration(node);
80283 case 240 /* ClassDeclaration */:
80284 return visitClassDeclaration(node);
80285 case 225 /* ForStatement */:
80286 return visitForStatement(node);
80287 case 226 /* ForInStatement */:
80288 return visitForInStatement(node);
80289 case 227 /* ForOfStatement */:
80290 return visitForOfStatement(node);
80291 case 223 /* DoStatement */:
80292 return visitDoStatement(node);
80293 case 224 /* WhileStatement */:
80294 return visitWhileStatement(node);
80295 case 233 /* LabeledStatement */:
80296 return visitLabeledStatement(node);
80297 case 231 /* WithStatement */:
80298 return visitWithStatement(node);
80299 case 232 /* SwitchStatement */:
80300 return visitSwitchStatement(node);
80301 case 246 /* CaseBlock */:
80302 return visitCaseBlock(node);
80303 case 271 /* CaseClause */:
80304 return visitCaseClause(node);
80305 case 272 /* DefaultClause */:
80306 return visitDefaultClause(node);
80307 case 235 /* TryStatement */:
80308 return visitTryStatement(node);
80309 case 274 /* CatchClause */:
80310 return visitCatchClause(node);
80311 case 218 /* Block */:
80312 return visitBlock(node);
80313 case 315 /* MergeDeclarationMarker */:
80314 return visitMergeDeclarationMarker(node);
80315 case 316 /* EndOfDeclarationMarker */:
80316 return visitEndOfDeclarationMarker(node);
80317 default:
80318 return destructuringAndImportCallVisitor(node);
80319 }
80320 }
80321 /**
80322 * Visits the body of a ForStatement to hoist declarations.
80323 *
80324 * @param node The node to visit.
80325 */
80326 function visitForStatement(node) {
80327 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
80328 enclosingBlockScopedContainer = node;
80329 node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement));
80330 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
80331 return node;
80332 }
80333 /**
80334 * Visits the body of a ForInStatement to hoist declarations.
80335 *
80336 * @param node The node to visit.
80337 */
80338 function visitForInStatement(node) {
80339 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
80340 enclosingBlockScopedContainer = node;
80341 node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
80342 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
80343 return node;
80344 }
80345 /**
80346 * Visits the body of a ForOfStatement to hoist declarations.
80347 *
80348 * @param node The node to visit.
80349 */
80350 function visitForOfStatement(node) {
80351 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
80352 enclosingBlockScopedContainer = node;
80353 node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
80354 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
80355 return node;
80356 }
80357 /**
80358 * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
80359 * ForOfStatement.
80360 *
80361 * @param node The node to test.
80362 */
80363 function shouldHoistForInitializer(node) {
80364 return ts.isVariableDeclarationList(node)
80365 && shouldHoistVariableDeclarationList(node);
80366 }
80367 /**
80368 * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
80369 *
80370 * @param node The node to visit.
80371 */
80372 function visitForInitializer(node) {
80373 if (shouldHoistForInitializer(node)) {
80374 var expressions = void 0;
80375 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
80376 var variable = _a[_i];
80377 expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
80378 if (!variable.initializer) {
80379 hoistBindingElement(variable);
80380 }
80381 }
80382 return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression();
80383 }
80384 else {
80385 return ts.visitEachChild(node, nestedElementVisitor, context);
80386 }
80387 }
80388 /**
80389 * Visits the body of a DoStatement to hoist declarations.
80390 *
80391 * @param node The node to visit.
80392 */
80393 function visitDoStatement(node) {
80394 return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
80395 }
80396 /**
80397 * Visits the body of a WhileStatement to hoist declarations.
80398 *
80399 * @param node The node to visit.
80400 */
80401 function visitWhileStatement(node) {
80402 return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
80403 }
80404 /**
80405 * Visits the body of a LabeledStatement to hoist declarations.
80406 *
80407 * @param node The node to visit.
80408 */
80409 function visitLabeledStatement(node) {
80410 return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
80411 }
80412 /**
80413 * Visits the body of a WithStatement to hoist declarations.
80414 *
80415 * @param node The node to visit.
80416 */
80417 function visitWithStatement(node) {
80418 return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
80419 }
80420 /**
80421 * Visits the body of a SwitchStatement to hoist declarations.
80422 *
80423 * @param node The node to visit.
80424 */
80425 function visitSwitchStatement(node) {
80426 return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
80427 }
80428 /**
80429 * Visits the body of a CaseBlock to hoist declarations.
80430 *
80431 * @param node The node to visit.
80432 */
80433 function visitCaseBlock(node) {
80434 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
80435 enclosingBlockScopedContainer = node;
80436 node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
80437 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
80438 return node;
80439 }
80440 /**
80441 * Visits the body of a CaseClause to hoist declarations.
80442 *
80443 * @param node The node to visit.
80444 */
80445 function visitCaseClause(node) {
80446 return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
80447 }
80448 /**
80449 * Visits the body of a DefaultClause to hoist declarations.
80450 *
80451 * @param node The node to visit.
80452 */
80453 function visitDefaultClause(node) {
80454 return ts.visitEachChild(node, nestedElementVisitor, context);
80455 }
80456 /**
80457 * Visits the body of a TryStatement to hoist declarations.
80458 *
80459 * @param node The node to visit.
80460 */
80461 function visitTryStatement(node) {
80462 return ts.visitEachChild(node, nestedElementVisitor, context);
80463 }
80464 /**
80465 * Visits the body of a CatchClause to hoist declarations.
80466 *
80467 * @param node The node to visit.
80468 */
80469 function visitCatchClause(node) {
80470 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
80471 enclosingBlockScopedContainer = node;
80472 node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
80473 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
80474 return node;
80475 }
80476 /**
80477 * Visits the body of a Block to hoist declarations.
80478 *
80479 * @param node The node to visit.
80480 */
80481 function visitBlock(node) {
80482 var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
80483 enclosingBlockScopedContainer = node;
80484 node = ts.visitEachChild(node, nestedElementVisitor, context);
80485 enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
80486 return node;
80487 }
80488 //
80489 // Destructuring Assignment Visitors
80490 //
80491 /**
80492 * Visit nodes to flatten destructuring assignments to exported symbols.
80493 *
80494 * @param node The node to visit.
80495 */
80496 function destructuringAndImportCallVisitor(node) {
80497 if (ts.isDestructuringAssignment(node)) {
80498 return visitDestructuringAssignment(node);
80499 }
80500 else if (ts.isImportCall(node)) {
80501 return visitImportCallExpression(node);
80502 }
80503 else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) {
80504 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
80505 }
80506 else {
80507 return node;
80508 }
80509 }
80510 function visitImportCallExpression(node) {
80511 // import("./blah")
80512 // emit as
80513 // System.register([], function (_export, _context) {
80514 // return {
80515 // setters: [],
80516 // execute: () => {
80517 // _context.import('./blah');
80518 // }
80519 // };
80520 // });
80521 return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")),
80522 /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
80523 }
80524 /**
80525 * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
80526 *
80527 * @param node The node to visit.
80528 */
80529 function visitDestructuringAssignment(node) {
80530 if (hasExportedReferenceInDestructuringTarget(node.left)) {
80531 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */,
80532 /*needsValue*/ true);
80533 }
80534 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
80535 }
80536 /**
80537 * Determines whether the target of a destructuring assigment refers to an exported symbol.
80538 *
80539 * @param node The destructuring target.
80540 */
80541 function hasExportedReferenceInDestructuringTarget(node) {
80542 if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
80543 return hasExportedReferenceInDestructuringTarget(node.left);
80544 }
80545 else if (ts.isSpreadElement(node)) {
80546 return hasExportedReferenceInDestructuringTarget(node.expression);
80547 }
80548 else if (ts.isObjectLiteralExpression(node)) {
80549 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
80550 }
80551 else if (ts.isArrayLiteralExpression(node)) {
80552 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
80553 }
80554 else if (ts.isShorthandPropertyAssignment(node)) {
80555 return hasExportedReferenceInDestructuringTarget(node.name);
80556 }
80557 else if (ts.isPropertyAssignment(node)) {
80558 return hasExportedReferenceInDestructuringTarget(node.initializer);
80559 }
80560 else if (ts.isIdentifier(node)) {
80561 var container = resolver.getReferencedExportContainer(node);
80562 return container !== undefined && container.kind === 284 /* SourceFile */;
80563 }
80564 else {
80565 return false;
80566 }
80567 }
80568 //
80569 // Modifier Visitors
80570 //
80571 /**
80572 * Visit nodes to elide module-specific modifiers.
80573 *
80574 * @param node The node to visit.
80575 */
80576 function modifierVisitor(node) {
80577 switch (node.kind) {
80578 case 85 /* ExportKeyword */:
80579 case 80 /* DefaultKeyword */:
80580 return undefined;
80581 }
80582 return node;
80583 }
80584 //
80585 // Emit Notification
80586 //
80587 /**
80588 * Hook for node emit notifications.
80589 *
80590 * @param hint A hint as to the intended usage of the node.
80591 * @param node The node to emit.
80592 * @param emitCallback A callback used to emit the node in the printer.
80593 */
80594 function onEmitNode(hint, node, emitCallback) {
80595 if (node.kind === 284 /* SourceFile */) {
80596 var id = ts.getOriginalNodeId(node);
80597 currentSourceFile = node;
80598 moduleInfo = moduleInfoMap[id];
80599 exportFunction = exportFunctionsMap[id];
80600 noSubstitution = noSubstitutionMap[id];
80601 if (noSubstitution) {
80602 delete noSubstitutionMap[id];
80603 }
80604 previousOnEmitNode(hint, node, emitCallback);
80605 currentSourceFile = undefined;
80606 moduleInfo = undefined;
80607 exportFunction = undefined;
80608 noSubstitution = undefined;
80609 }
80610 else {
80611 previousOnEmitNode(hint, node, emitCallback);
80612 }
80613 }
80614 //
80615 // Substitutions
80616 //
80617 /**
80618 * Hooks node substitutions.
80619 *
80620 * @param hint A hint as to the intended usage of the node.
80621 * @param node The node to substitute.
80622 */
80623 function onSubstituteNode(hint, node) {
80624 node = previousOnSubstituteNode(hint, node);
80625 if (isSubstitutionPrevented(node)) {
80626 return node;
80627 }
80628 if (hint === 1 /* Expression */) {
80629 return substituteExpression(node);
80630 }
80631 else if (hint === 4 /* Unspecified */) {
80632 return substituteUnspecified(node);
80633 }
80634 return node;
80635 }
80636 /**
80637 * Substitute the node, if necessary.
80638 *
80639 * @param node The node to substitute.
80640 */
80641 function substituteUnspecified(node) {
80642 switch (node.kind) {
80643 case 276 /* ShorthandPropertyAssignment */:
80644 return substituteShorthandPropertyAssignment(node);
80645 }
80646 return node;
80647 }
80648 /**
80649 * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
80650 *
80651 * @param node The node to substitute.
80652 */
80653 function substituteShorthandPropertyAssignment(node) {
80654 var name = node.name;
80655 if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
80656 var importDeclaration = resolver.getReferencedImportDeclaration(name);
80657 if (importDeclaration) {
80658 if (ts.isImportClause(importDeclaration)) {
80659 return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))),
80660 /*location*/ node);
80661 }
80662 else if (ts.isImportSpecifier(importDeclaration)) {
80663 return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))),
80664 /*location*/ node);
80665 }
80666 }
80667 }
80668 return node;
80669 }
80670 /**
80671 * Substitute the expression, if necessary.
80672 *
80673 * @param node The node to substitute.
80674 */
80675 function substituteExpression(node) {
80676 switch (node.kind) {
80677 case 72 /* Identifier */:
80678 return substituteExpressionIdentifier(node);
80679 case 204 /* BinaryExpression */:
80680 return substituteBinaryExpression(node);
80681 case 202 /* PrefixUnaryExpression */:
80682 case 203 /* PostfixUnaryExpression */:
80683 return substituteUnaryExpression(node);
80684 }
80685 return node;
80686 }
80687 /**
80688 * Substitution for an Identifier expression that may contain an imported or exported symbol.
80689 *
80690 * @param node The node to substitute.
80691 */
80692 function substituteExpressionIdentifier(node) {
80693 if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
80694 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
80695 if (externalHelpersModuleName) {
80696 return ts.createPropertyAccess(externalHelpersModuleName, node);
80697 }
80698 return node;
80699 }
80700 // When we see an identifier in an expression position that
80701 // points to an imported symbol, we should substitute a qualified
80702 // reference to the imported symbol if one is needed.
80703 //
80704 // - We do not substitute generated identifiers for any reason.
80705 // - We do not substitute identifiers tagged with the LocalName flag.
80706 if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
80707 var importDeclaration = resolver.getReferencedImportDeclaration(node);
80708 if (importDeclaration) {
80709 if (ts.isImportClause(importDeclaration)) {
80710 return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")),
80711 /*location*/ node);
80712 }
80713 else if (ts.isImportSpecifier(importDeclaration)) {
80714 return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)),
80715 /*location*/ node);
80716 }
80717 }
80718 }
80719 return node;
80720 }
80721 /**
80722 * Substitution for a BinaryExpression that may contain an imported or exported symbol.
80723 *
80724 * @param node The node to substitute.
80725 */
80726 function substituteBinaryExpression(node) {
80727 // When we see an assignment expression whose left-hand side is an exported symbol,
80728 // we should ensure all exports of that symbol are updated with the correct value.
80729 //
80730 // - We do not substitute generated identifiers for any reason.
80731 // - We do not substitute identifiers tagged with the LocalName flag.
80732 // - We do not substitute identifiers that were originally the name of an enum or
80733 // namespace due to how they are transformed in TypeScript.
80734 // - We only substitute identifiers that are exported at the top level.
80735 if (ts.isAssignmentOperator(node.operatorToken.kind)
80736 && ts.isIdentifier(node.left)
80737 && !ts.isGeneratedIdentifier(node.left)
80738 && !ts.isLocalName(node.left)
80739 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
80740 var exportedNames = getExports(node.left);
80741 if (exportedNames) {
80742 // For each additional export of the declaration, apply an export assignment.
80743 var expression = node;
80744 for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
80745 var exportName = exportedNames_4[_i];
80746 expression = createExportExpression(exportName, preventSubstitution(expression));
80747 }
80748 return expression;
80749 }
80750 }
80751 return node;
80752 }
80753 /**
80754 * Substitution for a UnaryExpression that may contain an imported or exported symbol.
80755 *
80756 * @param node The node to substitute.
80757 */
80758 function substituteUnaryExpression(node) {
80759 // When we see a prefix or postfix increment expression whose operand is an exported
80760 // symbol, we should ensure all exports of that symbol are updated with the correct
80761 // value.
80762 //
80763 // - We do not substitute generated identifiers for any reason.
80764 // - We do not substitute identifiers tagged with the LocalName flag.
80765 // - We do not substitute identifiers that were originally the name of an enum or
80766 // namespace due to how they are transformed in TypeScript.
80767 // - We only substitute identifiers that are exported at the top level.
80768 if ((node.operator === 44 /* PlusPlusToken */ || node.operator === 45 /* MinusMinusToken */)
80769 && ts.isIdentifier(node.operand)
80770 && !ts.isGeneratedIdentifier(node.operand)
80771 && !ts.isLocalName(node.operand)
80772 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
80773 var exportedNames = getExports(node.operand);
80774 if (exportedNames) {
80775 var expression = node.kind === 203 /* PostfixUnaryExpression */
80776 ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
80777 : node;
80778 for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
80779 var exportName = exportedNames_5[_i];
80780 expression = createExportExpression(exportName, preventSubstitution(expression));
80781 }
80782 if (node.kind === 203 /* PostfixUnaryExpression */) {
80783 expression = node.operator === 44 /* PlusPlusToken */
80784 ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1))
80785 : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1));
80786 }
80787 return expression;
80788 }
80789 }
80790 return node;
80791 }
80792 /**
80793 * Gets the exports of a name.
80794 *
80795 * @param name The name.
80796 */
80797 function getExports(name) {
80798 var exportedNames;
80799 if (!ts.isGeneratedIdentifier(name)) {
80800 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
80801 || resolver.getReferencedValueDeclaration(name);
80802 if (valueDeclaration) {
80803 var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
80804 if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
80805 exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
80806 }
80807 exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
80808 }
80809 }
80810 return exportedNames;
80811 }
80812 /**
80813 * Prevent substitution of a node for this transformer.
80814 *
80815 * @param node The node which should not be substituted.
80816 */
80817 function preventSubstitution(node) {
80818 if (noSubstitution === undefined)
80819 noSubstitution = [];
80820 noSubstitution[ts.getNodeId(node)] = true;
80821 return node;
80822 }
80823 /**
80824 * Determines whether a node should not be substituted.
80825 *
80826 * @param node The node to test.
80827 */
80828 function isSubstitutionPrevented(node) {
80829 return noSubstitution && node.id && noSubstitution[node.id];
80830 }
80831 }
80832 ts.transformSystemModule = transformSystemModule;
80833})(ts || (ts = {}));
80834/*@internal*/
80835var ts;
80836(function (ts) {
80837 function transformES2015Module(context) {
80838 var compilerOptions = context.getCompilerOptions();
80839 var previousOnEmitNode = context.onEmitNode;
80840 var previousOnSubstituteNode = context.onSubstituteNode;
80841 context.onEmitNode = onEmitNode;
80842 context.onSubstituteNode = onSubstituteNode;
80843 context.enableEmitNotification(284 /* SourceFile */);
80844 context.enableSubstitution(72 /* Identifier */);
80845 var currentSourceFile;
80846 return ts.chainBundle(transformSourceFile);
80847 function transformSourceFile(node) {
80848 if (node.isDeclarationFile) {
80849 return node;
80850 }
80851 if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
80852 var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions);
80853 if (externalHelpersModuleName) {
80854 var statements = [];
80855 var statementOffset = ts.addPrologue(statements, node.statements);
80856 var tslibImport = ts.createImportDeclaration(
80857 /*decorators*/ undefined,
80858 /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText));
80859 ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */);
80860 ts.append(statements, tslibImport);
80861 ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
80862 return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
80863 }
80864 else {
80865 return ts.visitEachChild(node, visitor, context);
80866 }
80867 }
80868 return node;
80869 }
80870 function visitor(node) {
80871 switch (node.kind) {
80872 case 248 /* ImportEqualsDeclaration */:
80873 // Elide `import=` as it is not legal with --module ES6
80874 return undefined;
80875 case 254 /* ExportAssignment */:
80876 return visitExportAssignment(node);
80877 }
80878 return node;
80879 }
80880 function visitExportAssignment(node) {
80881 // Elide `export=` as it is not legal with --module ES6
80882 return node.isExportEquals ? undefined : node;
80883 }
80884 //
80885 // Emit Notification
80886 //
80887 /**
80888 * Hook for node emit.
80889 *
80890 * @param hint A hint as to the intended usage of the node.
80891 * @param node The node to emit.
80892 * @param emit A callback used to emit the node in the printer.
80893 */
80894 function onEmitNode(hint, node, emitCallback) {
80895 if (ts.isSourceFile(node)) {
80896 currentSourceFile = node;
80897 previousOnEmitNode(hint, node, emitCallback);
80898 currentSourceFile = undefined;
80899 }
80900 else {
80901 previousOnEmitNode(hint, node, emitCallback);
80902 }
80903 }
80904 //
80905 // Substitutions
80906 //
80907 /**
80908 * Hooks node substitutions.
80909 *
80910 * @param hint A hint as to the intended usage of the node.
80911 * @param node The node to substitute.
80912 */
80913 function onSubstituteNode(hint, node) {
80914 node = previousOnSubstituteNode(hint, node);
80915 if (ts.isIdentifier(node) && hint === 1 /* Expression */) {
80916 return substituteExpressionIdentifier(node);
80917 }
80918 return node;
80919 }
80920 function substituteExpressionIdentifier(node) {
80921 if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
80922 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
80923 if (externalHelpersModuleName) {
80924 return ts.createPropertyAccess(externalHelpersModuleName, node);
80925 }
80926 }
80927 return node;
80928 }
80929 }
80930 ts.transformES2015Module = transformES2015Module;
80931})(ts || (ts = {}));
80932/* @internal */
80933var ts;
80934(function (ts) {
80935 function canProduceDiagnostics(node) {
80936 return ts.isVariableDeclaration(node) ||
80937 ts.isPropertyDeclaration(node) ||
80938 ts.isPropertySignature(node) ||
80939 ts.isBindingElement(node) ||
80940 ts.isSetAccessor(node) ||
80941 ts.isGetAccessor(node) ||
80942 ts.isConstructSignatureDeclaration(node) ||
80943 ts.isCallSignatureDeclaration(node) ||
80944 ts.isMethodDeclaration(node) ||
80945 ts.isMethodSignature(node) ||
80946 ts.isFunctionDeclaration(node) ||
80947 ts.isParameter(node) ||
80948 ts.isTypeParameterDeclaration(node) ||
80949 ts.isExpressionWithTypeArguments(node) ||
80950 ts.isImportEqualsDeclaration(node) ||
80951 ts.isTypeAliasDeclaration(node) ||
80952 ts.isConstructorDeclaration(node) ||
80953 ts.isIndexSignatureDeclaration(node) ||
80954 ts.isPropertyAccessExpression(node);
80955 }
80956 ts.canProduceDiagnostics = canProduceDiagnostics;
80957 function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
80958 if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
80959 return getAccessorNameVisibilityError;
80960 }
80961 else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
80962 return getMethodNameVisibilityError;
80963 }
80964 else {
80965 return createGetSymbolAccessibilityDiagnosticForNode(node);
80966 }
80967 function getAccessorNameVisibilityError(symbolAccessibilityResult) {
80968 var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
80969 return diagnosticMessage !== undefined ? {
80970 diagnosticMessage: diagnosticMessage,
80971 errorNode: node,
80972 typeName: node.name
80973 } : undefined;
80974 }
80975 function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
80976 if (ts.hasModifier(node, 32 /* Static */)) {
80977 return symbolAccessibilityResult.errorModuleName ?
80978 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
80979 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
80980 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
80981 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
80982 }
80983 else if (node.parent.kind === 240 /* ClassDeclaration */) {
80984 return symbolAccessibilityResult.errorModuleName ?
80985 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
80986 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
80987 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
80988 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
80989 }
80990 else {
80991 return symbolAccessibilityResult.errorModuleName ?
80992 ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
80993 ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
80994 }
80995 }
80996 function getMethodNameVisibilityError(symbolAccessibilityResult) {
80997 var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
80998 return diagnosticMessage !== undefined ? {
80999 diagnosticMessage: diagnosticMessage,
81000 errorNode: node,
81001 typeName: node.name
81002 } : undefined;
81003 }
81004 function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
81005 if (ts.hasModifier(node, 32 /* Static */)) {
81006 return symbolAccessibilityResult.errorModuleName ?
81007 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81008 ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81009 ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
81010 ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
81011 }
81012 else if (node.parent.kind === 240 /* ClassDeclaration */) {
81013 return symbolAccessibilityResult.errorModuleName ?
81014 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81015 ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81016 ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
81017 ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
81018 }
81019 else {
81020 return symbolAccessibilityResult.errorModuleName ?
81021 ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
81022 ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
81023 }
81024 }
81025 }
81026 ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
81027 function createGetSymbolAccessibilityDiagnosticForNode(node) {
81028 if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
81029 return getVariableDeclarationTypeVisibilityError;
81030 }
81031 else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
81032 return getAccessorDeclarationTypeVisibilityError;
81033 }
81034 else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
81035 return getReturnTypeVisibilityError;
81036 }
81037 else if (ts.isParameter(node)) {
81038 if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) {
81039 return getVariableDeclarationTypeVisibilityError;
81040 }
81041 return getParameterDeclarationTypeVisibilityError;
81042 }
81043 else if (ts.isTypeParameterDeclaration(node)) {
81044 return getTypeParameterConstraintVisibilityError;
81045 }
81046 else if (ts.isExpressionWithTypeArguments(node)) {
81047 return getHeritageClauseVisibilityError;
81048 }
81049 else if (ts.isImportEqualsDeclaration(node)) {
81050 return getImportEntityNameVisibilityError;
81051 }
81052 else if (ts.isTypeAliasDeclaration(node)) {
81053 return getTypeAliasDeclarationVisibilityError;
81054 }
81055 else {
81056 return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
81057 }
81058 function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
81059 if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) {
81060 return symbolAccessibilityResult.errorModuleName ?
81061 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81062 ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81063 ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
81064 ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
81065 }
81066 // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
81067 // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
81068 else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 189 /* PropertyAccessExpression */ || node.kind === 153 /* PropertySignature */ ||
81069 (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
81070 // TODO(jfreeman): Deal with computed properties in error reporting.
81071 if (ts.hasModifier(node, 32 /* Static */)) {
81072 return symbolAccessibilityResult.errorModuleName ?
81073 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81074 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81075 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
81076 ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
81077 }
81078 else if (node.parent.kind === 240 /* ClassDeclaration */ || node.kind === 151 /* Parameter */) {
81079 return symbolAccessibilityResult.errorModuleName ?
81080 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81081 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81082 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
81083 ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
81084 }
81085 else {
81086 // Interfaces cannot have types that cannot be named
81087 return symbolAccessibilityResult.errorModuleName ?
81088 ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
81089 ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
81090 }
81091 }
81092 }
81093 function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
81094 var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
81095 return diagnosticMessage !== undefined ? {
81096 diagnosticMessage: diagnosticMessage,
81097 errorNode: node,
81098 typeName: node.name
81099 } : undefined;
81100 }
81101 function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
81102 var diagnosticMessage;
81103 if (node.kind === 159 /* SetAccessor */) {
81104 // Getters can infer the return type from the returned expression, but setters cannot, so the
81105 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
81106 if (ts.hasModifier(node, 32 /* Static */)) {
81107 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81108 ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
81109 ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
81110 }
81111 else {
81112 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81113 ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
81114 ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
81115 }
81116 }
81117 else {
81118 if (ts.hasModifier(node, 32 /* Static */)) {
81119 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81120 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81121 ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81122 ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
81123 ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
81124 }
81125 else {
81126 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81127 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81128 ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81129 ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
81130 ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
81131 }
81132 }
81133 return {
81134 diagnosticMessage: diagnosticMessage,
81135 errorNode: node.name,
81136 typeName: node.name
81137 };
81138 }
81139 function getReturnTypeVisibilityError(symbolAccessibilityResult) {
81140 var diagnosticMessage;
81141 switch (node.kind) {
81142 case 161 /* ConstructSignature */:
81143 // Interfaces cannot have return types that cannot be named
81144 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81145 ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
81146 ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
81147 break;
81148 case 160 /* CallSignature */:
81149 // Interfaces cannot have return types that cannot be named
81150 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81151 ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
81152 ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
81153 break;
81154 case 162 /* IndexSignature */:
81155 // Interfaces cannot have return types that cannot be named
81156 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81157 ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
81158 ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
81159 break;
81160 case 156 /* MethodDeclaration */:
81161 case 155 /* MethodSignature */:
81162 if (ts.hasModifier(node, 32 /* Static */)) {
81163 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81164 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81165 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
81166 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
81167 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
81168 }
81169 else if (node.parent.kind === 240 /* ClassDeclaration */) {
81170 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81171 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81172 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
81173 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
81174 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
81175 }
81176 else {
81177 // Interfaces cannot have return types that cannot be named
81178 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81179 ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
81180 ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
81181 }
81182 break;
81183 case 239 /* FunctionDeclaration */:
81184 diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
81185 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81186 ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
81187 ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
81188 ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
81189 break;
81190 default:
81191 return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
81192 }
81193 return {
81194 diagnosticMessage: diagnosticMessage,
81195 errorNode: node.name || node
81196 };
81197 }
81198 function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
81199 var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
81200 return diagnosticMessage !== undefined ? {
81201 diagnosticMessage: diagnosticMessage,
81202 errorNode: node,
81203 typeName: node.name
81204 } : undefined;
81205 }
81206 function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
81207 switch (node.parent.kind) {
81208 case 157 /* Constructor */:
81209 return symbolAccessibilityResult.errorModuleName ?
81210 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81211 ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81212 ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
81213 ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
81214 case 161 /* ConstructSignature */:
81215 case 166 /* ConstructorType */:
81216 // Interfaces cannot have parameter types that cannot be named
81217 return symbolAccessibilityResult.errorModuleName ?
81218 ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
81219 ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
81220 case 160 /* CallSignature */:
81221 // Interfaces cannot have parameter types that cannot be named
81222 return symbolAccessibilityResult.errorModuleName ?
81223 ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
81224 ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
81225 case 162 /* IndexSignature */:
81226 // Interfaces cannot have parameter types that cannot be named
81227 return symbolAccessibilityResult.errorModuleName ?
81228 ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
81229 ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
81230 case 156 /* MethodDeclaration */:
81231 case 155 /* MethodSignature */:
81232 if (ts.hasModifier(node.parent, 32 /* Static */)) {
81233 return symbolAccessibilityResult.errorModuleName ?
81234 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81235 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81236 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
81237 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
81238 }
81239 else if (node.parent.parent.kind === 240 /* ClassDeclaration */) {
81240 return symbolAccessibilityResult.errorModuleName ?
81241 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81242 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81243 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
81244 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
81245 }
81246 else {
81247 // Interfaces cannot have parameter types that cannot be named
81248 return symbolAccessibilityResult.errorModuleName ?
81249 ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
81250 ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
81251 }
81252 case 239 /* FunctionDeclaration */:
81253 case 165 /* FunctionType */:
81254 return symbolAccessibilityResult.errorModuleName ?
81255 symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
81256 ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
81257 ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
81258 ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
81259 default:
81260 return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
81261 }
81262 }
81263 function getTypeParameterConstraintVisibilityError() {
81264 // Type parameter constraints are named by user so we should always be able to name it
81265 var diagnosticMessage;
81266 switch (node.parent.kind) {
81267 case 240 /* ClassDeclaration */:
81268 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
81269 break;
81270 case 241 /* InterfaceDeclaration */:
81271 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
81272 break;
81273 case 181 /* MappedType */:
81274 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
81275 break;
81276 case 166 /* ConstructorType */:
81277 case 161 /* ConstructSignature */:
81278 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
81279 break;
81280 case 160 /* CallSignature */:
81281 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
81282 break;
81283 case 156 /* MethodDeclaration */:
81284 case 155 /* MethodSignature */:
81285 if (ts.hasModifier(node.parent, 32 /* Static */)) {
81286 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
81287 }
81288 else if (node.parent.parent.kind === 240 /* ClassDeclaration */) {
81289 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
81290 }
81291 else {
81292 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
81293 }
81294 break;
81295 case 165 /* FunctionType */:
81296 case 239 /* FunctionDeclaration */:
81297 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
81298 break;
81299 case 242 /* TypeAliasDeclaration */:
81300 diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
81301 break;
81302 default:
81303 return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
81304 }
81305 return {
81306 diagnosticMessage: diagnosticMessage,
81307 errorNode: node,
81308 typeName: node.name
81309 };
81310 }
81311 function getHeritageClauseVisibilityError() {
81312 var diagnosticMessage;
81313 // Heritage clause is written by user so it can always be named
81314 if (node.parent.parent.kind === 240 /* ClassDeclaration */) {
81315 // Class or Interface implemented/extended is inaccessible
81316 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 109 /* ImplementsKeyword */ ?
81317 ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
81318 ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
81319 }
81320 else {
81321 // interface is inaccessible
81322 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
81323 }
81324 return {
81325 diagnosticMessage: diagnosticMessage,
81326 errorNode: node,
81327 typeName: ts.getNameOfDeclaration(node.parent.parent)
81328 };
81329 }
81330 function getImportEntityNameVisibilityError() {
81331 return {
81332 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
81333 errorNode: node,
81334 typeName: node.name
81335 };
81336 }
81337 function getTypeAliasDeclarationVisibilityError() {
81338 return {
81339 diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
81340 errorNode: node.type,
81341 typeName: node.name
81342 };
81343 }
81344 }
81345 ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
81346})(ts || (ts = {}));
81347/*@internal*/
81348var ts;
81349(function (ts) {
81350 function getDeclarationDiagnostics(host, resolver, file) {
81351 if (file && ts.isSourceFileJS(file)) {
81352 return []; // No declaration diagnostics for js for now
81353 }
81354 var compilerOptions = host.getCompilerOptions();
81355 var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false);
81356 return result.diagnostics;
81357 }
81358 ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
81359 function hasInternalAnnotation(range, currentSourceFile) {
81360 var comment = currentSourceFile.text.substring(range.pos, range.end);
81361 return ts.stringContains(comment, "@internal");
81362 }
81363 function isInternalDeclaration(node, currentSourceFile) {
81364 var parseTreeNode = ts.getParseTreeNode(node);
81365 if (parseTreeNode && parseTreeNode.kind === 151 /* Parameter */) {
81366 var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
81367 var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
81368 var text = currentSourceFile.text;
81369 var commentRanges = previousSibling
81370 ? ts.concatenate(
81371 // to handle
81372 // ... parameters, /* @internal */
81373 // public param: string
81374 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
81375 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
81376 return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
81377 }
81378 var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
81379 return !!ts.forEach(leadingCommentRanges, function (range) {
81380 return hasInternalAnnotation(range, currentSourceFile);
81381 });
81382 }
81383 ts.isInternalDeclaration = isInternalDeclaration;
81384 var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
81385 2048 /* WriteClassExpressionAsTypeLiteral */ |
81386 4096 /* UseTypeOfFunction */ |
81387 8 /* UseStructuralFallback */ |
81388 524288 /* AllowEmptyTuple */ |
81389 4 /* GenerateNamesForShadowedTypeParams */ |
81390 1 /* NoTruncation */;
81391 /**
81392 * Transforms a ts file into a .d.ts file
81393 * This process requires type information, which is retrieved through the emit resolver. Because of this,
81394 * in many places this transformer assumes it will be operating on parse tree nodes directly.
81395 * This means that _no transforms should be allowed to occur before this one_.
81396 */
81397 function transformDeclarations(context) {
81398 var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
81399 var getSymbolAccessibilityDiagnostic = throwDiagnostic;
81400 var needsDeclare = true;
81401 var isBundledEmit = false;
81402 var resultHasExternalModuleIndicator = false;
81403 var needsScopeFixMarker = false;
81404 var resultHasScopeMarker = false;
81405 var enclosingDeclaration;
81406 var necessaryTypeReferences;
81407 var lateMarkedStatements;
81408 var lateStatementReplacementMap;
81409 var suppressNewDiagnosticContexts;
81410 var exportedModulesFromDeclarationEmit;
81411 var host = context.getEmitHost();
81412 var symbolTracker = {
81413 trackSymbol: trackSymbol,
81414 reportInaccessibleThisError: reportInaccessibleThisError,
81415 reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
81416 reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
81417 reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
81418 moduleResolverHost: host,
81419 trackReferencedAmbientModule: trackReferencedAmbientModule,
81420 trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode
81421 };
81422 var errorNameNode;
81423 var currentSourceFile;
81424 var refs;
81425 var libs;
81426 var resolver = context.getEmitResolver();
81427 var options = context.getCompilerOptions();
81428 var newLine = ts.getNewLineCharacter(options);
81429 var noResolve = options.noResolve, stripInternal = options.stripInternal;
81430 return transformRoot;
81431 function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
81432 if (!typeReferenceDirectives) {
81433 return;
81434 }
81435 necessaryTypeReferences = necessaryTypeReferences || ts.createMap();
81436 for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
81437 var ref = typeReferenceDirectives_2[_i];
81438 necessaryTypeReferences.set(ref, true);
81439 }
81440 }
81441 function trackReferencedAmbientModule(node, symbol) {
81442 // If it is visible via `// <reference types="..."/>`, then we should just use that
81443 var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
81444 if (ts.length(directives)) {
81445 return recordTypeReferenceDirectivesIfNecessary(directives);
81446 }
81447 // Otherwise we should emit a path-based reference
81448 var container = ts.getSourceFileOfNode(node);
81449 refs.set("" + ts.getOriginalNodeId(container), container);
81450 }
81451 function handleSymbolAccessibilityError(symbolAccessibilityResult) {
81452 if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
81453 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
81454 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
81455 if (!lateMarkedStatements) {
81456 lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
81457 }
81458 else {
81459 for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
81460 var ref = _a[_i];
81461 ts.pushIfUnique(lateMarkedStatements, ref);
81462 }
81463 }
81464 }
81465 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
81466 }
81467 else {
81468 // Report error
81469 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
81470 if (errorInfo) {
81471 if (errorInfo.typeName) {
81472 context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
81473 }
81474 else {
81475 context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
81476 }
81477 }
81478 }
81479 }
81480 function trackExternalModuleSymbolOfImportTypeNode(symbol) {
81481 if (!isBundledEmit) {
81482 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
81483 }
81484 }
81485 function trackSymbol(symbol, enclosingDeclaration, meaning) {
81486 if (symbol.flags & 262144 /* TypeParameter */)
81487 return;
81488 handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
81489 recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
81490 }
81491 function reportPrivateInBaseOfClassExpression(propertyName) {
81492 if (errorNameNode) {
81493 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
81494 }
81495 }
81496 function reportInaccessibleUniqueSymbolError() {
81497 if (errorNameNode) {
81498 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol"));
81499 }
81500 }
81501 function reportInaccessibleThisError() {
81502 if (errorNameNode) {
81503 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
81504 }
81505 }
81506 function reportLikelyUnsafeImportRequiredError(specifier) {
81507 if (errorNameNode) {
81508 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier));
81509 }
81510 }
81511 function transformRoot(node) {
81512 if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
81513 return node;
81514 }
81515 if (node.kind === 285 /* Bundle */) {
81516 isBundledEmit = true;
81517 refs = ts.createMap();
81518 libs = ts.createMap();
81519 var hasNoDefaultLib_1 = false;
81520 var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
81521 if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile))
81522 return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
81523 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
81524 currentSourceFile = sourceFile;
81525 enclosingDeclaration = sourceFile;
81526 lateMarkedStatements = undefined;
81527 suppressNewDiagnosticContexts = false;
81528 lateStatementReplacementMap = ts.createMap();
81529 getSymbolAccessibilityDiagnostic = throwDiagnostic;
81530 needsScopeFixMarker = false;
81531 resultHasScopeMarker = false;
81532 collectReferences(sourceFile, refs);
81533 collectLibs(sourceFile, libs);
81534 if (ts.isExternalModule(sourceFile)) {
81535 resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
81536 needsDeclare = false;
81537 var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
81538 var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(125 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
81539 return newFile;
81540 }
81541 needsDeclare = true;
81542 var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
81543 return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
81544 }), ts.mapDefined(node.prepends, function (prepend) {
81545 if (prepend.kind === 287 /* InputFiles */) {
81546 var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
81547 hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
81548 collectReferences(sourceFile, refs);
81549 recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
81550 collectLibs(sourceFile, libs);
81551 return sourceFile;
81552 }
81553 return prepend;
81554 }));
81555 bundle.syntheticFileReferences = [];
81556 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
81557 bundle.syntheticLibReferences = getLibReferences();
81558 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
81559 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
81560 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
81561 refs.forEach(referenceVisitor_1);
81562 return bundle;
81563 }
81564 // Single source file
81565 needsDeclare = true;
81566 needsScopeFixMarker = false;
81567 resultHasScopeMarker = false;
81568 enclosingDeclaration = node;
81569 currentSourceFile = node;
81570 getSymbolAccessibilityDiagnostic = throwDiagnostic;
81571 isBundledEmit = false;
81572 resultHasExternalModuleIndicator = false;
81573 suppressNewDiagnosticContexts = false;
81574 lateMarkedStatements = undefined;
81575 lateStatementReplacementMap = ts.createMap();
81576 necessaryTypeReferences = undefined;
81577 refs = collectReferences(currentSourceFile, ts.createMap());
81578 libs = collectLibs(currentSourceFile, ts.createMap());
81579 var references = [];
81580 var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
81581 var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
81582 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
81583 var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
81584 refs.forEach(referenceVisitor);
81585 var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
81586 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
81587 combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements);
81588 }
81589 var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
81590 updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
81591 return updated;
81592 function getLibReferences() {
81593 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
81594 }
81595 function getFileReferencesForUsedTypeReferences() {
81596 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
81597 }
81598 function getFileReferenceForTypeName(typeName) {
81599 // Elide type references for which we have imports
81600 if (emittedImports) {
81601 for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
81602 var importStatement = emittedImports_1[_i];
81603 if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
81604 var expr = importStatement.moduleReference.expression;
81605 if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
81606 return undefined;
81607 }
81608 }
81609 else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
81610 return undefined;
81611 }
81612 }
81613 }
81614 return { fileName: typeName, pos: -1, end: -1 };
81615 }
81616 function mapReferencesIntoArray(references, outputFilePath) {
81617 return function (file) {
81618 var declFileName;
81619 if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
81620 declFileName = file.fileName;
81621 }
81622 else {
81623 if (isBundledEmit && ts.contains(node.sourceFiles, file))
81624 return; // Omit references to files which are being merged
81625 var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
81626 declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
81627 }
81628 if (declFileName) {
81629 var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName,
81630 /*isAbsolutePathAnUrl*/ false);
81631 if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
81632 fileName = fileName.substring(2);
81633 }
81634 // omit references to files from node_modules (npm may disambiguate module
81635 // references when installing this package, making the path is unreliable).
81636 if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) {
81637 return;
81638 }
81639 references.push({ pos: -1, end: -1, fileName: fileName });
81640 }
81641 };
81642 }
81643 }
81644 function collectReferences(sourceFile, ret) {
81645 if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
81646 return ret;
81647 ts.forEach(sourceFile.referencedFiles, function (f) {
81648 var elem = ts.tryResolveScriptReference(host, sourceFile, f);
81649 if (elem) {
81650 ret.set("" + ts.getOriginalNodeId(elem), elem);
81651 }
81652 });
81653 return ret;
81654 }
81655 function collectLibs(sourceFile, ret) {
81656 ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
81657 var lib = host.getLibFileFromReference(ref);
81658 if (lib) {
81659 ret.set(ref.fileName.toLocaleLowerCase(), true);
81660 }
81661 });
81662 return ret;
81663 }
81664 function filterBindingPatternInitializers(name) {
81665 if (name.kind === 72 /* Identifier */) {
81666 return name;
81667 }
81668 else {
81669 if (name.kind === 185 /* ArrayBindingPattern */) {
81670 return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
81671 }
81672 else {
81673 return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
81674 }
81675 }
81676 function visitBindingElement(elem) {
81677 if (elem.kind === 210 /* OmittedExpression */) {
81678 return elem;
81679 }
81680 return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
81681 }
81682 }
81683 function ensureParameter(p, modifierMask) {
81684 var oldDiag;
81685 if (!suppressNewDiagnosticContexts) {
81686 oldDiag = getSymbolAccessibilityDiagnostic;
81687 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
81688 }
81689 var newParam = ts.updateParameter(p,
81690 /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(56 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param
81691 ensureNoInitializer(p));
81692 if (!suppressNewDiagnosticContexts) {
81693 getSymbolAccessibilityDiagnostic = oldDiag;
81694 }
81695 return newParam;
81696 }
81697 function shouldPrintWithInitializer(node) {
81698 return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
81699 }
81700 function ensureNoInitializer(node) {
81701 if (shouldPrintWithInitializer(node)) {
81702 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
81703 }
81704 return undefined;
81705 }
81706 function ensureType(node, type, ignorePrivate) {
81707 if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) {
81708 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
81709 return;
81710 }
81711 if (shouldPrintWithInitializer(node)) {
81712 // Literal const declarations will have an initializer ensured rather than a type
81713 return;
81714 }
81715 var shouldUseResolverType = node.kind === 151 /* Parameter */ &&
81716 (resolver.isRequiredInitializedParameter(node) ||
81717 resolver.isOptionalUninitializedParameterProperty(node));
81718 if (type && !shouldUseResolverType) {
81719 return ts.visitNode(type, visitDeclarationSubtree);
81720 }
81721 if (!ts.getParseTreeNode(node)) {
81722 return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
81723 }
81724 if (node.kind === 159 /* SetAccessor */) {
81725 // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now
81726 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
81727 return ts.createKeywordTypeNode(120 /* AnyKeyword */);
81728 }
81729 errorNameNode = node.name;
81730 var oldDiag;
81731 if (!suppressNewDiagnosticContexts) {
81732 oldDiag = getSymbolAccessibilityDiagnostic;
81733 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
81734 }
81735 if (node.kind === 237 /* VariableDeclaration */ || node.kind === 186 /* BindingElement */) {
81736 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
81737 }
81738 if (node.kind === 151 /* Parameter */
81739 || node.kind === 154 /* PropertyDeclaration */
81740 || node.kind === 153 /* PropertySignature */) {
81741 if (!node.initializer)
81742 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
81743 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
81744 }
81745 return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
81746 function cleanup(returnValue) {
81747 errorNameNode = undefined;
81748 if (!suppressNewDiagnosticContexts) {
81749 getSymbolAccessibilityDiagnostic = oldDiag;
81750 }
81751 return returnValue || ts.createKeywordTypeNode(120 /* AnyKeyword */);
81752 }
81753 }
81754 function isDeclarationAndNotVisible(node) {
81755 node = ts.getParseTreeNode(node);
81756 switch (node.kind) {
81757 case 239 /* FunctionDeclaration */:
81758 case 244 /* ModuleDeclaration */:
81759 case 241 /* InterfaceDeclaration */:
81760 case 240 /* ClassDeclaration */:
81761 case 242 /* TypeAliasDeclaration */:
81762 case 243 /* EnumDeclaration */:
81763 return !resolver.isDeclarationVisible(node);
81764 // The following should be doing their own visibility checks based on filtering their members
81765 case 237 /* VariableDeclaration */:
81766 return !getBindingNameVisible(node);
81767 case 248 /* ImportEqualsDeclaration */:
81768 case 249 /* ImportDeclaration */:
81769 case 255 /* ExportDeclaration */:
81770 case 254 /* ExportAssignment */:
81771 return false;
81772 }
81773 return false;
81774 }
81775 function getBindingNameVisible(elem) {
81776 if (ts.isOmittedExpression(elem)) {
81777 return false;
81778 }
81779 if (ts.isBindingPattern(elem.name)) {
81780 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
81781 return ts.some(elem.name.elements, getBindingNameVisible);
81782 }
81783 else {
81784 return resolver.isDeclarationVisible(elem);
81785 }
81786 }
81787 function updateParamsList(node, params, modifierMask) {
81788 if (ts.hasModifier(node, 8 /* Private */)) {
81789 return undefined; // TODO: GH#18217
81790 }
81791 var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
81792 if (!newParams) {
81793 return undefined; // TODO: GH#18217
81794 }
81795 return ts.createNodeArray(newParams, params.hasTrailingComma);
81796 }
81797 function ensureTypeParams(node, params) {
81798 return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
81799 }
81800 function isEnclosingDeclaration(node) {
81801 return ts.isSourceFile(node)
81802 || ts.isTypeAliasDeclaration(node)
81803 || ts.isModuleDeclaration(node)
81804 || ts.isClassDeclaration(node)
81805 || ts.isInterfaceDeclaration(node)
81806 || ts.isFunctionLike(node)
81807 || ts.isIndexSignatureDeclaration(node)
81808 || ts.isMappedTypeNode(node);
81809 }
81810 function checkEntityNameVisibility(entityName, enclosingDeclaration) {
81811 var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
81812 handleSymbolAccessibilityError(visibilityResult);
81813 recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
81814 }
81815 function preserveJsDoc(updated, original) {
81816 if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
81817 updated.jsDoc = original.jsDoc;
81818 }
81819 return ts.setCommentRange(updated, ts.getCommentRange(original));
81820 }
81821 function rewriteModuleSpecifier(parent, input) {
81822 if (!input)
81823 return undefined; // TODO: GH#18217
81824 resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 244 /* ModuleDeclaration */ && parent.kind !== 183 /* ImportType */);
81825 if (ts.isStringLiteralLike(input)) {
81826 if (isBundledEmit) {
81827 var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
81828 if (newName) {
81829 return ts.createLiteral(newName);
81830 }
81831 }
81832 else {
81833 var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
81834 if (symbol) {
81835 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
81836 }
81837 }
81838 }
81839 return input;
81840 }
81841 function transformImportEqualsDeclaration(decl) {
81842 if (!resolver.isDeclarationVisible(decl))
81843 return;
81844 if (decl.moduleReference.kind === 259 /* ExternalModuleReference */) {
81845 // Rewrite external module names if necessary
81846 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
81847 return ts.updateImportEqualsDeclaration(decl,
81848 /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
81849 }
81850 else {
81851 var oldDiag = getSymbolAccessibilityDiagnostic;
81852 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
81853 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
81854 getSymbolAccessibilityDiagnostic = oldDiag;
81855 return decl;
81856 }
81857 }
81858 function transformImportDeclaration(decl) {
81859 if (!decl.importClause) {
81860 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
81861 return ts.updateImportDeclaration(decl,
81862 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
81863 }
81864 // The `importClause` visibility corresponds to the default's visibility.
81865 var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
81866 if (!decl.importClause.namedBindings) {
81867 // No named bindings (either namespace or list), meaning the import is just default or should be elided
81868 return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding,
81869 /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
81870 }
81871 if (decl.importClause.namedBindings.kind === 251 /* NamespaceImport */) {
81872 // Namespace import (optionally with visible default)
81873 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
81874 return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
81875 }
81876 // Named imports (optionally with visible default)
81877 var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
81878 if ((bindingList && bindingList.length) || visibleDefaultBinding) {
81879 return ts.updateImportDeclaration(decl,
81880 /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
81881 }
81882 // Nothing visible
81883 }
81884 function transformAndReplaceLatePaintedStatements(statements) {
81885 // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
81886 // error handling which must now be included in the output and themselves checked for errors.
81887 // For example:
81888 // ```
81889 // module A {
81890 // export module Q {}
81891 // import B = Q;
81892 // import C = B;
81893 // export import D = C;
81894 // }
81895 // ```
81896 // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must
81897 // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of
81898 // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
81899 while (ts.length(lateMarkedStatements)) {
81900 var i = lateMarkedStatements.shift();
81901 if (!ts.isLateVisibilityPaintedStatement(i)) {
81902 return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
81903 }
81904 var priorNeedsDeclare = needsDeclare;
81905 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
81906 var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true);
81907 needsDeclare = priorNeedsDeclare;
81908 lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
81909 }
81910 // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
81911 // (and remove them from the set to examine for outter declarations)
81912 return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
81913 function visitLateVisibilityMarkedStatements(statement) {
81914 if (ts.isLateVisibilityPaintedStatement(statement)) {
81915 var key = "" + ts.getOriginalNodeId(statement);
81916 if (lateStatementReplacementMap.has(key)) {
81917 var result = lateStatementReplacementMap.get(key);
81918 lateStatementReplacementMap.delete(key);
81919 if (result && ts.isSourceFile(statement.parent)) {
81920 if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) {
81921 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
81922 needsScopeFixMarker = true;
81923 }
81924 if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) {
81925 resultHasExternalModuleIndicator = true;
81926 }
81927 }
81928 return result;
81929 }
81930 }
81931 return statement;
81932 }
81933 }
81934 function isExternalModuleIndicator(result) {
81935 // Exported top-level member indicates moduleness
81936 return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
81937 }
81938 function needsScopeMarker(result) {
81939 return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
81940 }
81941 function visitDeclarationSubtree(input) {
81942 if (shouldStripInternal(input))
81943 return;
81944 if (ts.isDeclaration(input)) {
81945 if (isDeclarationAndNotVisible(input))
81946 return;
81947 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
81948 return;
81949 }
81950 }
81951 // Elide implementation signatures from overload sets
81952 if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
81953 return;
81954 // Elide semicolon class statements
81955 if (ts.isSemicolonClassElement(input))
81956 return;
81957 var previousEnclosingDeclaration;
81958 if (isEnclosingDeclaration(input)) {
81959 previousEnclosingDeclaration = enclosingDeclaration;
81960 enclosingDeclaration = input;
81961 }
81962 var oldDiag = getSymbolAccessibilityDiagnostic;
81963 // Emit methods which are private as properties with no type information
81964 if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
81965 if (ts.hasModifier(input, 8 /* Private */)) {
81966 if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
81967 return; // Elide all but the first overload
81968 return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
81969 }
81970 }
81971 var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
81972 if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) {
81973 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
81974 }
81975 if (ts.isTypeQueryNode(input)) {
81976 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
81977 }
81978 var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
81979 var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 168 /* TypeLiteral */ || input.kind === 181 /* MappedType */) && input.parent.kind !== 242 /* TypeAliasDeclaration */);
81980 if (shouldEnterSuppressNewDiagnosticsContextContext) {
81981 // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do.
81982 suppressNewDiagnosticContexts = true;
81983 }
81984 if (isProcessedComponent(input)) {
81985 switch (input.kind) {
81986 case 211 /* ExpressionWithTypeArguments */: {
81987 if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
81988 checkEntityNameVisibility(input.expression, enclosingDeclaration);
81989 }
81990 var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
81991 return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression));
81992 }
81993 case 164 /* TypeReference */: {
81994 checkEntityNameVisibility(input.typeName, enclosingDeclaration);
81995 var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
81996 return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments)));
81997 }
81998 case 161 /* ConstructSignature */:
81999 return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
82000 case 157 /* Constructor */: {
82001 var isPrivate = ts.hasModifier(input, 8 /* Private */);
82002 // A constructor declaration may not have a type annotation
82003 var ctor = ts.createSignatureDeclaration(157 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters),
82004 // TODO: GH#18217
82005 isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */),
82006 /*type*/ undefined);
82007 ctor.modifiers = ts.createNodeArray(ensureModifiers(input));
82008 return cleanup(ctor);
82009 }
82010 case 156 /* MethodDeclaration */: {
82011 var sig = ts.createSignatureDeclaration(155 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type));
82012 sig.name = input.name;
82013 sig.modifiers = ts.createNodeArray(ensureModifiers(input));
82014 sig.questionToken = input.questionToken;
82015 return cleanup(sig);
82016 }
82017 case 158 /* GetAccessor */: {
82018 var newNode = ensureAccessor(input);
82019 return cleanup(newNode);
82020 }
82021 case 159 /* SetAccessor */: {
82022 var newNode = ensureAccessor(input);
82023 return cleanup(newNode);
82024 }
82025 case 154 /* PropertyDeclaration */:
82026 return cleanup(ts.updateProperty(input,
82027 /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input)));
82028 case 153 /* PropertySignature */:
82029 return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input)));
82030 case 155 /* MethodSignature */: {
82031 return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken));
82032 }
82033 case 160 /* CallSignature */: {
82034 return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
82035 }
82036 case 162 /* IndexSignature */: {
82037 return cleanup(ts.updateIndexSignature(input,
82038 /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(120 /* AnyKeyword */)));
82039 }
82040 case 237 /* VariableDeclaration */: {
82041 if (ts.isBindingPattern(input.name)) {
82042 return recreateBindingPattern(input.name);
82043 }
82044 shouldEnterSuppressNewDiagnosticsContextContext = true;
82045 suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
82046 return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input)));
82047 }
82048 case 150 /* TypeParameter */: {
82049 if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
82050 return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
82051 }
82052 return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
82053 }
82054 case 175 /* ConditionalType */: {
82055 // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
82056 // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
82057 var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
82058 var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
82059 var oldEnclosingDecl = enclosingDeclaration;
82060 enclosingDeclaration = input.trueType;
82061 var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
82062 enclosingDeclaration = oldEnclosingDecl;
82063 var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
82064 return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
82065 }
82066 case 165 /* FunctionType */: {
82067 return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
82068 }
82069 case 166 /* ConstructorType */: {
82070 return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
82071 }
82072 case 183 /* ImportType */: {
82073 if (!ts.isLiteralImportTypeNode(input))
82074 return cleanup(input);
82075 return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf));
82076 }
82077 default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
82078 }
82079 }
82080 return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
82081 function cleanup(returnValue) {
82082 if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) {
82083 checkName(input);
82084 }
82085 if (isEnclosingDeclaration(input)) {
82086 enclosingDeclaration = previousEnclosingDeclaration;
82087 }
82088 if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) {
82089 getSymbolAccessibilityDiagnostic = oldDiag;
82090 }
82091 if (shouldEnterSuppressNewDiagnosticsContextContext) {
82092 suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
82093 }
82094 if (returnValue === input) {
82095 return returnValue;
82096 }
82097 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
82098 }
82099 }
82100 function isPrivateMethodTypeParameter(node) {
82101 return node.parent.kind === 156 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
82102 }
82103 function visitDeclarationStatements(input) {
82104 if (!isPreservedDeclarationStatement(input)) {
82105 // return undefined for unmatched kinds to omit them from the tree
82106 return;
82107 }
82108 if (shouldStripInternal(input))
82109 return;
82110 switch (input.kind) {
82111 case 255 /* ExportDeclaration */: {
82112 if (ts.isSourceFile(input.parent)) {
82113 resultHasExternalModuleIndicator = true;
82114 resultHasScopeMarker = true;
82115 }
82116 // Always visible if the parent node isn't dropped for being not visible
82117 // Rewrite external module names if necessary
82118 return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier));
82119 }
82120 case 254 /* ExportAssignment */: {
82121 // Always visible if the parent node isn't dropped for being not visible
82122 if (ts.isSourceFile(input.parent)) {
82123 resultHasExternalModuleIndicator = true;
82124 resultHasScopeMarker = true;
82125 }
82126 if (input.expression.kind === 72 /* Identifier */) {
82127 return input;
82128 }
82129 else {
82130 var newId = ts.createOptimisticUniqueName("_default");
82131 getSymbolAccessibilityDiagnostic = function () { return ({
82132 diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
82133 errorNode: input
82134 }); };
82135 var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
82136 var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
82137 return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
82138 }
82139 }
82140 }
82141 var result = transformTopLevelDeclaration(input);
82142 // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
82143 lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
82144 return input;
82145 }
82146 function transformTopLevelDeclaration(input, isPrivate) {
82147 if (shouldStripInternal(input))
82148 return;
82149 switch (input.kind) {
82150 case 248 /* ImportEqualsDeclaration */: {
82151 return transformImportEqualsDeclaration(input);
82152 }
82153 case 249 /* ImportDeclaration */: {
82154 return transformImportDeclaration(input);
82155 }
82156 }
82157 if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
82158 return;
82159 // Elide implementation signatures from overload sets
82160 if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
82161 return;
82162 var previousEnclosingDeclaration;
82163 if (isEnclosingDeclaration(input)) {
82164 previousEnclosingDeclaration = enclosingDeclaration;
82165 enclosingDeclaration = input;
82166 }
82167 var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
82168 var oldDiag = getSymbolAccessibilityDiagnostic;
82169 if (canProdiceDiagnostic) {
82170 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
82171 }
82172 var previousNeedsDeclare = needsDeclare;
82173 switch (input.kind) {
82174 case 242 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
82175 return cleanup(ts.updateTypeAliasDeclaration(input,
82176 /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
82177 case 241 /* InterfaceDeclaration */: {
82178 return cleanup(ts.updateInterfaceDeclaration(input,
82179 /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
82180 }
82181 case 239 /* FunctionDeclaration */: {
82182 // Generators lose their generator-ness, excepting their return type
82183 var clean = cleanup(ts.updateFunctionDeclaration(input,
82184 /*decorators*/ undefined, ensureModifiers(input, isPrivate),
82185 /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type),
82186 /*body*/ undefined));
82187 if (clean && resolver.isExpandoFunctionDeclaration(input)) {
82188 var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) {
82189 if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
82190 return undefined;
82191 }
82192 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
82193 var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
82194 getSymbolAccessibilityDiagnostic = oldDiag;
82195 var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
82196 return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
82197 });
82198 var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */);
82199 return [clean, namespaceDecl];
82200 }
82201 else {
82202 return clean;
82203 }
82204 }
82205 case 244 /* ModuleDeclaration */: {
82206 needsDeclare = false;
82207 var inner = input.body;
82208 if (inner && inner.kind === 245 /* ModuleBlock */) {
82209 var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
82210 var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements));
82211 needsDeclare = previousNeedsDeclare;
82212 var mods = ensureModifiers(input, isPrivate);
82213 return cleanup(ts.updateModuleDeclaration(input,
82214 /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
82215 }
82216 else {
82217 needsDeclare = previousNeedsDeclare;
82218 var mods = ensureModifiers(input, isPrivate);
82219 needsDeclare = false;
82220 ts.visitNode(inner, visitDeclarationStatements);
82221 // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
82222 var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217
82223 var body = lateStatementReplacementMap.get(id);
82224 lateStatementReplacementMap.delete(id);
82225 return cleanup(ts.updateModuleDeclaration(input,
82226 /*decorators*/ undefined, mods, input.name, body));
82227 }
82228 }
82229 case 240 /* ClassDeclaration */: {
82230 var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate));
82231 var typeParameters = ensureTypeParams(input, input.typeParameters);
82232 var ctor = ts.getFirstConstructorWithBody(input);
82233 var parameterProperties = void 0;
82234 if (ctor) {
82235 var oldDiag_1 = getSymbolAccessibilityDiagnostic;
82236 parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
82237 if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
82238 return;
82239 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
82240 if (param.name.kind === 72 /* Identifier */) {
82241 return preserveJsDoc(ts.createProperty(
82242 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
82243 }
82244 else {
82245 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
82246 return walkBindingPattern(param.name);
82247 }
82248 function walkBindingPattern(pattern) {
82249 var elems;
82250 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
82251 var elem = _a[_i];
82252 if (ts.isOmittedExpression(elem))
82253 continue;
82254 if (ts.isBindingPattern(elem.name)) {
82255 elems = ts.concatenate(elems, walkBindingPattern(elem.name));
82256 }
82257 elems = elems || [];
82258 elems.push(ts.createProperty(
82259 /*decorators*/ undefined, ensureModifiers(param), elem.name,
82260 /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined),
82261 /*initializer*/ undefined));
82262 }
82263 return elems;
82264 }
82265 }));
82266 getSymbolAccessibilityDiagnostic = oldDiag_1;
82267 }
82268 var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree)));
82269 var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
82270 if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) {
82271 // We must add a temporary declaration for the extends clause expression
82272 var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
82273 var newId_1 = ts.createOptimisticUniqueName(oldId + "_base");
82274 getSymbolAccessibilityDiagnostic = function () { return ({
82275 diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
82276 errorNode: extendsClause_1,
82277 typeName: input.name
82278 }); };
82279 var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
82280 var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(125 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
82281 var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) {
82282 if (clause.token === 86 /* ExtendsKeyword */) {
82283 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
82284 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
82285 var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); }));
82286 getSymbolAccessibilityDiagnostic = oldDiag_2;
82287 return newClause;
82288 }
82289 return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 96 /* NullKeyword */; })), visitDeclarationSubtree));
82290 }));
82291 return [statement, cleanup(ts.updateClassDeclaration(input,
82292 /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
82293 }
82294 else {
82295 var heritageClauses = transformHeritageClauses(input.heritageClauses);
82296 return cleanup(ts.updateClassDeclaration(input,
82297 /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
82298 }
82299 }
82300 case 219 /* VariableStatement */: {
82301 return cleanup(transformVariableStatement(input, isPrivate));
82302 }
82303 case 243 /* EnumDeclaration */: {
82304 return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
82305 if (shouldStripInternal(m))
82306 return;
82307 // Rewrite enum values to their constants, if available
82308 var constValue = resolver.getConstantValue(m);
82309 return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m);
82310 }))));
82311 }
82312 }
82313 // Anything left unhandled is an error, so this should be unreachable
82314 return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
82315 function cleanup(node) {
82316 if (isEnclosingDeclaration(input)) {
82317 enclosingDeclaration = previousEnclosingDeclaration;
82318 }
82319 if (canProdiceDiagnostic) {
82320 getSymbolAccessibilityDiagnostic = oldDiag;
82321 }
82322 if (input.kind === 244 /* ModuleDeclaration */) {
82323 needsDeclare = previousNeedsDeclare;
82324 }
82325 if (node === input) {
82326 return node;
82327 }
82328 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
82329 }
82330 }
82331 function transformVariableStatement(input, privateDeclaration) {
82332 if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
82333 return;
82334 var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
82335 if (!ts.length(nodes))
82336 return;
82337 return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input, privateDeclaration)), ts.updateVariableDeclarationList(input.declarationList, nodes));
82338 }
82339 function recreateBindingPattern(d) {
82340 return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
82341 }
82342 function recreateBindingElement(e) {
82343 if (e.kind === 210 /* OmittedExpression */) {
82344 return;
82345 }
82346 if (e.name) {
82347 if (!getBindingNameVisible(e))
82348 return;
82349 if (ts.isBindingPattern(e.name)) {
82350 return recreateBindingPattern(e.name);
82351 }
82352 else {
82353 return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
82354 }
82355 }
82356 }
82357 function checkName(node) {
82358 var oldDiag;
82359 if (!suppressNewDiagnosticContexts) {
82360 oldDiag = getSymbolAccessibilityDiagnostic;
82361 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
82362 }
82363 errorNameNode = node.name;
82364 ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
82365 var decl = node;
82366 var entityName = decl.name.expression;
82367 checkEntityNameVisibility(entityName, enclosingDeclaration);
82368 if (!suppressNewDiagnosticContexts) {
82369 getSymbolAccessibilityDiagnostic = oldDiag;
82370 }
82371 errorNameNode = undefined;
82372 }
82373 function shouldStripInternal(node) {
82374 return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
82375 }
82376 function isScopeMarker(node) {
82377 return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
82378 }
82379 function hasScopeMarker(node) {
82380 if (ts.isModuleBlock(node)) {
82381 return ts.some(node.statements, isScopeMarker);
82382 }
82383 return false;
82384 }
82385 function ensureModifiers(node, privateDeclaration) {
82386 var currentFlags = ts.getModifierFlags(node);
82387 var newFlags = ensureModifierFlags(node, privateDeclaration);
82388 if (currentFlags === newFlags) {
82389 return node.modifiers;
82390 }
82391 return ts.createModifiersFromModifierFlags(newFlags);
82392 }
82393 function ensureModifierFlags(node, privateDeclaration) {
82394 var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
82395 var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
82396 var parentIsFile = node.parent.kind === 284 /* SourceFile */;
82397 if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
82398 mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
82399 additions = 0 /* None */;
82400 }
82401 return maskModifierFlags(node, mask, additions);
82402 }
82403 function ensureAccessor(node) {
82404 var accessors = resolver.getAllAccessorDeclarations(node);
82405 if (node.kind !== accessors.firstAccessor.kind) {
82406 return;
82407 }
82408 var accessorType = getTypeAnnotationFromAccessor(node);
82409 if (!accessorType && accessors.secondAccessor) {
82410 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
82411 // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message
82412 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
82413 }
82414 var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined);
82415 var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile);
82416 if (leadingsSyntheticCommentRanges) {
82417 var _loop_10 = function (range) {
82418 if (range.kind === 3 /* MultiLineCommentTrivia */) {
82419 var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2);
82420 var lines = text.split(/\r\n?|\n/g);
82421 if (lines.length > 1) {
82422 var lastLines = lines.slice(1);
82423 var indentation_1 = ts.guessIndentation(lastLines);
82424 text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine);
82425 }
82426 ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine);
82427 }
82428 };
82429 for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) {
82430 var range = leadingsSyntheticCommentRanges_1[_i];
82431 _loop_10(range);
82432 }
82433 }
82434 return prop;
82435 }
82436 function transformHeritageClauses(nodes) {
82437 return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) {
82438 return ts.isEntityNameExpression(t.expression) || (clause.token === 86 /* ExtendsKeyword */ && t.expression.kind === 96 /* NullKeyword */);
82439 })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
82440 }
82441 }
82442 ts.transformDeclarations = transformDeclarations;
82443 function isAlwaysType(node) {
82444 if (node.kind === 241 /* InterfaceDeclaration */) {
82445 return true;
82446 }
82447 return false;
82448 }
82449 // Elide "public" modifier, as it is the default
82450 function maskModifiers(node, modifierMask, modifierAdditions) {
82451 return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
82452 }
82453 function maskModifierFlags(node, modifierMask, modifierAdditions) {
82454 if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; }
82455 if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
82456 var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions;
82457 if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
82458 // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
82459 // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
82460 flags ^= 1 /* Export */;
82461 }
82462 if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
82463 flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
82464 }
82465 return flags;
82466 }
82467 function getTypeAnnotationFromAccessor(accessor) {
82468 if (accessor) {
82469 return accessor.kind === 158 /* GetAccessor */
82470 ? accessor.type // Getter - return type
82471 : accessor.parameters.length > 0
82472 ? accessor.parameters[0].type // Setter parameter type
82473 : undefined;
82474 }
82475 }
82476 function canHaveLiteralInitializer(node) {
82477 switch (node.kind) {
82478 case 154 /* PropertyDeclaration */:
82479 case 153 /* PropertySignature */:
82480 return !ts.hasModifier(node, 8 /* Private */);
82481 case 151 /* Parameter */:
82482 case 237 /* VariableDeclaration */:
82483 return true;
82484 }
82485 return false;
82486 }
82487 function isPreservedDeclarationStatement(node) {
82488 switch (node.kind) {
82489 case 239 /* FunctionDeclaration */:
82490 case 244 /* ModuleDeclaration */:
82491 case 248 /* ImportEqualsDeclaration */:
82492 case 241 /* InterfaceDeclaration */:
82493 case 240 /* ClassDeclaration */:
82494 case 242 /* TypeAliasDeclaration */:
82495 case 243 /* EnumDeclaration */:
82496 case 219 /* VariableStatement */:
82497 case 249 /* ImportDeclaration */:
82498 case 255 /* ExportDeclaration */:
82499 case 254 /* ExportAssignment */:
82500 return true;
82501 }
82502 return false;
82503 }
82504 function isProcessedComponent(node) {
82505 switch (node.kind) {
82506 case 161 /* ConstructSignature */:
82507 case 157 /* Constructor */:
82508 case 156 /* MethodDeclaration */:
82509 case 158 /* GetAccessor */:
82510 case 159 /* SetAccessor */:
82511 case 154 /* PropertyDeclaration */:
82512 case 153 /* PropertySignature */:
82513 case 155 /* MethodSignature */:
82514 case 160 /* CallSignature */:
82515 case 162 /* IndexSignature */:
82516 case 237 /* VariableDeclaration */:
82517 case 150 /* TypeParameter */:
82518 case 211 /* ExpressionWithTypeArguments */:
82519 case 164 /* TypeReference */:
82520 case 175 /* ConditionalType */:
82521 case 165 /* FunctionType */:
82522 case 166 /* ConstructorType */:
82523 case 183 /* ImportType */:
82524 return true;
82525 }
82526 return false;
82527 }
82528})(ts || (ts = {}));
82529/* @internal */
82530var ts;
82531(function (ts) {
82532 function getModuleTransformer(moduleKind) {
82533 switch (moduleKind) {
82534 case ts.ModuleKind.ESNext:
82535 case ts.ModuleKind.ES2015:
82536 return ts.transformES2015Module;
82537 case ts.ModuleKind.System:
82538 return ts.transformSystemModule;
82539 default:
82540 return ts.transformModule;
82541 }
82542 }
82543 var TransformationState;
82544 (function (TransformationState) {
82545 TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
82546 TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
82547 TransformationState[TransformationState["Completed"] = 2] = "Completed";
82548 TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
82549 })(TransformationState || (TransformationState = {}));
82550 var SyntaxKindFeatureFlags;
82551 (function (SyntaxKindFeatureFlags) {
82552 SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
82553 SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
82554 })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
82555 function getTransformers(compilerOptions, customTransformers) {
82556 var jsx = compilerOptions.jsx;
82557 var languageVersion = ts.getEmitScriptTarget(compilerOptions);
82558 var moduleKind = ts.getEmitModuleKind(compilerOptions);
82559 var transformers = [];
82560 ts.addRange(transformers, customTransformers && customTransformers.before);
82561 transformers.push(ts.transformTypeScript);
82562 if (jsx === 2 /* React */) {
82563 transformers.push(ts.transformJsx);
82564 }
82565 if (languageVersion < 7 /* ESNext */) {
82566 transformers.push(ts.transformESNext);
82567 }
82568 if (languageVersion < 6 /* ES2019 */) {
82569 transformers.push(ts.transformES2019);
82570 }
82571 if (languageVersion < 5 /* ES2018 */) {
82572 transformers.push(ts.transformES2018);
82573 }
82574 if (languageVersion < 4 /* ES2017 */) {
82575 transformers.push(ts.transformES2017);
82576 }
82577 if (languageVersion < 3 /* ES2016 */) {
82578 transformers.push(ts.transformES2016);
82579 }
82580 if (languageVersion < 2 /* ES2015 */) {
82581 transformers.push(ts.transformES2015);
82582 transformers.push(ts.transformGenerators);
82583 }
82584 transformers.push(getModuleTransformer(moduleKind));
82585 // The ES5 transformer is last so that it can substitute expressions like `exports.default`
82586 // for ES3.
82587 if (languageVersion < 1 /* ES5 */) {
82588 transformers.push(ts.transformES5);
82589 }
82590 ts.addRange(transformers, customTransformers && customTransformers.after);
82591 return transformers;
82592 }
82593 ts.getTransformers = getTransformers;
82594 function noEmitSubstitution(_hint, node) {
82595 return node;
82596 }
82597 ts.noEmitSubstitution = noEmitSubstitution;
82598 function noEmitNotification(hint, node, callback) {
82599 callback(hint, node);
82600 }
82601 ts.noEmitNotification = noEmitNotification;
82602 /**
82603 * Transforms an array of SourceFiles by passing them through each transformer.
82604 *
82605 * @param resolver The emit resolver provided by the checker.
82606 * @param host The emit host object used to interact with the file system.
82607 * @param options Compiler options to surface in the `TransformationContext`.
82608 * @param nodes An array of nodes to transform.
82609 * @param transforms An array of `TransformerFactory` callbacks.
82610 * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
82611 */
82612 function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
82613 var enabledSyntaxKindFeatures = new Array(317 /* Count */);
82614 var lexicalEnvironmentVariableDeclarations;
82615 var lexicalEnvironmentFunctionDeclarations;
82616 var lexicalEnvironmentVariableDeclarationsStack = [];
82617 var lexicalEnvironmentFunctionDeclarationsStack = [];
82618 var lexicalEnvironmentStackOffset = 0;
82619 var lexicalEnvironmentSuspended = false;
82620 var emitHelpers;
82621 var onSubstituteNode = noEmitSubstitution;
82622 var onEmitNode = noEmitNotification;
82623 var state = 0 /* Uninitialized */;
82624 var diagnostics = [];
82625 // The transformation context is provided to each transformer as part of transformer
82626 // initialization.
82627 var context = {
82628 getCompilerOptions: function () { return options; },
82629 getEmitResolver: function () { return resolver; },
82630 getEmitHost: function () { return host; },
82631 startLexicalEnvironment: startLexicalEnvironment,
82632 suspendLexicalEnvironment: suspendLexicalEnvironment,
82633 resumeLexicalEnvironment: resumeLexicalEnvironment,
82634 endLexicalEnvironment: endLexicalEnvironment,
82635 hoistVariableDeclaration: hoistVariableDeclaration,
82636 hoistFunctionDeclaration: hoistFunctionDeclaration,
82637 requestEmitHelper: requestEmitHelper,
82638 readEmitHelpers: readEmitHelpers,
82639 enableSubstitution: enableSubstitution,
82640 enableEmitNotification: enableEmitNotification,
82641 isSubstitutionEnabled: isSubstitutionEnabled,
82642 isEmitNotificationEnabled: isEmitNotificationEnabled,
82643 get onSubstituteNode() { return onSubstituteNode; },
82644 set onSubstituteNode(value) {
82645 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
82646 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
82647 onSubstituteNode = value;
82648 },
82649 get onEmitNode() { return onEmitNode; },
82650 set onEmitNode(value) {
82651 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
82652 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
82653 onEmitNode = value;
82654 },
82655 addDiagnostic: function (diag) {
82656 diagnostics.push(diag);
82657 }
82658 };
82659 // Ensure the parse tree is clean before applying transformations
82660 for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
82661 var node = nodes_4[_i];
82662 ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
82663 }
82664 ts.performance.mark("beforeTransform");
82665 // Chain together and initialize each transformer.
82666 var transformation = ts.chain.apply(void 0, transformers)(context);
82667 // prevent modification of transformation hooks.
82668 state = 1 /* Initialized */;
82669 // Transform each node.
82670 var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
82671 // prevent modification of the lexical environment.
82672 state = 2 /* Completed */;
82673 ts.performance.mark("afterTransform");
82674 ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
82675 return {
82676 transformed: transformed,
82677 substituteNode: substituteNode,
82678 emitNodeWithNotification: emitNodeWithNotification,
82679 dispose: dispose,
82680 diagnostics: diagnostics
82681 };
82682 function transformRoot(node) {
82683 return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
82684 }
82685 /**
82686 * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
82687 */
82688 function enableSubstitution(kind) {
82689 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
82690 enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
82691 }
82692 /**
82693 * Determines whether expression substitutions are enabled for the provided node.
82694 */
82695 function isSubstitutionEnabled(node) {
82696 return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
82697 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
82698 }
82699 /**
82700 * Emits a node with possible substitution.
82701 *
82702 * @param hint A hint as to the intended usage of the node.
82703 * @param node The node to emit.
82704 * @param emitCallback The callback used to emit the node or its substitute.
82705 */
82706 function substituteNode(hint, node) {
82707 ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
82708 return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
82709 }
82710 /**
82711 * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
82712 */
82713 function enableEmitNotification(kind) {
82714 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
82715 enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
82716 }
82717 /**
82718 * Determines whether before/after emit notifications should be raised in the pretty
82719 * printer when it emits a node.
82720 */
82721 function isEmitNotificationEnabled(node) {
82722 return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
82723 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
82724 }
82725 /**
82726 * Emits a node with possible emit notification.
82727 *
82728 * @param hint A hint as to the intended usage of the node.
82729 * @param node The node to emit.
82730 * @param emitCallback The callback used to emit the node.
82731 */
82732 function emitNodeWithNotification(hint, node, emitCallback) {
82733 ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
82734 if (node) {
82735 if (isEmitNotificationEnabled(node)) {
82736 onEmitNode(hint, node, emitCallback);
82737 }
82738 else {
82739 emitCallback(hint, node);
82740 }
82741 }
82742 }
82743 /**
82744 * Records a hoisted variable declaration for the provided name within a lexical environment.
82745 */
82746 function hoistVariableDeclaration(name) {
82747 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
82748 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
82749 var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
82750 if (!lexicalEnvironmentVariableDeclarations) {
82751 lexicalEnvironmentVariableDeclarations = [decl];
82752 }
82753 else {
82754 lexicalEnvironmentVariableDeclarations.push(decl);
82755 }
82756 }
82757 /**
82758 * Records a hoisted function declaration within a lexical environment.
82759 */
82760 function hoistFunctionDeclaration(func) {
82761 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
82762 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
82763 if (!lexicalEnvironmentFunctionDeclarations) {
82764 lexicalEnvironmentFunctionDeclarations = [func];
82765 }
82766 else {
82767 lexicalEnvironmentFunctionDeclarations.push(func);
82768 }
82769 }
82770 /**
82771 * Starts a new lexical environment. Any existing hoisted variable or function declarations
82772 * are pushed onto a stack, and the related storage variables are reset.
82773 */
82774 function startLexicalEnvironment() {
82775 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
82776 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
82777 ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
82778 // Save the current lexical environment. Rather than resizing the array we adjust the
82779 // stack size variable. This allows us to reuse existing array slots we've
82780 // already allocated between transformations to avoid allocation and GC overhead during
82781 // transformation.
82782 lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
82783 lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
82784 lexicalEnvironmentStackOffset++;
82785 lexicalEnvironmentVariableDeclarations = undefined;
82786 lexicalEnvironmentFunctionDeclarations = undefined;
82787 }
82788 /** Suspends the current lexical environment, usually after visiting a parameter list. */
82789 function suspendLexicalEnvironment() {
82790 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
82791 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
82792 ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
82793 lexicalEnvironmentSuspended = true;
82794 }
82795 /** Resumes a suspended lexical environment, usually before visiting a function body. */
82796 function resumeLexicalEnvironment() {
82797 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
82798 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
82799 ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
82800 lexicalEnvironmentSuspended = false;
82801 }
82802 /**
82803 * Ends a lexical environment. The previous set of hoisted declarations are restored and
82804 * any hoisted declarations added in this environment are returned.
82805 */
82806 function endLexicalEnvironment() {
82807 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
82808 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
82809 ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
82810 var statements;
82811 if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) {
82812 if (lexicalEnvironmentFunctionDeclarations) {
82813 statements = lexicalEnvironmentFunctionDeclarations.slice();
82814 }
82815 if (lexicalEnvironmentVariableDeclarations) {
82816 var statement = ts.createVariableStatement(
82817 /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
82818 if (!statements) {
82819 statements = [statement];
82820 }
82821 else {
82822 statements.push(statement);
82823 }
82824 }
82825 }
82826 // Restore the previous lexical environment.
82827 lexicalEnvironmentStackOffset--;
82828 lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
82829 lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
82830 if (lexicalEnvironmentStackOffset === 0) {
82831 lexicalEnvironmentVariableDeclarationsStack = [];
82832 lexicalEnvironmentFunctionDeclarationsStack = [];
82833 }
82834 return statements;
82835 }
82836 function requestEmitHelper(helper) {
82837 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
82838 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
82839 ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
82840 emitHelpers = ts.append(emitHelpers, helper);
82841 }
82842 function readEmitHelpers() {
82843 ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
82844 ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
82845 var helpers = emitHelpers;
82846 emitHelpers = undefined;
82847 return helpers;
82848 }
82849 function dispose() {
82850 if (state < 3 /* Disposed */) {
82851 // Clean up emit nodes on parse tree
82852 for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
82853 var node = nodes_5[_i];
82854 ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
82855 }
82856 // Release references to external entries for GC purposes.
82857 lexicalEnvironmentVariableDeclarations = undefined;
82858 lexicalEnvironmentVariableDeclarationsStack = undefined;
82859 lexicalEnvironmentFunctionDeclarations = undefined;
82860 lexicalEnvironmentFunctionDeclarationsStack = undefined;
82861 onSubstituteNode = undefined;
82862 onEmitNode = undefined;
82863 emitHelpers = undefined;
82864 // Prevent further use of the transformation result.
82865 state = 3 /* Disposed */;
82866 }
82867 }
82868 }
82869 ts.transformNodes = transformNodes;
82870})(ts || (ts = {}));
82871var ts;
82872(function (ts) {
82873 var brackets = createBracketsMap();
82874 var syntheticParent = { pos: -1, end: -1 };
82875 /*@internal*/
82876 function isBuildInfoFile(file) {
82877 return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
82878 }
82879 ts.isBuildInfoFile = isBuildInfoFile;
82880 /*@internal*/
82881 /**
82882 * Iterates over the source files that are expected to have an emit output.
82883 *
82884 * @param host An EmitHost.
82885 * @param action The action to execute.
82886 * @param sourceFilesOrTargetSourceFile
82887 * If an array, the full list of source files to emit.
82888 * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
82889 */
82890 function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
82891 if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
82892 var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
82893 var options = host.getCompilerOptions();
82894 if (options.outFile || options.out) {
82895 var prepends = host.getPrependNodes();
82896 if (sourceFiles.length || prepends.length) {
82897 var bundle = ts.createBundle(sourceFiles, prepends);
82898 var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
82899 if (result) {
82900 return result;
82901 }
82902 }
82903 }
82904 else {
82905 if (!onlyBuildInfo) {
82906 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
82907 var sourceFile = sourceFiles_1[_a];
82908 var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
82909 if (result) {
82910 return result;
82911 }
82912 }
82913 }
82914 if (includeBuildInfo) {
82915 var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
82916 if (buildInfoPath)
82917 return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
82918 }
82919 }
82920 }
82921 ts.forEachEmittedFile = forEachEmittedFile;
82922 /*@internal*/
82923 function getOutputPathForBuildInfo(options) {
82924 var configFile = options.configFilePath;
82925 if (!configFile || !ts.isIncrementalCompilation(options))
82926 return undefined;
82927 if (options.tsBuildInfoFile)
82928 return options.tsBuildInfoFile;
82929 var outPath = options.outFile || options.out;
82930 var buildInfoExtensionLess;
82931 if (outPath) {
82932 buildInfoExtensionLess = ts.removeFileExtension(outPath);
82933 }
82934 else {
82935 var configFileExtensionLess = ts.removeFileExtension(configFile);
82936 buildInfoExtensionLess = options.outDir ?
82937 options.rootDir ?
82938 ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
82939 ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
82940 configFileExtensionLess;
82941 }
82942 return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
82943 }
82944 ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
82945 /*@internal*/
82946 function getOutputPathsForBundle(options, forceDtsPaths) {
82947 var outPath = options.outFile || options.out;
82948 var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
82949 var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
82950 var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
82951 var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
82952 var buildInfoPath = getOutputPathForBuildInfo(options);
82953 return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
82954 }
82955 ts.getOutputPathsForBundle = getOutputPathsForBundle;
82956 /*@internal*/
82957 function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
82958 var options = host.getCompilerOptions();
82959 if (sourceFile.kind === 285 /* Bundle */) {
82960 return getOutputPathsForBundle(options, forceDtsPaths);
82961 }
82962 else {
82963 var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
82964 // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
82965 var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) &&
82966 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
82967 var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
82968 var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
82969 // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error
82970 var isJs = ts.isSourceFileJS(sourceFile);
82971 var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
82972 var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
82973 return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
82974 }
82975 }
82976 ts.getOutputPathsFor = getOutputPathsFor;
82977 function getSourceMapFilePath(jsFilePath, options) {
82978 return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
82979 }
82980 // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
82981 // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
82982 // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
82983 /* @internal */
82984 function getOutputExtension(sourceFile, options) {
82985 if (ts.isJsonSourceFile(sourceFile)) {
82986 return ".json" /* Json */;
82987 }
82988 if (options.jsx === 1 /* Preserve */) {
82989 if (ts.isSourceFileJS(sourceFile)) {
82990 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
82991 return ".jsx" /* Jsx */;
82992 }
82993 }
82994 else if (sourceFile.languageVariant === 1 /* JSX */) {
82995 // TypeScript source file preserving JSX syntax
82996 return ".jsx" /* Jsx */;
82997 }
82998 }
82999 return ".js" /* Js */;
83000 }
83001 ts.getOutputExtension = getOutputExtension;
83002 function rootDirOfOptions(configFile) {
83003 return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath));
83004 }
83005 function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
83006 return outputDir ?
83007 ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
83008 inputFileName;
83009 }
83010 /* @internal */
83011 function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
83012 ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(inputFileName));
83013 return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
83014 }
83015 ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
83016 function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
83017 var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
83018 var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
83019 ".json" /* Json */ :
83020 ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
83021 ".jsx" /* Jsx */ :
83022 ".js" /* Js */);
83023 return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
83024 outputFileName :
83025 undefined;
83026 }
83027 /*@internal*/
83028 function getAllProjectOutputs(configFile, ignoreCase) {
83029 var outputs;
83030 var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
83031 if (configFile.options.outFile || configFile.options.out) {
83032 var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
83033 addOutput(jsFilePath);
83034 addOutput(sourceMapFilePath);
83035 addOutput(declarationFilePath);
83036 addOutput(declarationMapPath);
83037 addOutput(buildInfoPath);
83038 }
83039 else {
83040 for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
83041 var inputFileName = _c[_b];
83042 if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
83043 continue;
83044 var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
83045 addOutput(js);
83046 if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
83047 continue;
83048 if (configFile.options.sourceMap) {
83049 addOutput(js + ".map");
83050 }
83051 if (ts.getEmitDeclarations(configFile.options) && ts.hasTSFileExtension(inputFileName)) {
83052 var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
83053 addOutput(dts);
83054 if (configFile.options.declarationMap) {
83055 addOutput(dts + ".map");
83056 }
83057 }
83058 }
83059 addOutput(getOutputPathForBuildInfo(configFile.options));
83060 }
83061 return outputs || ts.emptyArray;
83062 }
83063 ts.getAllProjectOutputs = getAllProjectOutputs;
83064 /*@internal*/
83065 function getFirstProjectOutput(configFile, ignoreCase) {
83066 if (configFile.options.outFile || configFile.options.out) {
83067 var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
83068 return ts.Debug.assertDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
83069 }
83070 for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
83071 var inputFileName = _b[_a];
83072 if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
83073 continue;
83074 var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
83075 if (jsFilePath)
83076 return jsFilePath;
83077 }
83078 var buildInfoPath = getOutputPathForBuildInfo(configFile.options);
83079 if (buildInfoPath)
83080 return buildInfoPath;
83081 return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
83082 }
83083 ts.getFirstProjectOutput = getFirstProjectOutput;
83084 /*@internal*/
83085 // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
83086 function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
83087 var compilerOptions = host.getCompilerOptions();
83088 var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
83089 var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
83090 var emitterDiagnostics = ts.createDiagnosticCollection();
83091 var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
83092 var writer = ts.createTextWriter(newLine);
83093 var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
83094 var bundleBuildInfo;
83095 var emitSkipped = false;
83096 var exportedModulesFromDeclarationEmit;
83097 // Emit each output file
83098 enter();
83099 forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
83100 exit();
83101 return {
83102 emitSkipped: emitSkipped,
83103 diagnostics: emitterDiagnostics.getDiagnostics(),
83104 emittedFiles: emittedFilesList,
83105 sourceMaps: sourceMapDataList,
83106 exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
83107 };
83108 function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
83109 var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
83110 if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
83111 bundleBuildInfo = {
83112 commonSourceDirectory: host.getCommonSourceDirectory(),
83113 sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
83114 };
83115 }
83116 emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
83117 emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
83118 emitBuildInfo(bundleBuildInfo, buildInfoPath);
83119 if (!emitSkipped && emittedFilesList) {
83120 if (!emitOnlyDtsFiles) {
83121 if (jsFilePath) {
83122 emittedFilesList.push(jsFilePath);
83123 }
83124 if (sourceMapFilePath) {
83125 emittedFilesList.push(sourceMapFilePath);
83126 }
83127 if (buildInfoPath) {
83128 emittedFilesList.push(buildInfoPath);
83129 }
83130 }
83131 if (declarationFilePath) {
83132 emittedFilesList.push(declarationFilePath);
83133 }
83134 if (declarationMapPath) {
83135 emittedFilesList.push(declarationMapPath);
83136 }
83137 }
83138 }
83139 function emitBuildInfo(bundle, buildInfoPath) {
83140 // Write build information if applicable
83141 if (!buildInfoPath || targetSourceFile || emitSkipped)
83142 return;
83143 var program = host.getProgramBuildInfo();
83144 if (!bundle && !program)
83145 return;
83146 if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
83147 emitSkipped = true;
83148 return;
83149 }
83150 ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
83151 }
83152 function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
83153 if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
83154 return;
83155 }
83156 // Make sure not to write js file and source map file if any of them cannot be written
83157 if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
83158 emitSkipped = true;
83159 return;
83160 }
83161 // Transform the source files
83162 var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false);
83163 var printerOptions = {
83164 removeComments: compilerOptions.removeComments,
83165 newLine: compilerOptions.newLine,
83166 noEmitHelpers: compilerOptions.noEmitHelpers,
83167 module: compilerOptions.module,
83168 target: compilerOptions.target,
83169 sourceMap: compilerOptions.sourceMap,
83170 inlineSourceMap: compilerOptions.inlineSourceMap,
83171 inlineSources: compilerOptions.inlineSources,
83172 extendedDiagnostics: compilerOptions.extendedDiagnostics,
83173 writeBundleFileInfo: !!bundleBuildInfo
83174 };
83175 // Create a printer to print the nodes
83176 var printer = createPrinter(printerOptions, {
83177 // resolver hooks
83178 hasGlobalName: resolver.hasGlobalName,
83179 // transform hooks
83180 onEmitNode: transform.emitNodeWithNotification,
83181 substituteNode: transform.substituteNode,
83182 });
83183 ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
83184 printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
83185 // Clean up emit nodes on parse tree
83186 transform.dispose();
83187 if (bundleBuildInfo)
83188 bundleBuildInfo.js = printer.bundleFileInfo;
83189 }
83190 function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
83191 if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
83192 return;
83193 }
83194 var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
83195 // Setup and perform the transformation to retrieve declarations from the input files
83196 var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS);
83197 var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles;
83198 if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
83199 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
83200 // Do that here when emitting only dts files
83201 nonJsFiles.forEach(collectLinkedAliases);
83202 }
83203 var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false);
83204 if (ts.length(declarationTransform.diagnostics)) {
83205 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
83206 var diagnostic = _b[_a];
83207 emitterDiagnostics.add(diagnostic);
83208 }
83209 }
83210 var printerOptions = {
83211 removeComments: compilerOptions.removeComments,
83212 newLine: compilerOptions.newLine,
83213 noEmitHelpers: true,
83214 module: compilerOptions.module,
83215 target: compilerOptions.target,
83216 sourceMap: compilerOptions.sourceMap,
83217 inlineSourceMap: compilerOptions.inlineSourceMap,
83218 extendedDiagnostics: compilerOptions.extendedDiagnostics,
83219 onlyPrintJsDocStyle: true,
83220 writeBundleFileInfo: !!bundleBuildInfo,
83221 recordInternalSection: !!bundleBuildInfo
83222 };
83223 var declarationPrinter = createPrinter(printerOptions, {
83224 // resolver hooks
83225 hasGlobalName: resolver.hasGlobalName,
83226 // transform hooks
83227 onEmitNode: declarationTransform.emitNodeWithNotification,
83228 substituteNode: declarationTransform.substituteNode,
83229 });
83230 var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
83231 emitSkipped = emitSkipped || declBlocked;
83232 if (!declBlocked || emitOnlyDtsFiles) {
83233 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
83234 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
83235 sourceMap: compilerOptions.declarationMap,
83236 sourceRoot: compilerOptions.sourceRoot,
83237 mapRoot: compilerOptions.mapRoot,
83238 extendedDiagnostics: compilerOptions.extendedDiagnostics,
83239 });
83240 if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
83241 var sourceFile = declarationTransform.transformed[0];
83242 exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
83243 }
83244 }
83245 declarationTransform.dispose();
83246 if (bundleBuildInfo)
83247 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
83248 }
83249 function collectLinkedAliases(node) {
83250 if (ts.isExportAssignment(node)) {
83251 if (node.expression.kind === 72 /* Identifier */) {
83252 resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
83253 }
83254 return;
83255 }
83256 else if (ts.isExportSpecifier(node)) {
83257 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
83258 return;
83259 }
83260 ts.forEachChild(node, collectLinkedAliases);
83261 }
83262 function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
83263 var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
83264 var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
83265 var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
83266 var sourceMapGenerator;
83267 if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
83268 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
83269 }
83270 if (bundle) {
83271 printer.writeBundle(bundle, writer, sourceMapGenerator);
83272 }
83273 else {
83274 printer.writeFile(sourceFile, writer, sourceMapGenerator);
83275 }
83276 if (sourceMapGenerator) {
83277 if (sourceMapDataList) {
83278 sourceMapDataList.push({
83279 inputSourceFileNames: sourceMapGenerator.getSources(),
83280 sourceMap: sourceMapGenerator.toJSON()
83281 });
83282 }
83283 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
83284 if (sourceMappingURL) {
83285 if (!writer.isAtStartOfLine())
83286 writer.rawWrite(newLine);
83287 writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
83288 }
83289 // Write the source map
83290 if (sourceMapFilePath) {
83291 var sourceMap = sourceMapGenerator.toString();
83292 ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
83293 }
83294 }
83295 else {
83296 writer.writeLine();
83297 }
83298 // Write the output file
83299 ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
83300 // Reset state
83301 writer.clear();
83302 }
83303 function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
83304 return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
83305 && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
83306 }
83307 function getSourceRoot(mapOptions) {
83308 // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
83309 // relative paths of the sources list in the sourcemap
83310 var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
83311 return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
83312 }
83313 function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
83314 if (mapOptions.sourceRoot)
83315 return host.getCommonSourceDirectory();
83316 if (mapOptions.mapRoot) {
83317 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
83318 if (sourceFile) {
83319 // For modules or multiple emit files the mapRoot will have directory structure like the sources
83320 // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
83321 sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
83322 }
83323 if (ts.getRootLength(sourceMapDir) === 0) {
83324 // The relative paths are relative to the common directory
83325 sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
83326 }
83327 return sourceMapDir;
83328 }
83329 return ts.getDirectoryPath(ts.normalizePath(filePath));
83330 }
83331 function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
83332 if (mapOptions.inlineSourceMap) {
83333 // Encode the sourceMap into the sourceMap url
83334 var sourceMapText = sourceMapGenerator.toString();
83335 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
83336 return "data:application/json;base64," + base64SourceMapText;
83337 }
83338 var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath)));
83339 if (mapOptions.mapRoot) {
83340 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
83341 if (sourceFile) {
83342 // For modules or multiple emit files the mapRoot will have directory structure like the sources
83343 // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
83344 sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
83345 }
83346 if (ts.getRootLength(sourceMapDir) === 0) {
83347 // The relative paths are relative to the common directory
83348 sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
83349 return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
83350 ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
83351 host.getCurrentDirectory(), host.getCanonicalFileName,
83352 /*isAbsolutePathAnUrl*/ true);
83353 }
83354 else {
83355 return ts.combinePaths(sourceMapDir, sourceMapFile);
83356 }
83357 }
83358 return sourceMapFile;
83359 }
83360 }
83361 ts.emitFiles = emitFiles;
83362 /*@internal*/
83363 function getBuildInfoText(buildInfo) {
83364 return JSON.stringify(buildInfo, undefined, 2);
83365 }
83366 ts.getBuildInfoText = getBuildInfoText;
83367 /*@internal*/
83368 function getBuildInfo(buildInfoText) {
83369 return JSON.parse(buildInfoText);
83370 }
83371 ts.getBuildInfo = getBuildInfo;
83372 /*@internal*/
83373 ts.notImplementedResolver = {
83374 hasGlobalName: ts.notImplemented,
83375 getReferencedExportContainer: ts.notImplemented,
83376 getReferencedImportDeclaration: ts.notImplemented,
83377 getReferencedDeclarationWithCollidingName: ts.notImplemented,
83378 isDeclarationWithCollidingName: ts.notImplemented,
83379 isValueAliasDeclaration: ts.notImplemented,
83380 isReferencedAliasDeclaration: ts.notImplemented,
83381 isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
83382 getNodeCheckFlags: ts.notImplemented,
83383 isDeclarationVisible: ts.notImplemented,
83384 isLateBound: function (_node) { return false; },
83385 collectLinkedAliases: ts.notImplemented,
83386 isImplementationOfOverload: ts.notImplemented,
83387 isRequiredInitializedParameter: ts.notImplemented,
83388 isOptionalUninitializedParameterProperty: ts.notImplemented,
83389 isExpandoFunctionDeclaration: ts.notImplemented,
83390 getPropertiesOfContainerFunction: ts.notImplemented,
83391 createTypeOfDeclaration: ts.notImplemented,
83392 createReturnTypeOfSignatureDeclaration: ts.notImplemented,
83393 createTypeOfExpression: ts.notImplemented,
83394 createLiteralConstValue: ts.notImplemented,
83395 isSymbolAccessible: ts.notImplemented,
83396 isEntityNameVisible: ts.notImplemented,
83397 // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
83398 getConstantValue: ts.notImplemented,
83399 getReferencedValueDeclaration: ts.notImplemented,
83400 getTypeReferenceSerializationKind: ts.notImplemented,
83401 isOptionalParameter: ts.notImplemented,
83402 moduleExportsSomeValue: ts.notImplemented,
83403 isArgumentsLocalBinding: ts.notImplemented,
83404 getExternalModuleFileFromDeclaration: ts.notImplemented,
83405 getTypeReferenceDirectivesForEntityName: ts.notImplemented,
83406 getTypeReferenceDirectivesForSymbol: ts.notImplemented,
83407 isLiteralConstDeclaration: ts.notImplemented,
83408 getJsxFactoryEntity: ts.notImplemented,
83409 getAllAccessorDeclarations: ts.notImplemented,
83410 getSymbolOfExternalModuleSpecifier: ts.notImplemented,
83411 isBindingCapturedByNode: ts.notImplemented,
83412 };
83413 function createSourceFilesFromBundleBuildInfo(bundle) {
83414 var sourceFiles = bundle.sourceFiles.map(function (fileName) {
83415 var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
83416 sourceFile.fileName = fileName;
83417 sourceFile.text = "";
83418 sourceFile.statements = ts.createNodeArray();
83419 return sourceFile;
83420 });
83421 var jsBundle = ts.Debug.assertDefined(bundle.js);
83422 ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
83423 var sourceFile = sourceFiles[prologueInfo.file];
83424 sourceFile.text = prologueInfo.text;
83425 sourceFile.end = prologueInfo.text.length;
83426 sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
83427 var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
83428 statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
83429 statement.expression.text = directive.expression.text;
83430 return statement;
83431 }));
83432 });
83433 return sourceFiles;
83434 }
83435 /*@internal*/
83436 function emitUsingBuildInfo(config, host, getCommandLine) {
83437 var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
83438 var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
83439 if (!buildInfoText)
83440 return buildInfoPath;
83441 var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
83442 if (!jsFileText)
83443 return jsFilePath;
83444 var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
83445 // error if no source map or for now if inline sourcemap
83446 if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
83447 return sourceMapFilePath || "inline sourcemap decoding";
83448 // read declaration text
83449 var declarationText = declarationFilePath && host.readFile(declarationFilePath);
83450 if (declarationFilePath && !declarationText)
83451 return declarationFilePath;
83452 var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
83453 // error if no source map or for now if inline sourcemap
83454 if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
83455 return declarationMapPath || "inline sourcemap decoding";
83456 var buildInfo = getBuildInfo(buildInfoText);
83457 if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
83458 return buildInfoPath;
83459 var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
83460 /*onlyOwnText*/ true);
83461 var outputFiles = [];
83462 var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
83463 var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
83464 var emitHost = {
83465 getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
83466 getCanonicalFileName: host.getCanonicalFileName,
83467 getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
83468 getCompilerOptions: function () { return config.options; },
83469 getCurrentDirectory: function () { return host.getCurrentDirectory(); },
83470 getNewLine: function () { return host.getNewLine(); },
83471 getSourceFile: ts.returnUndefined,
83472 getSourceFileByPath: ts.returnUndefined,
83473 getSourceFiles: function () { return sourceFilesForJsEmit; },
83474 getLibFileFromReference: ts.notImplemented,
83475 isSourceFileFromExternalLibrary: ts.returnFalse,
83476 getResolvedProjectReferenceToRedirect: ts.returnUndefined,
83477 writeFile: function (name, text, writeByteOrderMark) {
83478 switch (name) {
83479 case jsFilePath:
83480 if (jsFileText === text)
83481 return;
83482 break;
83483 case sourceMapFilePath:
83484 if (sourceMapText === text)
83485 return;
83486 break;
83487 case buildInfoPath:
83488 var newBuildInfo = getBuildInfo(text);
83489 newBuildInfo.program = buildInfo.program;
83490 // Update sourceFileInfo
83491 var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
83492 newBuildInfo.bundle.js.sources = js.sources;
83493 if (dts) {
83494 newBuildInfo.bundle.dts.sources = dts.sources;
83495 }
83496 newBuildInfo.bundle.sourceFiles = sourceFiles;
83497 outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
83498 return;
83499 case declarationFilePath:
83500 if (declarationText === text)
83501 return;
83502 break;
83503 case declarationMapPath:
83504 if (declarationMapText === text)
83505 return;
83506 break;
83507 default:
83508 ts.Debug.fail("Unexpected path: " + name);
83509 }
83510 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
83511 },
83512 isEmitBlocked: ts.returnFalse,
83513 readFile: function (f) { return host.readFile(f); },
83514 fileExists: function (f) { return host.fileExists(f); },
83515 directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
83516 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
83517 getProgramBuildInfo: ts.returnUndefined
83518 };
83519 emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
83520 return outputFiles;
83521 }
83522 ts.emitUsingBuildInfo = emitUsingBuildInfo;
83523 var PipelinePhase;
83524 (function (PipelinePhase) {
83525 PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
83526 PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
83527 PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
83528 PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
83529 PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
83530 })(PipelinePhase || (PipelinePhase = {}));
83531 function createPrinter(printerOptions, handlers) {
83532 if (printerOptions === void 0) { printerOptions = {}; }
83533 if (handlers === void 0) { handlers = {}; }
83534 var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken;
83535 var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
83536 var newLine = ts.getNewLineCharacter(printerOptions);
83537 var moduleKind = ts.getEmitModuleKind(printerOptions);
83538 var bundledHelpers = ts.createMap();
83539 var currentSourceFile;
83540 var nodeIdToGeneratedName; // Map of generated names for specific nodes.
83541 var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
83542 var generatedNames; // Set of names generated by the NameGenerator.
83543 var tempFlagsStack; // Stack of enclosing name generation scopes.
83544 var tempFlags; // TempFlags for the current name generation scope.
83545 var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
83546 var reservedNames; // TempFlags to reserve in nested name generation scopes.
83547 var writer;
83548 var ownWriter; // Reusable `EmitTextWriter` for basic printing.
83549 var write = writeBase;
83550 var isOwnFileEmit;
83551 var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
83552 var recordInternalSection = printerOptions.recordInternalSection;
83553 var sourceFileTextPos = 0;
83554 var sourceFileTextKind = "text" /* Text */;
83555 // Source Maps
83556 var sourceMapsDisabled = true;
83557 var sourceMapGenerator;
83558 var sourceMapSource;
83559 var sourceMapSourceIndex = -1;
83560 // Comments
83561 var containerPos = -1;
83562 var containerEnd = -1;
83563 var declarationListContainerEnd = -1;
83564 var currentLineMap;
83565 var detachedCommentsInfo;
83566 var hasWrittenComment = false;
83567 var commentsDisabled = !!printerOptions.removeComments;
83568 var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
83569 reset();
83570 return {
83571 // public API
83572 printNode: printNode,
83573 printList: printList,
83574 printFile: printFile,
83575 printBundle: printBundle,
83576 // internal API
83577 writeNode: writeNode,
83578 writeList: writeList,
83579 writeFile: writeFile,
83580 writeBundle: writeBundle,
83581 bundleFileInfo: bundleFileInfo
83582 };
83583 function printNode(hint, node, sourceFile) {
83584 switch (hint) {
83585 case 0 /* SourceFile */:
83586 ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
83587 break;
83588 case 2 /* IdentifierName */:
83589 ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
83590 break;
83591 case 1 /* Expression */:
83592 ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
83593 break;
83594 }
83595 switch (node.kind) {
83596 case 284 /* SourceFile */: return printFile(node);
83597 case 285 /* Bundle */: return printBundle(node);
83598 case 286 /* UnparsedSource */: return printUnparsedSource(node);
83599 }
83600 writeNode(hint, node, sourceFile, beginPrint());
83601 return endPrint();
83602 }
83603 function printList(format, nodes, sourceFile) {
83604 writeList(format, nodes, sourceFile, beginPrint());
83605 return endPrint();
83606 }
83607 function printBundle(bundle) {
83608 writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
83609 return endPrint();
83610 }
83611 function printFile(sourceFile) {
83612 writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
83613 return endPrint();
83614 }
83615 function printUnparsedSource(unparsed) {
83616 writeUnparsedSource(unparsed, beginPrint());
83617 return endPrint();
83618 }
83619 function writeNode(hint, node, sourceFile, output) {
83620 var previousWriter = writer;
83621 setWriter(output, /*_sourceMapGenerator*/ undefined);
83622 print(hint, node, sourceFile);
83623 reset();
83624 writer = previousWriter;
83625 }
83626 function writeList(format, nodes, sourceFile, output) {
83627 var previousWriter = writer;
83628 setWriter(output, /*_sourceMapGenerator*/ undefined);
83629 if (sourceFile) {
83630 setSourceFile(sourceFile);
83631 }
83632 emitList(syntheticParent, nodes, format);
83633 reset();
83634 writer = previousWriter;
83635 }
83636 function getTextPosWithWriteLine() {
83637 return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
83638 }
83639 function updateOrPushBundleFileTextLike(pos, end, kind) {
83640 var last = ts.lastOrUndefined(bundleFileInfo.sections);
83641 if (last && last.kind === kind) {
83642 last.end = end;
83643 }
83644 else {
83645 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
83646 }
83647 }
83648 function recordBundleFileInternalSectionStart(node) {
83649 if (recordInternalSection &&
83650 bundleFileInfo &&
83651 currentSourceFile &&
83652 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
83653 ts.isInternalDeclaration(node, currentSourceFile) &&
83654 sourceFileTextKind !== "internal" /* Internal */) {
83655 var prevSourceFileTextKind = sourceFileTextKind;
83656 recordBundleFileTextLikeSection(writer.getTextPos());
83657 sourceFileTextPos = getTextPosWithWriteLine();
83658 sourceFileTextKind = "internal" /* Internal */;
83659 return prevSourceFileTextKind;
83660 }
83661 return undefined;
83662 }
83663 function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
83664 if (prevSourceFileTextKind) {
83665 recordBundleFileTextLikeSection(writer.getTextPos());
83666 sourceFileTextPos = getTextPosWithWriteLine();
83667 sourceFileTextKind = prevSourceFileTextKind;
83668 }
83669 }
83670 function recordBundleFileTextLikeSection(end) {
83671 if (sourceFileTextPos < end) {
83672 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
83673 return true;
83674 }
83675 return false;
83676 }
83677 function writeBundle(bundle, output, sourceMapGenerator) {
83678 var _a;
83679 isOwnFileEmit = false;
83680 var previousWriter = writer;
83681 setWriter(output, sourceMapGenerator);
83682 emitShebangIfNeeded(bundle);
83683 emitPrologueDirectivesIfNeeded(bundle);
83684 emitHelpers(bundle);
83685 emitSyntheticTripleSlashReferencesIfNeeded(bundle);
83686 for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
83687 var prepend = _c[_b];
83688 writeLine();
83689 var pos = writer.getTextPos();
83690 var savedSections = bundleFileInfo && bundleFileInfo.sections;
83691 if (savedSections)
83692 bundleFileInfo.sections = [];
83693 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
83694 if (bundleFileInfo) {
83695 var newSections = bundleFileInfo.sections;
83696 bundleFileInfo.sections = savedSections;
83697 if (prepend.oldFileOfCurrentEmit)
83698 (_a = bundleFileInfo.sections).push.apply(_a, newSections);
83699 else {
83700 newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
83701 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
83702 }
83703 }
83704 }
83705 sourceFileTextPos = getTextPosWithWriteLine();
83706 for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
83707 var sourceFile = _e[_d];
83708 print(0 /* SourceFile */, sourceFile, sourceFile);
83709 }
83710 if (bundleFileInfo && bundle.sourceFiles.length) {
83711 var end = writer.getTextPos();
83712 if (recordBundleFileTextLikeSection(end)) {
83713 // Store prologues
83714 var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
83715 if (prologues) {
83716 if (!bundleFileInfo.sources)
83717 bundleFileInfo.sources = {};
83718 bundleFileInfo.sources.prologues = prologues;
83719 }
83720 // Store helpes
83721 var helpers = getHelpersFromBundledSourceFiles(bundle);
83722 if (helpers) {
83723 if (!bundleFileInfo.sources)
83724 bundleFileInfo.sources = {};
83725 bundleFileInfo.sources.helpers = helpers;
83726 }
83727 }
83728 }
83729 reset();
83730 writer = previousWriter;
83731 }
83732 function writeUnparsedSource(unparsed, output) {
83733 var previousWriter = writer;
83734 setWriter(output, /*_sourceMapGenerator*/ undefined);
83735 print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
83736 reset();
83737 writer = previousWriter;
83738 }
83739 function writeFile(sourceFile, output, sourceMapGenerator) {
83740 isOwnFileEmit = true;
83741 var previousWriter = writer;
83742 setWriter(output, sourceMapGenerator);
83743 emitShebangIfNeeded(sourceFile);
83744 emitPrologueDirectivesIfNeeded(sourceFile);
83745 print(0 /* SourceFile */, sourceFile, sourceFile);
83746 reset();
83747 writer = previousWriter;
83748 }
83749 function beginPrint() {
83750 return ownWriter || (ownWriter = ts.createTextWriter(newLine));
83751 }
83752 function endPrint() {
83753 var text = ownWriter.getText();
83754 ownWriter.clear();
83755 return text;
83756 }
83757 function print(hint, node, sourceFile) {
83758 if (sourceFile) {
83759 setSourceFile(sourceFile);
83760 }
83761 var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
83762 pipelinePhase(hint, node);
83763 }
83764 function setSourceFile(sourceFile) {
83765 currentSourceFile = sourceFile;
83766 currentLineMap = undefined;
83767 detachedCommentsInfo = undefined;
83768 if (sourceFile) {
83769 setSourceMapSource(sourceFile);
83770 }
83771 }
83772 function setWriter(_writer, _sourceMapGenerator) {
83773 if (_writer && printerOptions.omitTrailingSemicolon) {
83774 _writer = ts.getTrailingSemicolonOmittingWriter(_writer);
83775 }
83776 writer = _writer; // TODO: GH#18217
83777 sourceMapGenerator = _sourceMapGenerator;
83778 sourceMapsDisabled = !writer || !sourceMapGenerator;
83779 }
83780 function reset() {
83781 nodeIdToGeneratedName = [];
83782 autoGeneratedIdToGeneratedName = [];
83783 generatedNames = ts.createMap();
83784 tempFlagsStack = [];
83785 tempFlags = 0 /* Auto */;
83786 reservedNamesStack = [];
83787 currentSourceFile = undefined;
83788 currentLineMap = undefined;
83789 detachedCommentsInfo = undefined;
83790 setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
83791 }
83792 function getCurrentLineMap() {
83793 return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
83794 }
83795 function emit(node) {
83796 if (node === undefined)
83797 return;
83798 var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
83799 var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
83800 pipelinePhase(4 /* Unspecified */, node);
83801 recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
83802 }
83803 function emitIdentifierName(node) {
83804 if (node === undefined)
83805 return;
83806 var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
83807 pipelinePhase(2 /* IdentifierName */, node);
83808 }
83809 function emitExpression(node) {
83810 if (node === undefined)
83811 return;
83812 var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
83813 pipelinePhase(1 /* Expression */, node);
83814 }
83815 function getPipelinePhase(phase, node) {
83816 switch (phase) {
83817 case 0 /* Notification */:
83818 if (onEmitNode !== ts.noEmitNotification) {
83819 return pipelineEmitWithNotification;
83820 }
83821 // falls through
83822 case 1 /* Substitution */:
83823 if (substituteNode !== ts.noEmitSubstitution) {
83824 return pipelineEmitWithSubstitution;
83825 }
83826 // falls through
83827 case 2 /* Comments */:
83828 if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
83829 return pipelineEmitWithComments;
83830 }
83831 // falls through
83832 case 3 /* SourceMaps */:
83833 if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
83834 return pipelineEmitWithSourceMap;
83835 }
83836 // falls through
83837 case 4 /* Emit */:
83838 return pipelineEmitWithHint;
83839 default:
83840 return ts.Debug.assertNever(phase);
83841 }
83842 }
83843 function getNextPipelinePhase(currentPhase, node) {
83844 return getPipelinePhase(currentPhase + 1, node);
83845 }
83846 function pipelineEmitWithNotification(hint, node) {
83847 var pipelinePhase = getNextPipelinePhase(0 /* Notification */, node);
83848 onEmitNode(hint, node, pipelinePhase);
83849 }
83850 function pipelineEmitWithHint(hint, node) {
83851 if (hint === 0 /* SourceFile */)
83852 return emitSourceFile(ts.cast(node, ts.isSourceFile));
83853 if (hint === 2 /* IdentifierName */)
83854 return emitIdentifier(ts.cast(node, ts.isIdentifier));
83855 if (hint === 3 /* MappedTypeParameter */)
83856 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
83857 if (hint === 5 /* EmbeddedStatement */) {
83858 ts.Debug.assertNode(node, ts.isEmptyStatement);
83859 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
83860 }
83861 if (hint === 4 /* Unspecified */) {
83862 if (ts.isKeyword(node.kind))
83863 return writeTokenNode(node, writeKeyword);
83864 switch (node.kind) {
83865 // Pseudo-literals
83866 case 15 /* TemplateHead */:
83867 case 16 /* TemplateMiddle */:
83868 case 17 /* TemplateTail */:
83869 return emitLiteral(node);
83870 case 286 /* UnparsedSource */:
83871 case 280 /* UnparsedPrepend */:
83872 return emitUnparsedSourceOrPrepend(node);
83873 case 279 /* UnparsedPrologue */:
83874 return writeUnparsedNode(node);
83875 case 281 /* UnparsedText */:
83876 case 282 /* UnparsedInternalText */:
83877 return emitUnparsedTextLike(node);
83878 case 283 /* UnparsedSyntheticReference */:
83879 return emitUnparsedSyntheticReference(node);
83880 // Identifiers
83881 case 72 /* Identifier */:
83882 return emitIdentifier(node);
83883 // Parse tree nodes
83884 // Names
83885 case 148 /* QualifiedName */:
83886 return emitQualifiedName(node);
83887 case 149 /* ComputedPropertyName */:
83888 return emitComputedPropertyName(node);
83889 // Signature elements
83890 case 150 /* TypeParameter */:
83891 return emitTypeParameter(node);
83892 case 151 /* Parameter */:
83893 return emitParameter(node);
83894 case 152 /* Decorator */:
83895 return emitDecorator(node);
83896 // Type members
83897 case 153 /* PropertySignature */:
83898 return emitPropertySignature(node);
83899 case 154 /* PropertyDeclaration */:
83900 return emitPropertyDeclaration(node);
83901 case 155 /* MethodSignature */:
83902 return emitMethodSignature(node);
83903 case 156 /* MethodDeclaration */:
83904 return emitMethodDeclaration(node);
83905 case 157 /* Constructor */:
83906 return emitConstructor(node);
83907 case 158 /* GetAccessor */:
83908 case 159 /* SetAccessor */:
83909 return emitAccessorDeclaration(node);
83910 case 160 /* CallSignature */:
83911 return emitCallSignature(node);
83912 case 161 /* ConstructSignature */:
83913 return emitConstructSignature(node);
83914 case 162 /* IndexSignature */:
83915 return emitIndexSignature(node);
83916 // Types
83917 case 163 /* TypePredicate */:
83918 return emitTypePredicate(node);
83919 case 164 /* TypeReference */:
83920 return emitTypeReference(node);
83921 case 165 /* FunctionType */:
83922 return emitFunctionType(node);
83923 case 294 /* JSDocFunctionType */:
83924 return emitJSDocFunctionType(node);
83925 case 166 /* ConstructorType */:
83926 return emitConstructorType(node);
83927 case 167 /* TypeQuery */:
83928 return emitTypeQuery(node);
83929 case 168 /* TypeLiteral */:
83930 return emitTypeLiteral(node);
83931 case 169 /* ArrayType */:
83932 return emitArrayType(node);
83933 case 170 /* TupleType */:
83934 return emitTupleType(node);
83935 case 171 /* OptionalType */:
83936 return emitOptionalType(node);
83937 case 173 /* UnionType */:
83938 return emitUnionType(node);
83939 case 174 /* IntersectionType */:
83940 return emitIntersectionType(node);
83941 case 175 /* ConditionalType */:
83942 return emitConditionalType(node);
83943 case 176 /* InferType */:
83944 return emitInferType(node);
83945 case 177 /* ParenthesizedType */:
83946 return emitParenthesizedType(node);
83947 case 211 /* ExpressionWithTypeArguments */:
83948 return emitExpressionWithTypeArguments(node);
83949 case 178 /* ThisType */:
83950 return emitThisType();
83951 case 179 /* TypeOperator */:
83952 return emitTypeOperator(node);
83953 case 180 /* IndexedAccessType */:
83954 return emitIndexedAccessType(node);
83955 case 181 /* MappedType */:
83956 return emitMappedType(node);
83957 case 182 /* LiteralType */:
83958 return emitLiteralType(node);
83959 case 183 /* ImportType */:
83960 return emitImportTypeNode(node);
83961 case 289 /* JSDocAllType */:
83962 writePunctuation("*");
83963 return;
83964 case 290 /* JSDocUnknownType */:
83965 writePunctuation("?");
83966 return;
83967 case 291 /* JSDocNullableType */:
83968 return emitJSDocNullableType(node);
83969 case 292 /* JSDocNonNullableType */:
83970 return emitJSDocNonNullableType(node);
83971 case 293 /* JSDocOptionalType */:
83972 return emitJSDocOptionalType(node);
83973 case 172 /* RestType */:
83974 case 295 /* JSDocVariadicType */:
83975 return emitRestOrJSDocVariadicType(node);
83976 // Binding patterns
83977 case 184 /* ObjectBindingPattern */:
83978 return emitObjectBindingPattern(node);
83979 case 185 /* ArrayBindingPattern */:
83980 return emitArrayBindingPattern(node);
83981 case 186 /* BindingElement */:
83982 return emitBindingElement(node);
83983 // Misc
83984 case 216 /* TemplateSpan */:
83985 return emitTemplateSpan(node);
83986 case 217 /* SemicolonClassElement */:
83987 return emitSemicolonClassElement();
83988 // Statements
83989 case 218 /* Block */:
83990 return emitBlock(node);
83991 case 219 /* VariableStatement */:
83992 return emitVariableStatement(node);
83993 case 220 /* EmptyStatement */:
83994 return emitEmptyStatement(/*isEmbeddedStatement*/ false);
83995 case 221 /* ExpressionStatement */:
83996 return emitExpressionStatement(node);
83997 case 222 /* IfStatement */:
83998 return emitIfStatement(node);
83999 case 223 /* DoStatement */:
84000 return emitDoStatement(node);
84001 case 224 /* WhileStatement */:
84002 return emitWhileStatement(node);
84003 case 225 /* ForStatement */:
84004 return emitForStatement(node);
84005 case 226 /* ForInStatement */:
84006 return emitForInStatement(node);
84007 case 227 /* ForOfStatement */:
84008 return emitForOfStatement(node);
84009 case 228 /* ContinueStatement */:
84010 return emitContinueStatement(node);
84011 case 229 /* BreakStatement */:
84012 return emitBreakStatement(node);
84013 case 230 /* ReturnStatement */:
84014 return emitReturnStatement(node);
84015 case 231 /* WithStatement */:
84016 return emitWithStatement(node);
84017 case 232 /* SwitchStatement */:
84018 return emitSwitchStatement(node);
84019 case 233 /* LabeledStatement */:
84020 return emitLabeledStatement(node);
84021 case 234 /* ThrowStatement */:
84022 return emitThrowStatement(node);
84023 case 235 /* TryStatement */:
84024 return emitTryStatement(node);
84025 case 236 /* DebuggerStatement */:
84026 return emitDebuggerStatement(node);
84027 // Declarations
84028 case 237 /* VariableDeclaration */:
84029 return emitVariableDeclaration(node);
84030 case 238 /* VariableDeclarationList */:
84031 return emitVariableDeclarationList(node);
84032 case 239 /* FunctionDeclaration */:
84033 return emitFunctionDeclaration(node);
84034 case 240 /* ClassDeclaration */:
84035 return emitClassDeclaration(node);
84036 case 241 /* InterfaceDeclaration */:
84037 return emitInterfaceDeclaration(node);
84038 case 242 /* TypeAliasDeclaration */:
84039 return emitTypeAliasDeclaration(node);
84040 case 243 /* EnumDeclaration */:
84041 return emitEnumDeclaration(node);
84042 case 244 /* ModuleDeclaration */:
84043 return emitModuleDeclaration(node);
84044 case 245 /* ModuleBlock */:
84045 return emitModuleBlock(node);
84046 case 246 /* CaseBlock */:
84047 return emitCaseBlock(node);
84048 case 247 /* NamespaceExportDeclaration */:
84049 return emitNamespaceExportDeclaration(node);
84050 case 248 /* ImportEqualsDeclaration */:
84051 return emitImportEqualsDeclaration(node);
84052 case 249 /* ImportDeclaration */:
84053 return emitImportDeclaration(node);
84054 case 250 /* ImportClause */:
84055 return emitImportClause(node);
84056 case 251 /* NamespaceImport */:
84057 return emitNamespaceImport(node);
84058 case 252 /* NamedImports */:
84059 return emitNamedImports(node);
84060 case 253 /* ImportSpecifier */:
84061 return emitImportSpecifier(node);
84062 case 254 /* ExportAssignment */:
84063 return emitExportAssignment(node);
84064 case 255 /* ExportDeclaration */:
84065 return emitExportDeclaration(node);
84066 case 256 /* NamedExports */:
84067 return emitNamedExports(node);
84068 case 257 /* ExportSpecifier */:
84069 return emitExportSpecifier(node);
84070 case 258 /* MissingDeclaration */:
84071 return;
84072 // Module references
84073 case 259 /* ExternalModuleReference */:
84074 return emitExternalModuleReference(node);
84075 // JSX (non-expression)
84076 case 11 /* JsxText */:
84077 return emitJsxText(node);
84078 case 262 /* JsxOpeningElement */:
84079 case 265 /* JsxOpeningFragment */:
84080 return emitJsxOpeningElementOrFragment(node);
84081 case 263 /* JsxClosingElement */:
84082 case 266 /* JsxClosingFragment */:
84083 return emitJsxClosingElementOrFragment(node);
84084 case 267 /* JsxAttribute */:
84085 return emitJsxAttribute(node);
84086 case 268 /* JsxAttributes */:
84087 return emitJsxAttributes(node);
84088 case 269 /* JsxSpreadAttribute */:
84089 return emitJsxSpreadAttribute(node);
84090 case 270 /* JsxExpression */:
84091 return emitJsxExpression(node);
84092 // Clauses
84093 case 271 /* CaseClause */:
84094 return emitCaseClause(node);
84095 case 272 /* DefaultClause */:
84096 return emitDefaultClause(node);
84097 case 273 /* HeritageClause */:
84098 return emitHeritageClause(node);
84099 case 274 /* CatchClause */:
84100 return emitCatchClause(node);
84101 // Property assignments
84102 case 275 /* PropertyAssignment */:
84103 return emitPropertyAssignment(node);
84104 case 276 /* ShorthandPropertyAssignment */:
84105 return emitShorthandPropertyAssignment(node);
84106 case 277 /* SpreadAssignment */:
84107 return emitSpreadAssignment(node);
84108 // Enum
84109 case 278 /* EnumMember */:
84110 return emitEnumMember(node);
84111 // JSDoc nodes (only used in codefixes currently)
84112 case 304 /* JSDocParameterTag */:
84113 case 310 /* JSDocPropertyTag */:
84114 return emitJSDocPropertyLikeTag(node);
84115 case 305 /* JSDocReturnTag */:
84116 case 307 /* JSDocTypeTag */:
84117 case 306 /* JSDocThisTag */:
84118 case 303 /* JSDocEnumTag */:
84119 return emitJSDocSimpleTypedTag(node);
84120 case 300 /* JSDocAugmentsTag */:
84121 return emitJSDocAugmentsTag(node);
84122 case 308 /* JSDocTemplateTag */:
84123 return emitJSDocTemplateTag(node);
84124 case 309 /* JSDocTypedefTag */:
84125 return emitJSDocTypedefTag(node);
84126 case 302 /* JSDocCallbackTag */:
84127 return emitJSDocCallbackTag(node);
84128 case 298 /* JSDocSignature */:
84129 return emitJSDocSignature(node);
84130 case 297 /* JSDocTypeLiteral */:
84131 return emitJSDocTypeLiteral(node);
84132 case 301 /* JSDocClassTag */:
84133 case 299 /* JSDocTag */:
84134 return emitJSDocSimpleTag(node);
84135 case 296 /* JSDocComment */:
84136 return emitJSDoc(node);
84137 // Transformation nodes (ignored)
84138 }
84139 if (ts.isExpression(node)) {
84140 hint = 1 /* Expression */;
84141 if (substituteNode !== ts.noEmitSubstitution) {
84142 node = substituteNode(hint, node);
84143 }
84144 }
84145 else if (ts.isToken(node)) {
84146 return writeTokenNode(node, writePunctuation);
84147 }
84148 }
84149 if (hint === 1 /* Expression */) {
84150 switch (node.kind) {
84151 // Literals
84152 case 8 /* NumericLiteral */:
84153 case 9 /* BigIntLiteral */:
84154 return emitNumericOrBigIntLiteral(node);
84155 case 10 /* StringLiteral */:
84156 case 13 /* RegularExpressionLiteral */:
84157 case 14 /* NoSubstitutionTemplateLiteral */:
84158 return emitLiteral(node);
84159 // Identifiers
84160 case 72 /* Identifier */:
84161 return emitIdentifier(node);
84162 // Reserved words
84163 case 87 /* FalseKeyword */:
84164 case 96 /* NullKeyword */:
84165 case 98 /* SuperKeyword */:
84166 case 102 /* TrueKeyword */:
84167 case 100 /* ThisKeyword */:
84168 case 92 /* ImportKeyword */:
84169 writeTokenNode(node, writeKeyword);
84170 return;
84171 // Expressions
84172 case 187 /* ArrayLiteralExpression */:
84173 return emitArrayLiteralExpression(node);
84174 case 188 /* ObjectLiteralExpression */:
84175 return emitObjectLiteralExpression(node);
84176 case 189 /* PropertyAccessExpression */:
84177 return emitPropertyAccessExpression(node);
84178 case 190 /* ElementAccessExpression */:
84179 return emitElementAccessExpression(node);
84180 case 191 /* CallExpression */:
84181 return emitCallExpression(node);
84182 case 192 /* NewExpression */:
84183 return emitNewExpression(node);
84184 case 193 /* TaggedTemplateExpression */:
84185 return emitTaggedTemplateExpression(node);
84186 case 194 /* TypeAssertionExpression */:
84187 return emitTypeAssertionExpression(node);
84188 case 195 /* ParenthesizedExpression */:
84189 return emitParenthesizedExpression(node);
84190 case 196 /* FunctionExpression */:
84191 return emitFunctionExpression(node);
84192 case 197 /* ArrowFunction */:
84193 return emitArrowFunction(node);
84194 case 198 /* DeleteExpression */:
84195 return emitDeleteExpression(node);
84196 case 199 /* TypeOfExpression */:
84197 return emitTypeOfExpression(node);
84198 case 200 /* VoidExpression */:
84199 return emitVoidExpression(node);
84200 case 201 /* AwaitExpression */:
84201 return emitAwaitExpression(node);
84202 case 202 /* PrefixUnaryExpression */:
84203 return emitPrefixUnaryExpression(node);
84204 case 203 /* PostfixUnaryExpression */:
84205 return emitPostfixUnaryExpression(node);
84206 case 204 /* BinaryExpression */:
84207 return emitBinaryExpression(node);
84208 case 205 /* ConditionalExpression */:
84209 return emitConditionalExpression(node);
84210 case 206 /* TemplateExpression */:
84211 return emitTemplateExpression(node);
84212 case 207 /* YieldExpression */:
84213 return emitYieldExpression(node);
84214 case 208 /* SpreadElement */:
84215 return emitSpreadExpression(node);
84216 case 209 /* ClassExpression */:
84217 return emitClassExpression(node);
84218 case 210 /* OmittedExpression */:
84219 return;
84220 case 212 /* AsExpression */:
84221 return emitAsExpression(node);
84222 case 213 /* NonNullExpression */:
84223 return emitNonNullExpression(node);
84224 case 214 /* MetaProperty */:
84225 return emitMetaProperty(node);
84226 // JSX
84227 case 260 /* JsxElement */:
84228 return emitJsxElement(node);
84229 case 261 /* JsxSelfClosingElement */:
84230 return emitJsxSelfClosingElement(node);
84231 case 264 /* JsxFragment */:
84232 return emitJsxFragment(node);
84233 // Transformation nodes
84234 case 313 /* PartiallyEmittedExpression */:
84235 return emitPartiallyEmittedExpression(node);
84236 case 314 /* CommaListExpression */:
84237 return emitCommaList(node);
84238 }
84239 }
84240 }
84241 function emitMappedTypeParameter(node) {
84242 emit(node.name);
84243 writeSpace();
84244 writeKeyword("in");
84245 writeSpace();
84246 emit(node.constraint);
84247 }
84248 function pipelineEmitWithSubstitution(hint, node) {
84249 var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
84250 pipelinePhase(hint, substituteNode(hint, node));
84251 }
84252 function getHelpersFromBundledSourceFiles(bundle) {
84253 var result;
84254 if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
84255 return undefined;
84256 }
84257 var bundledHelpers = ts.createMap();
84258 for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
84259 var sourceFile = _b[_a];
84260 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
84261 var helpers = getSortedEmitHelpers(sourceFile);
84262 if (!helpers)
84263 continue;
84264 for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
84265 var helper = helpers_3[_c];
84266 if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
84267 bundledHelpers.set(helper.name, true);
84268 (result || (result = [])).push(helper.name);
84269 }
84270 }
84271 }
84272 return result;
84273 }
84274 function emitHelpers(node) {
84275 var helpersEmitted = false;
84276 var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
84277 if (bundle && moduleKind === ts.ModuleKind.None) {
84278 return;
84279 }
84280 var numPrepends = bundle ? bundle.prepends.length : 0;
84281 var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
84282 for (var i = 0; i < numNodes; i++) {
84283 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
84284 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
84285 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
84286 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
84287 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
84288 if (helpers) {
84289 for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
84290 var helper = helpers_4[_a];
84291 if (!helper.scoped) {
84292 // Skip the helper if it can be skipped and the noEmitHelpers compiler
84293 // option is set, or if it can be imported and the importHelpers compiler
84294 // option is set.
84295 if (shouldSkip)
84296 continue;
84297 // Skip the helper if it can be bundled but hasn't already been emitted and we
84298 // are emitting a bundled module.
84299 if (shouldBundle) {
84300 if (bundledHelpers.get(helper.name)) {
84301 continue;
84302 }
84303 bundledHelpers.set(helper.name, true);
84304 }
84305 }
84306 else if (bundle) {
84307 // Skip the helper if it is scoped and we are emitting bundled helpers
84308 continue;
84309 }
84310 var pos = getTextPosWithWriteLine();
84311 if (typeof helper.text === "string") {
84312 writeLines(helper.text);
84313 }
84314 else {
84315 writeLines(helper.text(makeFileLevelOptimisticUniqueName));
84316 }
84317 if (bundleFileInfo)
84318 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
84319 helpersEmitted = true;
84320 }
84321 }
84322 }
84323 return helpersEmitted;
84324 }
84325 function getSortedEmitHelpers(node) {
84326 var helpers = ts.getEmitHelpers(node);
84327 return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
84328 }
84329 //
84330 // Literals/Pseudo-literals
84331 //
84332 // SyntaxKind.NumericLiteral
84333 // SyntaxKind.BigIntLiteral
84334 function emitNumericOrBigIntLiteral(node) {
84335 emitLiteral(node);
84336 }
84337 // SyntaxKind.StringLiteral
84338 // SyntaxKind.RegularExpressionLiteral
84339 // SyntaxKind.NoSubstitutionTemplateLiteral
84340 // SyntaxKind.TemplateHead
84341 // SyntaxKind.TemplateMiddle
84342 // SyntaxKind.TemplateTail
84343 function emitLiteral(node) {
84344 var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape);
84345 if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
84346 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
84347 writeLiteral(text);
84348 }
84349 else {
84350 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
84351 writeStringLiteral(text);
84352 }
84353 }
84354 // SyntaxKind.UnparsedSource
84355 // SyntaxKind.UnparsedPrepend
84356 function emitUnparsedSourceOrPrepend(unparsed) {
84357 for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
84358 var text = _b[_a];
84359 writeLine();
84360 emit(text);
84361 }
84362 }
84363 // SyntaxKind.UnparsedPrologue
84364 // SyntaxKind.UnparsedText
84365 // SyntaxKind.UnparsedInternal
84366 // SyntaxKind.UnparsedSyntheticReference
84367 function writeUnparsedNode(unparsed) {
84368 writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
84369 }
84370 // SyntaxKind.UnparsedText
84371 // SyntaxKind.UnparsedInternal
84372 function emitUnparsedTextLike(unparsed) {
84373 var pos = getTextPosWithWriteLine();
84374 writeUnparsedNode(unparsed);
84375 if (bundleFileInfo) {
84376 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
84377 "text" /* Text */ :
84378 "internal" /* Internal */);
84379 }
84380 }
84381 // SyntaxKind.UnparsedSyntheticReference
84382 function emitUnparsedSyntheticReference(unparsed) {
84383 var pos = getTextPosWithWriteLine();
84384 writeUnparsedNode(unparsed);
84385 if (bundleFileInfo) {
84386 var section = ts.clone(unparsed.section);
84387 section.pos = pos;
84388 section.end = writer.getTextPos();
84389 bundleFileInfo.sections.push(section);
84390 }
84391 }
84392 //
84393 // Identifiers
84394 //
84395 function emitIdentifier(node) {
84396 var writeText = node.symbol ? writeSymbol : write;
84397 writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
84398 emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
84399 }
84400 //
84401 // Names
84402 //
84403 function emitQualifiedName(node) {
84404 emitEntityName(node.left);
84405 writePunctuation(".");
84406 emit(node.right);
84407 }
84408 function emitEntityName(node) {
84409 if (node.kind === 72 /* Identifier */) {
84410 emitExpression(node);
84411 }
84412 else {
84413 emit(node);
84414 }
84415 }
84416 function emitComputedPropertyName(node) {
84417 writePunctuation("[");
84418 emitExpression(node.expression);
84419 writePunctuation("]");
84420 }
84421 //
84422 // Signature elements
84423 //
84424 function emitTypeParameter(node) {
84425 emit(node.name);
84426 if (node.constraint) {
84427 writeSpace();
84428 writeKeyword("extends");
84429 writeSpace();
84430 emit(node.constraint);
84431 }
84432 if (node.default) {
84433 writeSpace();
84434 writeOperator("=");
84435 writeSpace();
84436 emit(node.default);
84437 }
84438 }
84439 function emitParameter(node) {
84440 emitDecorators(node, node.decorators);
84441 emitModifiers(node, node.modifiers);
84442 emit(node.dotDotDotToken);
84443 emitNodeWithWriter(node.name, writeParameter);
84444 emit(node.questionToken);
84445 if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
84446 emit(node.type);
84447 }
84448 else {
84449 emitTypeAnnotation(node.type);
84450 }
84451 // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer.
84452 emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node);
84453 }
84454 function emitDecorator(decorator) {
84455 writePunctuation("@");
84456 emitExpression(decorator.expression);
84457 }
84458 //
84459 // Type members
84460 //
84461 function emitPropertySignature(node) {
84462 emitDecorators(node, node.decorators);
84463 emitModifiers(node, node.modifiers);
84464 emitNodeWithWriter(node.name, writeProperty);
84465 emit(node.questionToken);
84466 emitTypeAnnotation(node.type);
84467 writeTrailingSemicolon();
84468 }
84469 function emitPropertyDeclaration(node) {
84470 emitDecorators(node, node.decorators);
84471 emitModifiers(node, node.modifiers);
84472 emit(node.name);
84473 emit(node.questionToken);
84474 emit(node.exclamationToken);
84475 emitTypeAnnotation(node.type);
84476 emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
84477 writeTrailingSemicolon();
84478 }
84479 function emitMethodSignature(node) {
84480 pushNameGenerationScope(node);
84481 emitDecorators(node, node.decorators);
84482 emitModifiers(node, node.modifiers);
84483 emit(node.name);
84484 emit(node.questionToken);
84485 emitTypeParameters(node, node.typeParameters);
84486 emitParameters(node, node.parameters);
84487 emitTypeAnnotation(node.type);
84488 writeTrailingSemicolon();
84489 popNameGenerationScope(node);
84490 }
84491 function emitMethodDeclaration(node) {
84492 emitDecorators(node, node.decorators);
84493 emitModifiers(node, node.modifiers);
84494 emit(node.asteriskToken);
84495 emit(node.name);
84496 emit(node.questionToken);
84497 emitSignatureAndBody(node, emitSignatureHead);
84498 }
84499 function emitConstructor(node) {
84500 emitModifiers(node, node.modifiers);
84501 writeKeyword("constructor");
84502 emitSignatureAndBody(node, emitSignatureHead);
84503 }
84504 function emitAccessorDeclaration(node) {
84505 emitDecorators(node, node.decorators);
84506 emitModifiers(node, node.modifiers);
84507 writeKeyword(node.kind === 158 /* GetAccessor */ ? "get" : "set");
84508 writeSpace();
84509 emit(node.name);
84510 emitSignatureAndBody(node, emitSignatureHead);
84511 }
84512 function emitCallSignature(node) {
84513 pushNameGenerationScope(node);
84514 emitDecorators(node, node.decorators);
84515 emitModifiers(node, node.modifiers);
84516 emitTypeParameters(node, node.typeParameters);
84517 emitParameters(node, node.parameters);
84518 emitTypeAnnotation(node.type);
84519 writeTrailingSemicolon();
84520 popNameGenerationScope(node);
84521 }
84522 function emitConstructSignature(node) {
84523 pushNameGenerationScope(node);
84524 emitDecorators(node, node.decorators);
84525 emitModifiers(node, node.modifiers);
84526 writeKeyword("new");
84527 writeSpace();
84528 emitTypeParameters(node, node.typeParameters);
84529 emitParameters(node, node.parameters);
84530 emitTypeAnnotation(node.type);
84531 writeTrailingSemicolon();
84532 popNameGenerationScope(node);
84533 }
84534 function emitIndexSignature(node) {
84535 emitDecorators(node, node.decorators);
84536 emitModifiers(node, node.modifiers);
84537 emitParametersForIndexSignature(node, node.parameters);
84538 emitTypeAnnotation(node.type);
84539 writeTrailingSemicolon();
84540 }
84541 function emitSemicolonClassElement() {
84542 writeTrailingSemicolon();
84543 }
84544 //
84545 // Types
84546 //
84547 function emitTypePredicate(node) {
84548 emit(node.parameterName);
84549 writeSpace();
84550 writeKeyword("is");
84551 writeSpace();
84552 emit(node.type);
84553 }
84554 function emitTypeReference(node) {
84555 emit(node.typeName);
84556 emitTypeArguments(node, node.typeArguments);
84557 }
84558 function emitFunctionType(node) {
84559 pushNameGenerationScope(node);
84560 emitTypeParameters(node, node.typeParameters);
84561 emitParametersForArrow(node, node.parameters);
84562 writeSpace();
84563 writePunctuation("=>");
84564 writeSpace();
84565 emit(node.type);
84566 popNameGenerationScope(node);
84567 }
84568 function emitJSDocFunctionType(node) {
84569 writeKeyword("function");
84570 emitParameters(node, node.parameters);
84571 writePunctuation(":");
84572 emit(node.type);
84573 }
84574 function emitJSDocNullableType(node) {
84575 writePunctuation("?");
84576 emit(node.type);
84577 }
84578 function emitJSDocNonNullableType(node) {
84579 writePunctuation("!");
84580 emit(node.type);
84581 }
84582 function emitJSDocOptionalType(node) {
84583 emit(node.type);
84584 writePunctuation("=");
84585 }
84586 function emitConstructorType(node) {
84587 pushNameGenerationScope(node);
84588 writeKeyword("new");
84589 writeSpace();
84590 emitTypeParameters(node, node.typeParameters);
84591 emitParameters(node, node.parameters);
84592 writeSpace();
84593 writePunctuation("=>");
84594 writeSpace();
84595 emit(node.type);
84596 popNameGenerationScope(node);
84597 }
84598 function emitTypeQuery(node) {
84599 writeKeyword("typeof");
84600 writeSpace();
84601 emit(node.exprName);
84602 }
84603 function emitTypeLiteral(node) {
84604 writePunctuation("{");
84605 var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
84606 emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
84607 writePunctuation("}");
84608 }
84609 function emitArrayType(node) {
84610 emit(node.elementType);
84611 writePunctuation("[");
84612 writePunctuation("]");
84613 }
84614 function emitRestOrJSDocVariadicType(node) {
84615 writePunctuation("...");
84616 emit(node.type);
84617 }
84618 function emitTupleType(node) {
84619 writePunctuation("[");
84620 emitList(node, node.elementTypes, 528 /* TupleTypeElements */);
84621 writePunctuation("]");
84622 }
84623 function emitOptionalType(node) {
84624 emit(node.type);
84625 writePunctuation("?");
84626 }
84627 function emitUnionType(node) {
84628 emitList(node, node.types, 516 /* UnionTypeConstituents */);
84629 }
84630 function emitIntersectionType(node) {
84631 emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
84632 }
84633 function emitConditionalType(node) {
84634 emit(node.checkType);
84635 writeSpace();
84636 writeKeyword("extends");
84637 writeSpace();
84638 emit(node.extendsType);
84639 writeSpace();
84640 writePunctuation("?");
84641 writeSpace();
84642 emit(node.trueType);
84643 writeSpace();
84644 writePunctuation(":");
84645 writeSpace();
84646 emit(node.falseType);
84647 }
84648 function emitInferType(node) {
84649 writeKeyword("infer");
84650 writeSpace();
84651 emit(node.typeParameter);
84652 }
84653 function emitParenthesizedType(node) {
84654 writePunctuation("(");
84655 emit(node.type);
84656 writePunctuation(")");
84657 }
84658 function emitThisType() {
84659 writeKeyword("this");
84660 }
84661 function emitTypeOperator(node) {
84662 writeTokenText(node.operator, writeKeyword);
84663 writeSpace();
84664 emit(node.type);
84665 }
84666 function emitIndexedAccessType(node) {
84667 emit(node.objectType);
84668 writePunctuation("[");
84669 emit(node.indexType);
84670 writePunctuation("]");
84671 }
84672 function emitMappedType(node) {
84673 var emitFlags = ts.getEmitFlags(node);
84674 writePunctuation("{");
84675 if (emitFlags & 1 /* SingleLine */) {
84676 writeSpace();
84677 }
84678 else {
84679 writeLine();
84680 increaseIndent();
84681 }
84682 if (node.readonlyToken) {
84683 emit(node.readonlyToken);
84684 if (node.readonlyToken.kind !== 133 /* ReadonlyKeyword */) {
84685 writeKeyword("readonly");
84686 }
84687 writeSpace();
84688 }
84689 writePunctuation("[");
84690 var pipelinePhase = getPipelinePhase(0 /* Notification */, node.typeParameter);
84691 pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter);
84692 writePunctuation("]");
84693 if (node.questionToken) {
84694 emit(node.questionToken);
84695 if (node.questionToken.kind !== 56 /* QuestionToken */) {
84696 writePunctuation("?");
84697 }
84698 }
84699 writePunctuation(":");
84700 writeSpace();
84701 emit(node.type);
84702 writeTrailingSemicolon();
84703 if (emitFlags & 1 /* SingleLine */) {
84704 writeSpace();
84705 }
84706 else {
84707 writeLine();
84708 decreaseIndent();
84709 }
84710 writePunctuation("}");
84711 }
84712 function emitLiteralType(node) {
84713 emitExpression(node.literal);
84714 }
84715 function emitImportTypeNode(node) {
84716 if (node.isTypeOf) {
84717 writeKeyword("typeof");
84718 writeSpace();
84719 }
84720 writeKeyword("import");
84721 writePunctuation("(");
84722 emit(node.argument);
84723 writePunctuation(")");
84724 if (node.qualifier) {
84725 writePunctuation(".");
84726 emit(node.qualifier);
84727 }
84728 emitTypeArguments(node, node.typeArguments);
84729 }
84730 //
84731 // Binding patterns
84732 //
84733 function emitObjectBindingPattern(node) {
84734 writePunctuation("{");
84735 emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
84736 writePunctuation("}");
84737 }
84738 function emitArrayBindingPattern(node) {
84739 writePunctuation("[");
84740 emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
84741 writePunctuation("]");
84742 }
84743 function emitBindingElement(node) {
84744 emit(node.dotDotDotToken);
84745 if (node.propertyName) {
84746 emit(node.propertyName);
84747 writePunctuation(":");
84748 writeSpace();
84749 }
84750 emit(node.name);
84751 emitInitializer(node.initializer, node.name.end, node);
84752 }
84753 //
84754 // Expressions
84755 //
84756 function emitArrayLiteralExpression(node) {
84757 var elements = node.elements;
84758 var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
84759 emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
84760 }
84761 function emitObjectLiteralExpression(node) {
84762 ts.forEach(node.properties, generateMemberNames);
84763 var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
84764 if (indentedFlag) {
84765 increaseIndent();
84766 }
84767 var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
84768 var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
84769 emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
84770 if (indentedFlag) {
84771 decreaseIndent();
84772 }
84773 }
84774 function emitPropertyAccessExpression(node) {
84775 var indentBeforeDot = false;
84776 var indentAfterDot = false;
84777 var dotRangeFirstCommentStart = ts.skipTrivia(currentSourceFile.text, node.expression.end,
84778 /*stopAfterLineBreak*/ false,
84779 /*stopAtComments*/ true);
84780 var dotRangeStart = ts.skipTrivia(currentSourceFile.text, dotRangeFirstCommentStart);
84781 var dotRangeEnd = dotRangeStart + 1;
84782 if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) {
84783 var dotToken = ts.createToken(24 /* DotToken */);
84784 dotToken.pos = node.expression.end;
84785 dotToken.end = dotRangeEnd;
84786 indentBeforeDot = needsIndentation(node, node.expression, dotToken);
84787 indentAfterDot = needsIndentation(node, dotToken, node.name);
84788 }
84789 emitExpression(node.expression);
84790 increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false);
84791 var dotHasCommentTrivia = dotRangeFirstCommentStart !== dotRangeStart;
84792 var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression, dotHasCommentTrivia);
84793 if (shouldEmitDotDot) {
84794 writePunctuation(".");
84795 }
84796 emitTokenWithComment(24 /* DotToken */, node.expression.end, writePunctuation, node);
84797 increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false);
84798 emit(node.name);
84799 decreaseIndentIf(indentBeforeDot, indentAfterDot);
84800 }
84801 // 1..toString is a valid property access, emit a dot after the literal
84802 // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
84803 function needsDotDotForPropertyAccess(expression, dotHasTrivia) {
84804 expression = ts.skipPartiallyEmittedExpressions(expression);
84805 if (ts.isNumericLiteral(expression)) {
84806 // check if numeric literal is a decimal literal that was originally written with a dot
84807 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true);
84808 // If he number will be printed verbatim and it doesn't already contain a dot, add one
84809 // if the expression doesn't have any comments that will be emitted.
84810 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)) &&
84811 (!dotHasTrivia || printerOptions.removeComments);
84812 }
84813 else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) {
84814 // check if constant enum value is integer
84815 var constantValue = ts.getConstantValue(expression);
84816 // isFinite handles cases when constantValue is undefined
84817 return typeof constantValue === "number" && isFinite(constantValue)
84818 && Math.floor(constantValue) === constantValue
84819 && printerOptions.removeComments;
84820 }
84821 }
84822 function emitElementAccessExpression(node) {
84823 emitExpression(node.expression);
84824 emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
84825 emitExpression(node.argumentExpression);
84826 emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
84827 }
84828 function emitCallExpression(node) {
84829 emitExpression(node.expression);
84830 emitTypeArguments(node, node.typeArguments);
84831 emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
84832 }
84833 function emitNewExpression(node) {
84834 emitTokenWithComment(95 /* NewKeyword */, node.pos, writeKeyword, node);
84835 writeSpace();
84836 emitExpression(node.expression);
84837 emitTypeArguments(node, node.typeArguments);
84838 emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
84839 }
84840 function emitTaggedTemplateExpression(node) {
84841 emitExpression(node.tag);
84842 emitTypeArguments(node, node.typeArguments);
84843 writeSpace();
84844 emitExpression(node.template);
84845 }
84846 function emitTypeAssertionExpression(node) {
84847 writePunctuation("<");
84848 emit(node.type);
84849 writePunctuation(">");
84850 emitExpression(node.expression);
84851 }
84852 function emitParenthesizedExpression(node) {
84853 var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
84854 emitExpression(node.expression);
84855 emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
84856 }
84857 function emitFunctionExpression(node) {
84858 generateNameIfNeeded(node.name);
84859 emitFunctionDeclarationOrExpression(node);
84860 }
84861 function emitArrowFunction(node) {
84862 emitDecorators(node, node.decorators);
84863 emitModifiers(node, node.modifiers);
84864 emitSignatureAndBody(node, emitArrowFunctionHead);
84865 }
84866 function emitArrowFunctionHead(node) {
84867 emitTypeParameters(node, node.typeParameters);
84868 emitParametersForArrow(node, node.parameters);
84869 emitTypeAnnotation(node.type);
84870 writeSpace();
84871 emit(node.equalsGreaterThanToken);
84872 }
84873 function emitDeleteExpression(node) {
84874 emitTokenWithComment(81 /* DeleteKeyword */, node.pos, writeKeyword, node);
84875 writeSpace();
84876 emitExpression(node.expression);
84877 }
84878 function emitTypeOfExpression(node) {
84879 emitTokenWithComment(104 /* TypeOfKeyword */, node.pos, writeKeyword, node);
84880 writeSpace();
84881 emitExpression(node.expression);
84882 }
84883 function emitVoidExpression(node) {
84884 emitTokenWithComment(106 /* VoidKeyword */, node.pos, writeKeyword, node);
84885 writeSpace();
84886 emitExpression(node.expression);
84887 }
84888 function emitAwaitExpression(node) {
84889 emitTokenWithComment(122 /* AwaitKeyword */, node.pos, writeKeyword, node);
84890 writeSpace();
84891 emitExpression(node.expression);
84892 }
84893 function emitPrefixUnaryExpression(node) {
84894 writeTokenText(node.operator, writeOperator);
84895 if (shouldEmitWhitespaceBeforeOperand(node)) {
84896 writeSpace();
84897 }
84898 emitExpression(node.operand);
84899 }
84900 function shouldEmitWhitespaceBeforeOperand(node) {
84901 // In some cases, we need to emit a space between the operator and the operand. One obvious case
84902 // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
84903 // and minus expressions in certain cases. Specifically, consider the following two cases (parens
84904 // are just for clarity of exposition, and not part of the source code):
84905 //
84906 // (+(+1))
84907 // (+(++1))
84908 //
84909 // We need to emit a space in both cases. In the first case, the absence of a space will make
84910 // the resulting expression a prefix increment operation. And in the second, it will make the resulting
84911 // expression a prefix increment whose operand is a plus expression - (++(+x))
84912 // The same is true of minus of course.
84913 var operand = node.operand;
84914 return operand.kind === 202 /* PrefixUnaryExpression */
84915 && ((node.operator === 38 /* PlusToken */ && (operand.operator === 38 /* PlusToken */ || operand.operator === 44 /* PlusPlusToken */))
84916 || (node.operator === 39 /* MinusToken */ && (operand.operator === 39 /* MinusToken */ || operand.operator === 45 /* MinusMinusToken */)));
84917 }
84918 function emitPostfixUnaryExpression(node) {
84919 emitExpression(node.operand);
84920 writeTokenText(node.operator, writeOperator);
84921 }
84922 function emitBinaryExpression(node) {
84923 var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
84924 var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken);
84925 var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right);
84926 emitExpression(node.left);
84927 increaseIndentIf(indentBeforeOperator, isCommaOperator);
84928 emitLeadingCommentsOfPosition(node.operatorToken.pos);
84929 writeTokenNode(node.operatorToken, node.operatorToken.kind === 93 /* InKeyword */ ? writeKeyword : writeOperator);
84930 emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
84931 increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true);
84932 emitExpression(node.right);
84933 decreaseIndentIf(indentBeforeOperator, indentAfterOperator);
84934 }
84935 function emitConditionalExpression(node) {
84936 var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken);
84937 var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue);
84938 var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken);
84939 var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse);
84940 emitExpression(node.condition);
84941 increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
84942 emit(node.questionToken);
84943 increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
84944 emitExpression(node.whenTrue);
84945 decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion);
84946 increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true);
84947 emit(node.colonToken);
84948 increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true);
84949 emitExpression(node.whenFalse);
84950 decreaseIndentIf(indentBeforeColon, indentAfterColon);
84951 }
84952 function emitTemplateExpression(node) {
84953 emit(node.head);
84954 emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
84955 }
84956 function emitYieldExpression(node) {
84957 emitTokenWithComment(117 /* YieldKeyword */, node.pos, writeKeyword, node);
84958 emit(node.asteriskToken);
84959 emitExpressionWithLeadingSpace(node.expression);
84960 }
84961 function emitSpreadExpression(node) {
84962 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
84963 emitExpression(node.expression);
84964 }
84965 function emitClassExpression(node) {
84966 generateNameIfNeeded(node.name);
84967 emitClassDeclarationOrExpression(node);
84968 }
84969 function emitExpressionWithTypeArguments(node) {
84970 emitExpression(node.expression);
84971 emitTypeArguments(node, node.typeArguments);
84972 }
84973 function emitAsExpression(node) {
84974 emitExpression(node.expression);
84975 if (node.type) {
84976 writeSpace();
84977 writeKeyword("as");
84978 writeSpace();
84979 emit(node.type);
84980 }
84981 }
84982 function emitNonNullExpression(node) {
84983 emitExpression(node.expression);
84984 writeOperator("!");
84985 }
84986 function emitMetaProperty(node) {
84987 writeToken(node.keywordToken, node.pos, writePunctuation);
84988 writePunctuation(".");
84989 emit(node.name);
84990 }
84991 //
84992 // Misc
84993 //
84994 function emitTemplateSpan(node) {
84995 emitExpression(node.expression);
84996 emit(node.literal);
84997 }
84998 //
84999 // Statements
85000 //
85001 function emitBlock(node) {
85002 emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
85003 }
85004 function emitBlockStatements(node, forceSingleLine) {
85005 emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
85006 var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
85007 emitList(node, node.statements, format);
85008 emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
85009 }
85010 function emitVariableStatement(node) {
85011 emitModifiers(node, node.modifiers);
85012 emit(node.declarationList);
85013 writeTrailingSemicolon();
85014 }
85015 function emitEmptyStatement(isEmbeddedStatement) {
85016 // While most trailing semicolons are possibly insignificant, an embedded "empty"
85017 // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
85018 if (isEmbeddedStatement) {
85019 writePunctuation(";");
85020 }
85021 else {
85022 writeTrailingSemicolon();
85023 }
85024 }
85025 function emitExpressionStatement(node) {
85026 emitExpression(node.expression);
85027 // Emit semicolon in non json files
85028 // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
85029 if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
85030 writeTrailingSemicolon();
85031 }
85032 }
85033 function emitIfStatement(node) {
85034 var openParenPos = emitTokenWithComment(91 /* IfKeyword */, node.pos, writeKeyword, node);
85035 writeSpace();
85036 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
85037 emitExpression(node.expression);
85038 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
85039 emitEmbeddedStatement(node, node.thenStatement);
85040 if (node.elseStatement) {
85041 writeLineOrSpace(node);
85042 emitTokenWithComment(83 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
85043 if (node.elseStatement.kind === 222 /* IfStatement */) {
85044 writeSpace();
85045 emit(node.elseStatement);
85046 }
85047 else {
85048 emitEmbeddedStatement(node, node.elseStatement);
85049 }
85050 }
85051 }
85052 function emitWhileClause(node, startPos) {
85053 var openParenPos = emitTokenWithComment(107 /* WhileKeyword */, startPos, writeKeyword, node);
85054 writeSpace();
85055 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
85056 emitExpression(node.expression);
85057 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
85058 }
85059 function emitDoStatement(node) {
85060 emitTokenWithComment(82 /* DoKeyword */, node.pos, writeKeyword, node);
85061 emitEmbeddedStatement(node, node.statement);
85062 if (ts.isBlock(node.statement)) {
85063 writeSpace();
85064 }
85065 else {
85066 writeLineOrSpace(node);
85067 }
85068 emitWhileClause(node, node.statement.end);
85069 writePunctuation(";");
85070 }
85071 function emitWhileStatement(node) {
85072 emitWhileClause(node, node.pos);
85073 emitEmbeddedStatement(node, node.statement);
85074 }
85075 function emitForStatement(node) {
85076 var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node);
85077 writeSpace();
85078 var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
85079 emitForBinding(node.initializer);
85080 pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
85081 emitExpressionWithLeadingSpace(node.condition);
85082 pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
85083 emitExpressionWithLeadingSpace(node.incrementor);
85084 emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
85085 emitEmbeddedStatement(node, node.statement);
85086 }
85087 function emitForInStatement(node) {
85088 var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node);
85089 writeSpace();
85090 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
85091 emitForBinding(node.initializer);
85092 writeSpace();
85093 emitTokenWithComment(93 /* InKeyword */, node.initializer.end, writeKeyword, node);
85094 writeSpace();
85095 emitExpression(node.expression);
85096 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
85097 emitEmbeddedStatement(node, node.statement);
85098 }
85099 function emitForOfStatement(node) {
85100 var openParenPos = emitTokenWithComment(89 /* ForKeyword */, node.pos, writeKeyword, node);
85101 writeSpace();
85102 emitWithTrailingSpace(node.awaitModifier);
85103 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
85104 emitForBinding(node.initializer);
85105 writeSpace();
85106 emitTokenWithComment(147 /* OfKeyword */, node.initializer.end, writeKeyword, node);
85107 writeSpace();
85108 emitExpression(node.expression);
85109 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
85110 emitEmbeddedStatement(node, node.statement);
85111 }
85112 function emitForBinding(node) {
85113 if (node !== undefined) {
85114 if (node.kind === 238 /* VariableDeclarationList */) {
85115 emit(node);
85116 }
85117 else {
85118 emitExpression(node);
85119 }
85120 }
85121 }
85122 function emitContinueStatement(node) {
85123 emitTokenWithComment(78 /* ContinueKeyword */, node.pos, writeKeyword, node);
85124 emitWithLeadingSpace(node.label);
85125 writeTrailingSemicolon();
85126 }
85127 function emitBreakStatement(node) {
85128 emitTokenWithComment(73 /* BreakKeyword */, node.pos, writeKeyword, node);
85129 emitWithLeadingSpace(node.label);
85130 writeTrailingSemicolon();
85131 }
85132 function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
85133 var node = ts.getParseTreeNode(contextNode);
85134 var isSimilarNode = node && node.kind === contextNode.kind;
85135 var startPos = pos;
85136 if (isSimilarNode) {
85137 pos = ts.skipTrivia(currentSourceFile.text, pos);
85138 }
85139 if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
85140 var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
85141 if (needsIndent) {
85142 increaseIndent();
85143 }
85144 emitLeadingCommentsOfPosition(startPos);
85145 if (needsIndent) {
85146 decreaseIndent();
85147 }
85148 }
85149 pos = writeTokenText(token, writer, pos);
85150 if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
85151 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
85152 }
85153 return pos;
85154 }
85155 function emitReturnStatement(node) {
85156 emitTokenWithComment(97 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
85157 emitExpressionWithLeadingSpace(node.expression);
85158 writeTrailingSemicolon();
85159 }
85160 function emitWithStatement(node) {
85161 var openParenPos = emitTokenWithComment(108 /* WithKeyword */, node.pos, writeKeyword, node);
85162 writeSpace();
85163 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
85164 emitExpression(node.expression);
85165 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
85166 emitEmbeddedStatement(node, node.statement);
85167 }
85168 function emitSwitchStatement(node) {
85169 var openParenPos = emitTokenWithComment(99 /* SwitchKeyword */, node.pos, writeKeyword, node);
85170 writeSpace();
85171 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
85172 emitExpression(node.expression);
85173 emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
85174 writeSpace();
85175 emit(node.caseBlock);
85176 }
85177 function emitLabeledStatement(node) {
85178 emit(node.label);
85179 emitTokenWithComment(57 /* ColonToken */, node.label.end, writePunctuation, node);
85180 writeSpace();
85181 emit(node.statement);
85182 }
85183 function emitThrowStatement(node) {
85184 emitTokenWithComment(101 /* ThrowKeyword */, node.pos, writeKeyword, node);
85185 emitExpressionWithLeadingSpace(node.expression);
85186 writeTrailingSemicolon();
85187 }
85188 function emitTryStatement(node) {
85189 emitTokenWithComment(103 /* TryKeyword */, node.pos, writeKeyword, node);
85190 writeSpace();
85191 emit(node.tryBlock);
85192 if (node.catchClause) {
85193 writeLineOrSpace(node);
85194 emit(node.catchClause);
85195 }
85196 if (node.finallyBlock) {
85197 writeLineOrSpace(node);
85198 emitTokenWithComment(88 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
85199 writeSpace();
85200 emit(node.finallyBlock);
85201 }
85202 }
85203 function emitDebuggerStatement(node) {
85204 writeToken(79 /* DebuggerKeyword */, node.pos, writeKeyword);
85205 writeTrailingSemicolon();
85206 }
85207 //
85208 // Declarations
85209 //
85210 function emitVariableDeclaration(node) {
85211 emit(node.name);
85212 emitTypeAnnotation(node.type);
85213 emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
85214 }
85215 function emitVariableDeclarationList(node) {
85216 writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
85217 writeSpace();
85218 emitList(node, node.declarations, 528 /* VariableDeclarationList */);
85219 }
85220 function emitFunctionDeclaration(node) {
85221 emitFunctionDeclarationOrExpression(node);
85222 }
85223 function emitFunctionDeclarationOrExpression(node) {
85224 emitDecorators(node, node.decorators);
85225 emitModifiers(node, node.modifiers);
85226 writeKeyword("function");
85227 emit(node.asteriskToken);
85228 writeSpace();
85229 emitIdentifierName(node.name); // TODO: GH#18217
85230 emitSignatureAndBody(node, emitSignatureHead);
85231 }
85232 function emitBlockCallback(_hint, body) {
85233 emitBlockFunctionBody(body);
85234 }
85235 function emitSignatureAndBody(node, emitSignatureHead) {
85236 var body = node.body;
85237 if (body) {
85238 if (ts.isBlock(body)) {
85239 var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
85240 if (indentedFlag) {
85241 increaseIndent();
85242 }
85243 pushNameGenerationScope(node);
85244 ts.forEach(node.parameters, generateNames);
85245 generateNames(node.body);
85246 emitSignatureHead(node);
85247 if (onEmitNode) {
85248 onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
85249 }
85250 else {
85251 emitBlockFunctionBody(body);
85252 }
85253 popNameGenerationScope(node);
85254 if (indentedFlag) {
85255 decreaseIndent();
85256 }
85257 }
85258 else {
85259 emitSignatureHead(node);
85260 writeSpace();
85261 emitExpression(body);
85262 }
85263 }
85264 else {
85265 emitSignatureHead(node);
85266 writeTrailingSemicolon();
85267 }
85268 }
85269 function emitSignatureHead(node) {
85270 emitTypeParameters(node, node.typeParameters);
85271 emitParameters(node, node.parameters);
85272 emitTypeAnnotation(node.type);
85273 }
85274 function shouldEmitBlockFunctionBodyOnSingleLine(body) {
85275 // We must emit a function body as a single-line body in the following case:
85276 // * The body has NodeEmitFlags.SingleLine specified.
85277 // We must emit a function body as a multi-line body in the following cases:
85278 // * The body is explicitly marked as multi-line.
85279 // * A non-synthesized body's start and end position are on different lines.
85280 // * Any statement in the body starts on a new line.
85281 if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
85282 return true;
85283 }
85284 if (body.multiLine) {
85285 return false;
85286 }
85287 if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
85288 return false;
85289 }
85290 if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */)
85291 || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) {
85292 return false;
85293 }
85294 var previousStatement;
85295 for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
85296 var statement = _b[_a];
85297 if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) {
85298 return false;
85299 }
85300 previousStatement = statement;
85301 }
85302 return true;
85303 }
85304 function emitBlockFunctionBody(body) {
85305 writeSpace();
85306 writePunctuation("{");
85307 increaseIndent();
85308 var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
85309 ? emitBlockFunctionBodyOnSingleLine
85310 : emitBlockFunctionBodyWorker;
85311 if (emitBodyWithDetachedComments) {
85312 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
85313 }
85314 else {
85315 emitBlockFunctionBody(body);
85316 }
85317 decreaseIndent();
85318 writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
85319 }
85320 function emitBlockFunctionBodyOnSingleLine(body) {
85321 emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
85322 }
85323 function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
85324 // Emit all the prologue directives (like "use strict").
85325 var statementOffset = emitPrologueDirectives(body.statements);
85326 var pos = writer.getTextPos();
85327 emitHelpers(body);
85328 if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
85329 decreaseIndent();
85330 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
85331 increaseIndent();
85332 }
85333 else {
85334 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
85335 }
85336 }
85337 function emitClassDeclaration(node) {
85338 emitClassDeclarationOrExpression(node);
85339 }
85340 function emitClassDeclarationOrExpression(node) {
85341 ts.forEach(node.members, generateMemberNames);
85342 emitDecorators(node, node.decorators);
85343 emitModifiers(node, node.modifiers);
85344 writeKeyword("class");
85345 if (node.name) {
85346 writeSpace();
85347 emitIdentifierName(node.name);
85348 }
85349 var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
85350 if (indentedFlag) {
85351 increaseIndent();
85352 }
85353 emitTypeParameters(node, node.typeParameters);
85354 emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
85355 writeSpace();
85356 writePunctuation("{");
85357 emitList(node, node.members, 129 /* ClassMembers */);
85358 writePunctuation("}");
85359 if (indentedFlag) {
85360 decreaseIndent();
85361 }
85362 }
85363 function emitInterfaceDeclaration(node) {
85364 emitDecorators(node, node.decorators);
85365 emitModifiers(node, node.modifiers);
85366 writeKeyword("interface");
85367 writeSpace();
85368 emit(node.name);
85369 emitTypeParameters(node, node.typeParameters);
85370 emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
85371 writeSpace();
85372 writePunctuation("{");
85373 emitList(node, node.members, 129 /* InterfaceMembers */);
85374 writePunctuation("}");
85375 }
85376 function emitTypeAliasDeclaration(node) {
85377 emitDecorators(node, node.decorators);
85378 emitModifiers(node, node.modifiers);
85379 writeKeyword("type");
85380 writeSpace();
85381 emit(node.name);
85382 emitTypeParameters(node, node.typeParameters);
85383 writeSpace();
85384 writePunctuation("=");
85385 writeSpace();
85386 emit(node.type);
85387 writeTrailingSemicolon();
85388 }
85389 function emitEnumDeclaration(node) {
85390 emitModifiers(node, node.modifiers);
85391 writeKeyword("enum");
85392 writeSpace();
85393 emit(node.name);
85394 writeSpace();
85395 writePunctuation("{");
85396 emitList(node, node.members, 145 /* EnumMembers */);
85397 writePunctuation("}");
85398 }
85399 function emitModuleDeclaration(node) {
85400 emitModifiers(node, node.modifiers);
85401 if (~node.flags & 512 /* GlobalAugmentation */) {
85402 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
85403 writeSpace();
85404 }
85405 emit(node.name);
85406 var body = node.body;
85407 if (!body)
85408 return writeTrailingSemicolon();
85409 while (body.kind === 244 /* ModuleDeclaration */) {
85410 writePunctuation(".");
85411 emit(body.name);
85412 body = body.body;
85413 }
85414 writeSpace();
85415 emit(body);
85416 }
85417 function emitModuleBlock(node) {
85418 pushNameGenerationScope(node);
85419 ts.forEach(node.statements, generateNames);
85420 emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
85421 popNameGenerationScope(node);
85422 }
85423 function emitCaseBlock(node) {
85424 emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
85425 emitList(node, node.clauses, 129 /* CaseBlockClauses */);
85426 emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
85427 }
85428 function emitImportEqualsDeclaration(node) {
85429 emitModifiers(node, node.modifiers);
85430 emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
85431 writeSpace();
85432 emit(node.name);
85433 writeSpace();
85434 emitTokenWithComment(59 /* EqualsToken */, node.name.end, writePunctuation, node);
85435 writeSpace();
85436 emitModuleReference(node.moduleReference);
85437 writeTrailingSemicolon();
85438 }
85439 function emitModuleReference(node) {
85440 if (node.kind === 72 /* Identifier */) {
85441 emitExpression(node);
85442 }
85443 else {
85444 emit(node);
85445 }
85446 }
85447 function emitImportDeclaration(node) {
85448 emitModifiers(node, node.modifiers);
85449 emitTokenWithComment(92 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
85450 writeSpace();
85451 if (node.importClause) {
85452 emit(node.importClause);
85453 writeSpace();
85454 emitTokenWithComment(144 /* FromKeyword */, node.importClause.end, writeKeyword, node);
85455 writeSpace();
85456 }
85457 emitExpression(node.moduleSpecifier);
85458 writeTrailingSemicolon();
85459 }
85460 function emitImportClause(node) {
85461 emit(node.name);
85462 if (node.name && node.namedBindings) {
85463 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
85464 writeSpace();
85465 }
85466 emit(node.namedBindings);
85467 }
85468 function emitNamespaceImport(node) {
85469 var asPos = emitTokenWithComment(40 /* AsteriskToken */, node.pos, writePunctuation, node);
85470 writeSpace();
85471 emitTokenWithComment(119 /* AsKeyword */, asPos, writeKeyword, node);
85472 writeSpace();
85473 emit(node.name);
85474 }
85475 function emitNamedImports(node) {
85476 emitNamedImportsOrExports(node);
85477 }
85478 function emitImportSpecifier(node) {
85479 emitImportOrExportSpecifier(node);
85480 }
85481 function emitExportAssignment(node) {
85482 var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node);
85483 writeSpace();
85484 if (node.isExportEquals) {
85485 emitTokenWithComment(59 /* EqualsToken */, nextPos, writeOperator, node);
85486 }
85487 else {
85488 emitTokenWithComment(80 /* DefaultKeyword */, nextPos, writeKeyword, node);
85489 }
85490 writeSpace();
85491 emitExpression(node.expression);
85492 writeTrailingSemicolon();
85493 }
85494 function emitExportDeclaration(node) {
85495 var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node);
85496 writeSpace();
85497 if (node.exportClause) {
85498 emit(node.exportClause);
85499 }
85500 else {
85501 nextPos = emitTokenWithComment(40 /* AsteriskToken */, nextPos, writePunctuation, node);
85502 }
85503 if (node.moduleSpecifier) {
85504 writeSpace();
85505 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
85506 emitTokenWithComment(144 /* FromKeyword */, fromPos, writeKeyword, node);
85507 writeSpace();
85508 emitExpression(node.moduleSpecifier);
85509 }
85510 writeTrailingSemicolon();
85511 }
85512 function emitNamespaceExportDeclaration(node) {
85513 var nextPos = emitTokenWithComment(85 /* ExportKeyword */, node.pos, writeKeyword, node);
85514 writeSpace();
85515 nextPos = emitTokenWithComment(119 /* AsKeyword */, nextPos, writeKeyword, node);
85516 writeSpace();
85517 nextPos = emitTokenWithComment(131 /* NamespaceKeyword */, nextPos, writeKeyword, node);
85518 writeSpace();
85519 emit(node.name);
85520 writeTrailingSemicolon();
85521 }
85522 function emitNamedExports(node) {
85523 emitNamedImportsOrExports(node);
85524 }
85525 function emitExportSpecifier(node) {
85526 emitImportOrExportSpecifier(node);
85527 }
85528 function emitNamedImportsOrExports(node) {
85529 writePunctuation("{");
85530 emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
85531 writePunctuation("}");
85532 }
85533 function emitImportOrExportSpecifier(node) {
85534 if (node.propertyName) {
85535 emit(node.propertyName);
85536 writeSpace();
85537 emitTokenWithComment(119 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
85538 writeSpace();
85539 }
85540 emit(node.name);
85541 }
85542 //
85543 // Module references
85544 //
85545 function emitExternalModuleReference(node) {
85546 writeKeyword("require");
85547 writePunctuation("(");
85548 emitExpression(node.expression);
85549 writePunctuation(")");
85550 }
85551 //
85552 // JSX
85553 //
85554 function emitJsxElement(node) {
85555 emit(node.openingElement);
85556 emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
85557 emit(node.closingElement);
85558 }
85559 function emitJsxSelfClosingElement(node) {
85560 writePunctuation("<");
85561 emitJsxTagName(node.tagName);
85562 emitTypeArguments(node, node.typeArguments);
85563 writeSpace();
85564 emit(node.attributes);
85565 writePunctuation("/>");
85566 }
85567 function emitJsxFragment(node) {
85568 emit(node.openingFragment);
85569 emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
85570 emit(node.closingFragment);
85571 }
85572 function emitJsxOpeningElementOrFragment(node) {
85573 writePunctuation("<");
85574 if (ts.isJsxOpeningElement(node)) {
85575 emitJsxTagName(node.tagName);
85576 emitTypeArguments(node, node.typeArguments);
85577 if (node.attributes.properties && node.attributes.properties.length > 0) {
85578 writeSpace();
85579 }
85580 emit(node.attributes);
85581 }
85582 writePunctuation(">");
85583 }
85584 function emitJsxText(node) {
85585 writer.writeLiteral(node.text);
85586 }
85587 function emitJsxClosingElementOrFragment(node) {
85588 writePunctuation("</");
85589 if (ts.isJsxClosingElement(node)) {
85590 emitJsxTagName(node.tagName);
85591 }
85592 writePunctuation(">");
85593 }
85594 function emitJsxAttributes(node) {
85595 emitList(node, node.properties, 262656 /* JsxElementAttributes */);
85596 }
85597 function emitJsxAttribute(node) {
85598 emit(node.name);
85599 emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217
85600 }
85601 function emitJsxSpreadAttribute(node) {
85602 writePunctuation("{...");
85603 emitExpression(node.expression);
85604 writePunctuation("}");
85605 }
85606 function emitJsxExpression(node) {
85607 if (node.expression) {
85608 writePunctuation("{");
85609 emit(node.dotDotDotToken);
85610 emitExpression(node.expression);
85611 writePunctuation("}");
85612 }
85613 }
85614 function emitJsxTagName(node) {
85615 if (node.kind === 72 /* Identifier */) {
85616 emitExpression(node);
85617 }
85618 else {
85619 emit(node);
85620 }
85621 }
85622 //
85623 // Clauses
85624 //
85625 function emitCaseClause(node) {
85626 emitTokenWithComment(74 /* CaseKeyword */, node.pos, writeKeyword, node);
85627 writeSpace();
85628 emitExpression(node.expression);
85629 emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
85630 }
85631 function emitDefaultClause(node) {
85632 var pos = emitTokenWithComment(80 /* DefaultKeyword */, node.pos, writeKeyword, node);
85633 emitCaseOrDefaultClauseRest(node, node.statements, pos);
85634 }
85635 function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
85636 var emitAsSingleStatement = statements.length === 1 &&
85637 (
85638 // treat synthesized nodes as located on the same line for emit purposes
85639 ts.nodeIsSynthesized(parentNode) ||
85640 ts.nodeIsSynthesized(statements[0]) ||
85641 ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
85642 var format = 163969 /* CaseOrDefaultClauseStatements */;
85643 if (emitAsSingleStatement) {
85644 writeToken(57 /* ColonToken */, colonPos, writePunctuation, parentNode);
85645 writeSpace();
85646 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
85647 }
85648 else {
85649 emitTokenWithComment(57 /* ColonToken */, colonPos, writePunctuation, parentNode);
85650 }
85651 emitList(parentNode, statements, format);
85652 }
85653 function emitHeritageClause(node) {
85654 writeSpace();
85655 writeTokenText(node.token, writeKeyword);
85656 writeSpace();
85657 emitList(node, node.types, 528 /* HeritageClauseTypes */);
85658 }
85659 function emitCatchClause(node) {
85660 var openParenPos = emitTokenWithComment(75 /* CatchKeyword */, node.pos, writeKeyword, node);
85661 writeSpace();
85662 if (node.variableDeclaration) {
85663 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
85664 emit(node.variableDeclaration);
85665 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
85666 writeSpace();
85667 }
85668 emit(node.block);
85669 }
85670 //
85671 // Property assignments
85672 //
85673 function emitPropertyAssignment(node) {
85674 emit(node.name);
85675 writePunctuation(":");
85676 writeSpace();
85677 // This is to ensure that we emit comment in the following case:
85678 // For example:
85679 // obj = {
85680 // id: /*comment1*/ ()=>void
85681 // }
85682 // "comment1" is not considered to be leading comment for node.initializer
85683 // but rather a trailing comment on the previous node.
85684 var initializer = node.initializer;
85685 if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
85686 var commentRange = ts.getCommentRange(initializer);
85687 emitTrailingCommentsOfPosition(commentRange.pos);
85688 }
85689 emitExpression(initializer);
85690 }
85691 function emitShorthandPropertyAssignment(node) {
85692 emit(node.name);
85693 if (node.objectAssignmentInitializer) {
85694 writeSpace();
85695 writePunctuation("=");
85696 writeSpace();
85697 emitExpression(node.objectAssignmentInitializer);
85698 }
85699 }
85700 function emitSpreadAssignment(node) {
85701 if (node.expression) {
85702 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
85703 emitExpression(node.expression);
85704 }
85705 }
85706 //
85707 // Enum
85708 //
85709 function emitEnumMember(node) {
85710 emit(node.name);
85711 emitInitializer(node.initializer, node.name.end, node);
85712 }
85713 //
85714 // JSDoc
85715 //
85716 function emitJSDoc(node) {
85717 write("/**");
85718 if (node.comment) {
85719 var lines = node.comment.split(/\r\n?|\n/g);
85720 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
85721 var line = lines_2[_a];
85722 writeLine();
85723 writeSpace();
85724 writePunctuation("*");
85725 writeSpace();
85726 write(line);
85727 }
85728 }
85729 if (node.tags) {
85730 if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
85731 writeSpace();
85732 emit(node.tags[0]);
85733 }
85734 else {
85735 emitList(node, node.tags, 33 /* JSDocComment */);
85736 }
85737 }
85738 writeSpace();
85739 write("*/");
85740 }
85741 function emitJSDocSimpleTypedTag(tag) {
85742 emitJSDocTagName(tag.tagName);
85743 emitJSDocTypeExpression(tag.typeExpression);
85744 emitJSDocComment(tag.comment);
85745 }
85746 function emitJSDocAugmentsTag(tag) {
85747 emitJSDocTagName(tag.tagName);
85748 writeSpace();
85749 writePunctuation("{");
85750 emit(tag.class);
85751 writePunctuation("}");
85752 emitJSDocComment(tag.comment);
85753 }
85754 function emitJSDocTemplateTag(tag) {
85755 emitJSDocTagName(tag.tagName);
85756 emitJSDocTypeExpression(tag.constraint);
85757 writeSpace();
85758 emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
85759 emitJSDocComment(tag.comment);
85760 }
85761 function emitJSDocTypedefTag(tag) {
85762 emitJSDocTagName(tag.tagName);
85763 if (tag.typeExpression) {
85764 if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
85765 emitJSDocTypeExpression(tag.typeExpression);
85766 }
85767 else {
85768 writeSpace();
85769 writePunctuation("{");
85770 write("Object");
85771 if (tag.typeExpression.isArrayType) {
85772 writePunctuation("[");
85773 writePunctuation("]");
85774 }
85775 writePunctuation("}");
85776 }
85777 }
85778 if (tag.fullName) {
85779 writeSpace();
85780 emit(tag.fullName);
85781 }
85782 emitJSDocComment(tag.comment);
85783 if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
85784 emitJSDocTypeLiteral(tag.typeExpression);
85785 }
85786 }
85787 function emitJSDocCallbackTag(tag) {
85788 emitJSDocTagName(tag.tagName);
85789 if (tag.name) {
85790 writeSpace();
85791 emit(tag.name);
85792 }
85793 emitJSDocComment(tag.comment);
85794 emitJSDocSignature(tag.typeExpression);
85795 }
85796 function emitJSDocSimpleTag(tag) {
85797 emitJSDocTagName(tag.tagName);
85798 emitJSDocComment(tag.comment);
85799 }
85800 function emitJSDocTypeLiteral(lit) {
85801 emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
85802 }
85803 function emitJSDocSignature(sig) {
85804 if (sig.typeParameters) {
85805 emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
85806 }
85807 if (sig.parameters) {
85808 emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */);
85809 }
85810 if (sig.type) {
85811 writeLine();
85812 writeSpace();
85813 writePunctuation("*");
85814 writeSpace();
85815 emit(sig.type);
85816 }
85817 }
85818 function emitJSDocPropertyLikeTag(param) {
85819 emitJSDocTagName(param.tagName);
85820 emitJSDocTypeExpression(param.typeExpression);
85821 writeSpace();
85822 if (param.isBracketed) {
85823 writePunctuation("[");
85824 }
85825 emit(param.name);
85826 if (param.isBracketed) {
85827 writePunctuation("]");
85828 }
85829 emitJSDocComment(param.comment);
85830 }
85831 function emitJSDocTagName(tagName) {
85832 writePunctuation("@");
85833 emit(tagName);
85834 }
85835 function emitJSDocComment(comment) {
85836 if (comment) {
85837 writeSpace();
85838 write(comment);
85839 }
85840 }
85841 function emitJSDocTypeExpression(typeExpression) {
85842 if (typeExpression) {
85843 writeSpace();
85844 writePunctuation("{");
85845 emit(typeExpression.type);
85846 writePunctuation("}");
85847 }
85848 }
85849 //
85850 // Top-level nodes
85851 //
85852 function emitSourceFile(node) {
85853 writeLine();
85854 var statements = node.statements;
85855 if (emitBodyWithDetachedComments) {
85856 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
85857 // The synthesized node will have no leading comment so some comments may be missed.
85858 var shouldEmitDetachedComment = statements.length === 0 ||
85859 !ts.isPrologueDirective(statements[0]) ||
85860 ts.nodeIsSynthesized(statements[0]);
85861 if (shouldEmitDetachedComment) {
85862 emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
85863 return;
85864 }
85865 }
85866 emitSourceFileWorker(node);
85867 }
85868 function emitSyntheticTripleSlashReferencesIfNeeded(node) {
85869 emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
85870 for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
85871 var prepend = _b[_a];
85872 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
85873 for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
85874 var ref = _d[_c];
85875 emit(ref);
85876 writeLine();
85877 }
85878 }
85879 }
85880 }
85881 function emitTripleSlashDirectivesIfNeeded(node) {
85882 if (node.isDeclarationFile)
85883 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
85884 }
85885 function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
85886 if (hasNoDefaultLib) {
85887 var pos = writer.getTextPos();
85888 writeComment("/// <reference no-default-lib=\"true\"/>");
85889 if (bundleFileInfo)
85890 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
85891 writeLine();
85892 }
85893 if (currentSourceFile && currentSourceFile.moduleName) {
85894 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
85895 writeLine();
85896 }
85897 if (currentSourceFile && currentSourceFile.amdDependencies) {
85898 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
85899 var dep = _b[_a];
85900 if (dep.name) {
85901 writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
85902 }
85903 else {
85904 writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
85905 }
85906 writeLine();
85907 }
85908 }
85909 for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
85910 var directive = files_1[_c];
85911 var pos = writer.getTextPos();
85912 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
85913 if (bundleFileInfo)
85914 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
85915 writeLine();
85916 }
85917 for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
85918 var directive = types_19[_d];
85919 var pos = writer.getTextPos();
85920 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
85921 if (bundleFileInfo)
85922 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
85923 writeLine();
85924 }
85925 for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
85926 var directive = libs_1[_e];
85927 var pos = writer.getTextPos();
85928 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
85929 if (bundleFileInfo)
85930 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
85931 writeLine();
85932 }
85933 }
85934 function emitSourceFileWorker(node) {
85935 var statements = node.statements;
85936 pushNameGenerationScope(node);
85937 ts.forEach(node.statements, generateNames);
85938 emitHelpers(node);
85939 var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
85940 emitTripleSlashDirectivesIfNeeded(node);
85941 emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
85942 popNameGenerationScope(node);
85943 }
85944 // Transformation nodes
85945 function emitPartiallyEmittedExpression(node) {
85946 emitExpression(node.expression);
85947 }
85948 function emitCommaList(node) {
85949 emitExpressionList(node, node.elements, 528 /* CommaListElements */);
85950 }
85951 /**
85952 * Emits any prologue directives at the start of a Statement list, returning the
85953 * number of prologue directives written to the output.
85954 */
85955 function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
85956 var needsToSetSourceFile = !!sourceFile;
85957 for (var i = 0; i < statements.length; i++) {
85958 var statement = statements[i];
85959 if (ts.isPrologueDirective(statement)) {
85960 var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
85961 if (shouldEmitPrologueDirective) {
85962 if (needsToSetSourceFile) {
85963 needsToSetSourceFile = false;
85964 setSourceFile(sourceFile);
85965 }
85966 writeLine();
85967 var pos = writer.getTextPos();
85968 emit(statement);
85969 if (recordBundleFileSection && bundleFileInfo)
85970 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
85971 if (seenPrologueDirectives) {
85972 seenPrologueDirectives.set(statement.expression.text, true);
85973 }
85974 }
85975 }
85976 else {
85977 // return index of the first non prologue directive
85978 return i;
85979 }
85980 }
85981 return statements.length;
85982 }
85983 function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
85984 for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
85985 var prologue = prologues_1[_a];
85986 if (!seenPrologueDirectives.has(prologue.data)) {
85987 writeLine();
85988 var pos = writer.getTextPos();
85989 emit(prologue);
85990 if (bundleFileInfo)
85991 bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
85992 if (seenPrologueDirectives) {
85993 seenPrologueDirectives.set(prologue.data, true);
85994 }
85995 }
85996 }
85997 }
85998 function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
85999 if (ts.isSourceFile(sourceFileOrBundle)) {
86000 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
86001 }
86002 else {
86003 var seenPrologueDirectives = ts.createMap();
86004 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
86005 var prepend = _b[_a];
86006 emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
86007 }
86008 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
86009 var sourceFile = _d[_c];
86010 emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
86011 }
86012 setSourceFile(undefined);
86013 }
86014 }
86015 function getPrologueDirectivesFromBundledSourceFiles(bundle) {
86016 var seenPrologueDirectives = ts.createMap();
86017 var prologues;
86018 for (var index = 0; index < bundle.sourceFiles.length; index++) {
86019 var sourceFile = bundle.sourceFiles[index];
86020 var directives = void 0;
86021 var end = 0;
86022 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
86023 var statement = _b[_a];
86024 if (!ts.isPrologueDirective(statement))
86025 break;
86026 if (seenPrologueDirectives.has(statement.expression.text))
86027 continue;
86028 seenPrologueDirectives.set(statement.expression.text, true);
86029 (directives || (directives = [])).push({
86030 pos: statement.pos,
86031 end: statement.end,
86032 expression: {
86033 pos: statement.expression.pos,
86034 end: statement.expression.end,
86035 text: statement.expression.text
86036 }
86037 });
86038 end = end < statement.end ? statement.end : end;
86039 }
86040 if (directives)
86041 (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
86042 }
86043 return prologues;
86044 }
86045 function emitShebangIfNeeded(sourceFileOrBundle) {
86046 if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
86047 var shebang = ts.getShebang(sourceFileOrBundle.text);
86048 if (shebang) {
86049 writeComment(shebang);
86050 writeLine();
86051 return true;
86052 }
86053 }
86054 else {
86055 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
86056 var prepend = _b[_a];
86057 ts.Debug.assertNode(prepend, ts.isUnparsedSource);
86058 if (emitShebangIfNeeded(prepend)) {
86059 return true;
86060 }
86061 }
86062 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
86063 var sourceFile = _d[_c];
86064 // Emit only the first encountered shebang
86065 if (emitShebangIfNeeded(sourceFile)) {
86066 return true;
86067 }
86068 }
86069 }
86070 }
86071 //
86072 // Helpers
86073 //
86074 function emitNodeWithWriter(node, writer) {
86075 if (!node)
86076 return;
86077 var savedWrite = write;
86078 write = writer;
86079 emit(node);
86080 write = savedWrite;
86081 }
86082 function emitModifiers(node, modifiers) {
86083 if (modifiers && modifiers.length) {
86084 emitList(node, modifiers, 262656 /* Modifiers */);
86085 writeSpace();
86086 }
86087 }
86088 function emitTypeAnnotation(node) {
86089 if (node) {
86090 writePunctuation(":");
86091 writeSpace();
86092 emit(node);
86093 }
86094 }
86095 function emitInitializer(node, equalCommentStartPos, container) {
86096 if (node) {
86097 writeSpace();
86098 emitTokenWithComment(59 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
86099 writeSpace();
86100 emitExpression(node);
86101 }
86102 }
86103 function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
86104 if (node) {
86105 prefixWriter(prefix);
86106 emit(node);
86107 }
86108 }
86109 function emitWithLeadingSpace(node) {
86110 if (node) {
86111 writeSpace();
86112 emit(node);
86113 }
86114 }
86115 function emitExpressionWithLeadingSpace(node) {
86116 if (node) {
86117 writeSpace();
86118 emitExpression(node);
86119 }
86120 }
86121 function emitWithTrailingSpace(node) {
86122 if (node) {
86123 emit(node);
86124 writeSpace();
86125 }
86126 }
86127 function emitEmbeddedStatement(parent, node) {
86128 if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
86129 writeSpace();
86130 emit(node);
86131 }
86132 else {
86133 writeLine();
86134 increaseIndent();
86135 if (ts.isEmptyStatement(node)) {
86136 var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
86137 pipelinePhase(5 /* EmbeddedStatement */, node);
86138 }
86139 else {
86140 emit(node);
86141 }
86142 decreaseIndent();
86143 }
86144 }
86145 function emitDecorators(parentNode, decorators) {
86146 emitList(parentNode, decorators, 49153 /* Decorators */);
86147 }
86148 function emitTypeArguments(parentNode, typeArguments) {
86149 emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
86150 }
86151 function emitTypeParameters(parentNode, typeParameters) {
86152 if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
86153 return emitTypeArguments(parentNode, parentNode.typeArguments);
86154 }
86155 emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
86156 }
86157 function emitParameters(parentNode, parameters) {
86158 emitList(parentNode, parameters, 2576 /* Parameters */);
86159 }
86160 function canEmitSimpleArrowHead(parentNode, parameters) {
86161 var parameter = ts.singleOrUndefined(parameters);
86162 return parameter
86163 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
86164 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
86165 && !parentNode.type // arrow function may not have return type annotation
86166 && !ts.some(parentNode.decorators) // parent may not have decorators
86167 && !ts.some(parentNode.modifiers) // parent may not have modifiers
86168 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
86169 && !ts.some(parameter.decorators) // parameter may not have decorators
86170 && !ts.some(parameter.modifiers) // parameter may not have modifiers
86171 && !parameter.dotDotDotToken // parameter may not be rest
86172 && !parameter.questionToken // parameter may not be optional
86173 && !parameter.type // parameter may not have a type annotation
86174 && !parameter.initializer // parameter may not have an initializer
86175 && ts.isIdentifier(parameter.name); // parameter name must be identifier
86176 }
86177 function emitParametersForArrow(parentNode, parameters) {
86178 if (canEmitSimpleArrowHead(parentNode, parameters)) {
86179 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
86180 }
86181 else {
86182 emitParameters(parentNode, parameters);
86183 }
86184 }
86185 function emitParametersForIndexSignature(parentNode, parameters) {
86186 emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
86187 }
86188 function emitList(parentNode, children, format, start, count) {
86189 emitNodeList(emit, parentNode, children, format, start, count);
86190 }
86191 function emitExpressionList(parentNode, children, format, start, count) {
86192 emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
86193 }
86194 function writeDelimiter(format) {
86195 switch (format & 60 /* DelimitersMask */) {
86196 case 0 /* None */:
86197 break;
86198 case 16 /* CommaDelimited */:
86199 writePunctuation(",");
86200 break;
86201 case 4 /* BarDelimited */:
86202 writeSpace();
86203 writePunctuation("|");
86204 break;
86205 case 32 /* AsteriskDelimited */:
86206 writeSpace();
86207 writePunctuation("*");
86208 writeSpace();
86209 break;
86210 case 8 /* AmpersandDelimited */:
86211 writeSpace();
86212 writePunctuation("&");
86213 break;
86214 }
86215 }
86216 function emitNodeList(emit, parentNode, children, format, start, count) {
86217 if (start === void 0) { start = 0; }
86218 if (count === void 0) { count = children ? children.length - start : 0; }
86219 var isUndefined = children === undefined;
86220 if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
86221 return;
86222 }
86223 var isEmpty = children === undefined || start >= children.length || count === 0;
86224 if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
86225 if (onBeforeEmitNodeArray) {
86226 onBeforeEmitNodeArray(children);
86227 }
86228 if (onAfterEmitNodeArray) {
86229 onAfterEmitNodeArray(children);
86230 }
86231 return;
86232 }
86233 if (format & 15360 /* BracketsMask */) {
86234 writePunctuation(getOpeningBracket(format));
86235 if (isEmpty && !isUndefined) {
86236 // TODO: GH#18217
86237 emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
86238 }
86239 }
86240 if (onBeforeEmitNodeArray) {
86241 onBeforeEmitNodeArray(children);
86242 }
86243 if (isEmpty) {
86244 // Write a line terminator if the parent node was multi-line
86245 if (format & 1 /* MultiLine */) {
86246 writeLine();
86247 }
86248 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
86249 writeSpace();
86250 }
86251 }
86252 else {
86253 // Write the opening line terminator or leading whitespace.
86254 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
86255 var shouldEmitInterveningComments = mayEmitInterveningComments;
86256 if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217
86257 writeLine();
86258 shouldEmitInterveningComments = false;
86259 }
86260 else if (format & 256 /* SpaceBetweenBraces */) {
86261 writeSpace();
86262 }
86263 // Increase the indent, if requested.
86264 if (format & 128 /* Indented */) {
86265 increaseIndent();
86266 }
86267 // Emit each child.
86268 var previousSibling = void 0;
86269 var previousSourceFileTextKind = void 0;
86270 var shouldDecreaseIndentAfterEmit = false;
86271 for (var i = 0; i < count; i++) {
86272 var child = children[start + i];
86273 // Write the delimiter if this is not the first node.
86274 if (format & 32 /* AsteriskDelimited */) {
86275 // always write JSDoc in the format "\n *"
86276 writeLine();
86277 writeDelimiter(format);
86278 }
86279 else if (previousSibling) {
86280 // i.e
86281 // function commentedParameters(
86282 // /* Parameter a */
86283 // a
86284 // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
86285 // ,
86286 if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
86287 emitLeadingCommentsOfPosition(previousSibling.end);
86288 }
86289 writeDelimiter(format);
86290 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
86291 // Write either a line terminator or whitespace to separate the elements.
86292 if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
86293 // If a synthesized node in a single-line list starts on a new
86294 // line, we should increase the indent.
86295 if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
86296 increaseIndent();
86297 shouldDecreaseIndentAfterEmit = true;
86298 }
86299 writeLine();
86300 shouldEmitInterveningComments = false;
86301 }
86302 else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
86303 writeSpace();
86304 }
86305 }
86306 // Emit this child.
86307 previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
86308 if (shouldEmitInterveningComments) {
86309 if (emitTrailingCommentsOfPosition) {
86310 var commentRange = ts.getCommentRange(child);
86311 emitTrailingCommentsOfPosition(commentRange.pos);
86312 }
86313 }
86314 else {
86315 shouldEmitInterveningComments = mayEmitInterveningComments;
86316 }
86317 emit(child);
86318 if (shouldDecreaseIndentAfterEmit) {
86319 decreaseIndent();
86320 shouldDecreaseIndentAfterEmit = false;
86321 }
86322 previousSibling = child;
86323 }
86324 // Write a trailing comma, if requested.
86325 var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
86326 if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
86327 writePunctuation(",");
86328 }
86329 // Emit any trailing comment of the last element in the list
86330 // i.e
86331 // var array = [...
86332 // 2
86333 // /* end of element 2 */
86334 // ];
86335 if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
86336 emitLeadingCommentsOfPosition(previousSibling.end);
86337 }
86338 // Decrease the indent, if requested.
86339 if (format & 128 /* Indented */) {
86340 decreaseIndent();
86341 }
86342 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
86343 // Write the closing line terminator or closing whitespace.
86344 if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
86345 writeLine();
86346 }
86347 else if (format & 256 /* SpaceBetweenBraces */) {
86348 writeSpace();
86349 }
86350 }
86351 if (onAfterEmitNodeArray) {
86352 onAfterEmitNodeArray(children);
86353 }
86354 if (format & 15360 /* BracketsMask */) {
86355 if (isEmpty && !isUndefined) {
86356 // TODO: GH#18217
86357 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
86358 }
86359 writePunctuation(getClosingBracket(format));
86360 }
86361 }
86362 // Writers
86363 function writeLiteral(s) {
86364 writer.writeLiteral(s);
86365 }
86366 function writeStringLiteral(s) {
86367 writer.writeStringLiteral(s);
86368 }
86369 function writeBase(s) {
86370 writer.write(s);
86371 }
86372 function writeSymbol(s, sym) {
86373 writer.writeSymbol(s, sym);
86374 }
86375 function writePunctuation(s) {
86376 writer.writePunctuation(s);
86377 }
86378 function writeTrailingSemicolon() {
86379 writer.writeTrailingSemicolon(";");
86380 }
86381 function writeKeyword(s) {
86382 writer.writeKeyword(s);
86383 }
86384 function writeOperator(s) {
86385 writer.writeOperator(s);
86386 }
86387 function writeParameter(s) {
86388 writer.writeParameter(s);
86389 }
86390 function writeComment(s) {
86391 writer.writeComment(s);
86392 }
86393 function writeSpace() {
86394 writer.writeSpace(" ");
86395 }
86396 function writeProperty(s) {
86397 writer.writeProperty(s);
86398 }
86399 function writeLine() {
86400 writer.writeLine();
86401 }
86402 function increaseIndent() {
86403 writer.increaseIndent();
86404 }
86405 function decreaseIndent() {
86406 writer.decreaseIndent();
86407 }
86408 function writeToken(token, pos, writer, contextNode) {
86409 return !sourceMapsDisabled
86410 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
86411 : writeTokenText(token, writer, pos);
86412 }
86413 function writeTokenNode(node, writer) {
86414 if (onBeforeEmitToken) {
86415 onBeforeEmitToken(node);
86416 }
86417 writer(ts.tokenToString(node.kind));
86418 if (onAfterEmitToken) {
86419 onAfterEmitToken(node);
86420 }
86421 }
86422 function writeTokenText(token, writer, pos) {
86423 var tokenString = ts.tokenToString(token);
86424 writer(tokenString);
86425 return pos < 0 ? pos : pos + tokenString.length;
86426 }
86427 function writeLineOrSpace(node) {
86428 if (ts.getEmitFlags(node) & 1 /* SingleLine */) {
86429 writeSpace();
86430 }
86431 else {
86432 writeLine();
86433 }
86434 }
86435 function writeLines(text) {
86436 var lines = text.split(/\r\n?|\n/g);
86437 var indentation = ts.guessIndentation(lines);
86438 for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
86439 var lineText = lines_3[_a];
86440 var line = indentation ? lineText.slice(indentation) : lineText;
86441 if (line.length) {
86442 writeLine();
86443 write(line);
86444 }
86445 }
86446 }
86447 function increaseIndentIf(value, writeSpaceIfNotIndenting) {
86448 if (value) {
86449 increaseIndent();
86450 writeLine();
86451 }
86452 else if (writeSpaceIfNotIndenting) {
86453 writeSpace();
86454 }
86455 }
86456 // Helper function to decrease the indent if we previously indented. Allows multiple
86457 // previous indent values to be considered at a time. This also allows caller to just
86458 // call this once, passing in all their appropriate indent values, instead of needing
86459 // to call this helper function multiple times.
86460 function decreaseIndentIf(value1, value2) {
86461 if (value1) {
86462 decreaseIndent();
86463 }
86464 if (value2) {
86465 decreaseIndent();
86466 }
86467 }
86468 function shouldWriteLeadingLineTerminator(parentNode, children, format) {
86469 if (format & 1 /* MultiLine */) {
86470 return true;
86471 }
86472 if (format & 2 /* PreserveLines */) {
86473 if (format & 65536 /* PreferNewLine */) {
86474 return true;
86475 }
86476 var firstChild = children[0];
86477 if (firstChild === undefined) {
86478 return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile);
86479 }
86480 else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) {
86481 return synthesizedNodeStartsOnNewLine(firstChild, format);
86482 }
86483 else {
86484 return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile);
86485 }
86486 }
86487 else {
86488 return false;
86489 }
86490 }
86491 function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) {
86492 if (format & 1 /* MultiLine */) {
86493 return true;
86494 }
86495 else if (format & 2 /* PreserveLines */) {
86496 if (previousNode === undefined || nextNode === undefined) {
86497 return false;
86498 }
86499 else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) {
86500 return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format);
86501 }
86502 else {
86503 return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile);
86504 }
86505 }
86506 else {
86507 return ts.getStartsOnNewLine(nextNode);
86508 }
86509 }
86510 function shouldWriteClosingLineTerminator(parentNode, children, format) {
86511 if (format & 1 /* MultiLine */) {
86512 return (format & 131072 /* NoTrailingNewLine */) === 0;
86513 }
86514 else if (format & 2 /* PreserveLines */) {
86515 if (format & 65536 /* PreferNewLine */) {
86516 return true;
86517 }
86518 var lastChild = ts.lastOrUndefined(children);
86519 if (lastChild === undefined) {
86520 return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile);
86521 }
86522 else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) {
86523 return synthesizedNodeStartsOnNewLine(lastChild, format);
86524 }
86525 else {
86526 return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile);
86527 }
86528 }
86529 else {
86530 return false;
86531 }
86532 }
86533 function synthesizedNodeStartsOnNewLine(node, format) {
86534 if (ts.nodeIsSynthesized(node)) {
86535 var startsOnNewLine = ts.getStartsOnNewLine(node);
86536 if (startsOnNewLine === undefined) {
86537 return (format & 65536 /* PreferNewLine */) !== 0;
86538 }
86539 return startsOnNewLine;
86540 }
86541 return (format & 65536 /* PreferNewLine */) !== 0;
86542 }
86543 function needsIndentation(parent, node1, node2) {
86544 parent = skipSynthesizedParentheses(parent);
86545 node1 = skipSynthesizedParentheses(node1);
86546 node2 = skipSynthesizedParentheses(node2);
86547 // Always use a newline for synthesized code if the synthesizer desires it.
86548 if (ts.getStartsOnNewLine(node2)) {
86549 return true;
86550 }
86551 return !ts.nodeIsSynthesized(parent)
86552 && !ts.nodeIsSynthesized(node1)
86553 && !ts.nodeIsSynthesized(node2)
86554 && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile);
86555 }
86556 function isEmptyBlock(block) {
86557 return block.statements.length === 0
86558 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
86559 }
86560 function skipSynthesizedParentheses(node) {
86561 while (node.kind === 195 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
86562 node = node.expression;
86563 }
86564 return node;
86565 }
86566 function getTextOfNode(node, includeTrivia) {
86567 if (ts.isGeneratedIdentifier(node)) {
86568 return generateName(node);
86569 }
86570 else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
86571 return ts.idText(node);
86572 }
86573 else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
86574 return getTextOfNode(node.textSourceNode, includeTrivia);
86575 }
86576 else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
86577 return node.text;
86578 }
86579 return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
86580 }
86581 function getLiteralTextOfNode(node, neverAsciiEscape) {
86582 if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
86583 var textSourceNode = node.textSourceNode;
86584 if (ts.isIdentifier(textSourceNode)) {
86585 return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ?
86586 "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" :
86587 "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\"";
86588 }
86589 else {
86590 return getLiteralTextOfNode(textSourceNode, neverAsciiEscape);
86591 }
86592 }
86593 return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape);
86594 }
86595 /**
86596 * Push a new name generation scope.
86597 */
86598 function pushNameGenerationScope(node) {
86599 if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
86600 return;
86601 }
86602 tempFlagsStack.push(tempFlags);
86603 tempFlags = 0;
86604 reservedNamesStack.push(reservedNames);
86605 }
86606 /**
86607 * Pop the current name generation scope.
86608 */
86609 function popNameGenerationScope(node) {
86610 if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
86611 return;
86612 }
86613 tempFlags = tempFlagsStack.pop();
86614 reservedNames = reservedNamesStack.pop();
86615 }
86616 function reserveNameInNestedScopes(name) {
86617 if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
86618 reservedNames = ts.createMap();
86619 }
86620 reservedNames.set(name, true);
86621 }
86622 function generateNames(node) {
86623 if (!node)
86624 return;
86625 switch (node.kind) {
86626 case 218 /* Block */:
86627 ts.forEach(node.statements, generateNames);
86628 break;
86629 case 233 /* LabeledStatement */:
86630 case 231 /* WithStatement */:
86631 case 223 /* DoStatement */:
86632 case 224 /* WhileStatement */:
86633 generateNames(node.statement);
86634 break;
86635 case 222 /* IfStatement */:
86636 generateNames(node.thenStatement);
86637 generateNames(node.elseStatement);
86638 break;
86639 case 225 /* ForStatement */:
86640 case 227 /* ForOfStatement */:
86641 case 226 /* ForInStatement */:
86642 generateNames(node.initializer);
86643 generateNames(node.statement);
86644 break;
86645 case 232 /* SwitchStatement */:
86646 generateNames(node.caseBlock);
86647 break;
86648 case 246 /* CaseBlock */:
86649 ts.forEach(node.clauses, generateNames);
86650 break;
86651 case 271 /* CaseClause */:
86652 case 272 /* DefaultClause */:
86653 ts.forEach(node.statements, generateNames);
86654 break;
86655 case 235 /* TryStatement */:
86656 generateNames(node.tryBlock);
86657 generateNames(node.catchClause);
86658 generateNames(node.finallyBlock);
86659 break;
86660 case 274 /* CatchClause */:
86661 generateNames(node.variableDeclaration);
86662 generateNames(node.block);
86663 break;
86664 case 219 /* VariableStatement */:
86665 generateNames(node.declarationList);
86666 break;
86667 case 238 /* VariableDeclarationList */:
86668 ts.forEach(node.declarations, generateNames);
86669 break;
86670 case 237 /* VariableDeclaration */:
86671 case 151 /* Parameter */:
86672 case 186 /* BindingElement */:
86673 case 240 /* ClassDeclaration */:
86674 generateNameIfNeeded(node.name);
86675 break;
86676 case 239 /* FunctionDeclaration */:
86677 generateNameIfNeeded(node.name);
86678 if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
86679 ts.forEach(node.parameters, generateNames);
86680 generateNames(node.body);
86681 }
86682 break;
86683 case 184 /* ObjectBindingPattern */:
86684 case 185 /* ArrayBindingPattern */:
86685 ts.forEach(node.elements, generateNames);
86686 break;
86687 case 249 /* ImportDeclaration */:
86688 generateNames(node.importClause);
86689 break;
86690 case 250 /* ImportClause */:
86691 generateNameIfNeeded(node.name);
86692 generateNames(node.namedBindings);
86693 break;
86694 case 251 /* NamespaceImport */:
86695 generateNameIfNeeded(node.name);
86696 break;
86697 case 252 /* NamedImports */:
86698 ts.forEach(node.elements, generateNames);
86699 break;
86700 case 253 /* ImportSpecifier */:
86701 generateNameIfNeeded(node.propertyName || node.name);
86702 break;
86703 }
86704 }
86705 function generateMemberNames(node) {
86706 if (!node)
86707 return;
86708 switch (node.kind) {
86709 case 275 /* PropertyAssignment */:
86710 case 276 /* ShorthandPropertyAssignment */:
86711 case 154 /* PropertyDeclaration */:
86712 case 156 /* MethodDeclaration */:
86713 case 158 /* GetAccessor */:
86714 case 159 /* SetAccessor */:
86715 generateNameIfNeeded(node.name);
86716 break;
86717 }
86718 }
86719 function generateNameIfNeeded(name) {
86720 if (name) {
86721 if (ts.isGeneratedIdentifier(name)) {
86722 generateName(name);
86723 }
86724 else if (ts.isBindingPattern(name)) {
86725 generateNames(name);
86726 }
86727 }
86728 }
86729 /**
86730 * Generate the text for a generated identifier.
86731 */
86732 function generateName(name) {
86733 if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
86734 // Node names generate unique names based on their original node
86735 // and are cached based on that node's id.
86736 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
86737 }
86738 else {
86739 // Auto, Loop, and Unique names are cached based on their unique
86740 // autoGenerateId.
86741 var autoGenerateId = name.autoGenerateId;
86742 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
86743 }
86744 }
86745 function generateNameCached(node, flags) {
86746 var nodeId = ts.getNodeId(node);
86747 return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
86748 }
86749 /**
86750 * Returns a value indicating whether a name is unique globally, within the current file,
86751 * or within the NameGenerator.
86752 */
86753 function isUniqueName(name) {
86754 return isFileLevelUniqueName(name)
86755 && !generatedNames.has(name)
86756 && !(reservedNames && reservedNames.has(name));
86757 }
86758 /**
86759 * Returns a value indicating whether a name is unique globally or within the current file.
86760 */
86761 function isFileLevelUniqueName(name) {
86762 return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
86763 }
86764 /**
86765 * Returns a value indicating whether a name is unique within a container.
86766 */
86767 function isUniqueLocalName(name, container) {
86768 for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
86769 if (node.locals) {
86770 var local = node.locals.get(ts.escapeLeadingUnderscores(name));
86771 // We conservatively include alias symbols to cover cases where they're emitted as locals
86772 if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
86773 return false;
86774 }
86775 }
86776 }
86777 return true;
86778 }
86779 /**
86780 * Return the next available name in the pattern _a ... _z, _0, _1, ...
86781 * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
86782 * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
86783 */
86784 function makeTempVariableName(flags, reservedInNestedScopes) {
86785 if (flags && !(tempFlags & flags)) {
86786 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
86787 if (isUniqueName(name)) {
86788 tempFlags |= flags;
86789 if (reservedInNestedScopes) {
86790 reserveNameInNestedScopes(name);
86791 }
86792 return name;
86793 }
86794 }
86795 while (true) {
86796 var count = tempFlags & 268435455 /* CountMask */;
86797 tempFlags++;
86798 // Skip over 'i' and 'n'
86799 if (count !== 8 && count !== 13) {
86800 var name = count < 26
86801 ? "_" + String.fromCharCode(97 /* a */ + count)
86802 : "_" + (count - 26);
86803 if (isUniqueName(name)) {
86804 if (reservedInNestedScopes) {
86805 reserveNameInNestedScopes(name);
86806 }
86807 return name;
86808 }
86809 }
86810 }
86811 }
86812 /**
86813 * Generate a name that is unique within the current file and doesn't conflict with any names
86814 * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
86815 * where n is a positive integer. Note that names generated by makeTempVariableName and
86816 * makeUniqueName are guaranteed to never conflict.
86817 * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
86818 */
86819 function makeUniqueName(baseName, checkFn, optimistic, scoped) {
86820 if (checkFn === void 0) { checkFn = isUniqueName; }
86821 if (optimistic) {
86822 if (checkFn(baseName)) {
86823 if (scoped) {
86824 reserveNameInNestedScopes(baseName);
86825 }
86826 else {
86827 generatedNames.set(baseName, true);
86828 }
86829 return baseName;
86830 }
86831 }
86832 // Find the first unique 'name_n', where n is a positive number
86833 if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
86834 baseName += "_";
86835 }
86836 var i = 1;
86837 while (true) {
86838 var generatedName = baseName + i;
86839 if (checkFn(generatedName)) {
86840 if (scoped) {
86841 reserveNameInNestedScopes(generatedName);
86842 }
86843 else {
86844 generatedNames.set(generatedName, true);
86845 }
86846 return generatedName;
86847 }
86848 i++;
86849 }
86850 }
86851 function makeFileLevelOptimisticUniqueName(name) {
86852 return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
86853 }
86854 /**
86855 * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
86856 */
86857 function generateNameForModuleOrEnum(node) {
86858 var name = getTextOfNode(node.name);
86859 // Use module/enum name itself if it is unique, otherwise make a unique variation
86860 return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
86861 }
86862 /**
86863 * Generates a unique name for an ImportDeclaration or ExportDeclaration.
86864 */
86865 function generateNameForImportOrExportDeclaration(node) {
86866 var expr = ts.getExternalModuleName(node); // TODO: GH#18217
86867 var baseName = ts.isStringLiteral(expr) ?
86868 ts.makeIdentifierFromModuleName(expr.text) : "module";
86869 return makeUniqueName(baseName);
86870 }
86871 /**
86872 * Generates a unique name for a default export.
86873 */
86874 function generateNameForExportDefault() {
86875 return makeUniqueName("default");
86876 }
86877 /**
86878 * Generates a unique name for a class expression.
86879 */
86880 function generateNameForClassExpression() {
86881 return makeUniqueName("class");
86882 }
86883 function generateNameForMethodOrAccessor(node) {
86884 if (ts.isIdentifier(node.name)) {
86885 return generateNameCached(node.name);
86886 }
86887 return makeTempVariableName(0 /* Auto */);
86888 }
86889 /**
86890 * Generates a unique name from a node.
86891 */
86892 function generateNameForNode(node, flags) {
86893 switch (node.kind) {
86894 case 72 /* Identifier */:
86895 return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
86896 case 244 /* ModuleDeclaration */:
86897 case 243 /* EnumDeclaration */:
86898 return generateNameForModuleOrEnum(node);
86899 case 249 /* ImportDeclaration */:
86900 case 255 /* ExportDeclaration */:
86901 return generateNameForImportOrExportDeclaration(node);
86902 case 239 /* FunctionDeclaration */:
86903 case 240 /* ClassDeclaration */:
86904 case 254 /* ExportAssignment */:
86905 return generateNameForExportDefault();
86906 case 209 /* ClassExpression */:
86907 return generateNameForClassExpression();
86908 case 156 /* MethodDeclaration */:
86909 case 158 /* GetAccessor */:
86910 case 159 /* SetAccessor */:
86911 return generateNameForMethodOrAccessor(node);
86912 default:
86913 return makeTempVariableName(0 /* Auto */);
86914 }
86915 }
86916 /**
86917 * Generates a unique identifier for a node.
86918 */
86919 function makeName(name) {
86920 switch (name.autoGenerateFlags & 7 /* KindMask */) {
86921 case 1 /* Auto */:
86922 return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
86923 case 2 /* Loop */:
86924 return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
86925 case 3 /* Unique */:
86926 return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
86927 }
86928 return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
86929 }
86930 /**
86931 * Gets the node from which a name should be generated.
86932 */
86933 function getNodeForGeneratedName(name) {
86934 var autoGenerateId = name.autoGenerateId;
86935 var node = name;
86936 var original = node.original;
86937 while (original) {
86938 node = original;
86939 // if "node" is a different generated name (having a different
86940 // "autoGenerateId"), use it and stop traversing.
86941 if (ts.isIdentifier(node)
86942 && !!(node.autoGenerateFlags & 4 /* Node */)
86943 && node.autoGenerateId !== autoGenerateId) {
86944 break;
86945 }
86946 original = node.original;
86947 }
86948 // otherwise, return the original node for the source;
86949 return node;
86950 }
86951 // Comments
86952 function pipelineEmitWithComments(hint, node) {
86953 enterComment();
86954 hasWrittenComment = false;
86955 var emitFlags = ts.getEmitFlags(node);
86956 var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
86957 var isEmittedNode = node.kind !== 312 /* NotEmittedStatement */;
86958 // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
86959 // It is expensive to walk entire tree just to set one kind of node to have no comments.
86960 var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
86961 var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
86962 // Save current container state on the stack.
86963 var savedContainerPos = containerPos;
86964 var savedContainerEnd = containerEnd;
86965 var savedDeclarationListContainerEnd = declarationListContainerEnd;
86966 if ((pos > 0 || end > 0) && pos !== end) {
86967 // Emit leading comments if the position is not synthesized and the node
86968 // has not opted out from emitting leading comments.
86969 if (!skipLeadingComments) {
86970 emitLeadingComments(pos, isEmittedNode);
86971 }
86972 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
86973 // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
86974 containerPos = pos;
86975 }
86976 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
86977 // As above.
86978 containerEnd = end;
86979 // To avoid invalid comment emit in a down-level binding pattern, we
86980 // keep track of the last declaration list container's end
86981 if (node.kind === 238 /* VariableDeclarationList */) {
86982 declarationListContainerEnd = end;
86983 }
86984 }
86985 }
86986 ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
86987 exitComment();
86988 var pipelinePhase = getNextPipelinePhase(2 /* Comments */, node);
86989 if (emitFlags & 2048 /* NoNestedComments */) {
86990 commentsDisabled = true;
86991 pipelinePhase(hint, node);
86992 commentsDisabled = false;
86993 }
86994 else {
86995 pipelinePhase(hint, node);
86996 }
86997 enterComment();
86998 ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
86999 if ((pos > 0 || end > 0) && pos !== end) {
87000 // Restore previous container state.
87001 containerPos = savedContainerPos;
87002 containerEnd = savedContainerEnd;
87003 declarationListContainerEnd = savedDeclarationListContainerEnd;
87004 // Emit trailing comments if the position is not synthesized and the node
87005 // has not opted out from emitting leading comments and is an emitted node.
87006 if (!skipTrailingComments && isEmittedNode) {
87007 emitTrailingComments(end);
87008 }
87009 }
87010 exitComment();
87011 }
87012 function emitLeadingSynthesizedComment(comment) {
87013 if (comment.kind === 2 /* SingleLineCommentTrivia */) {
87014 writer.writeLine();
87015 }
87016 writeSynthesizedComment(comment);
87017 if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
87018 writer.writeLine();
87019 }
87020 else {
87021 writer.writeSpace(" ");
87022 }
87023 }
87024 function emitTrailingSynthesizedComment(comment) {
87025 if (!writer.isAtStartOfLine()) {
87026 writer.writeSpace(" ");
87027 }
87028 writeSynthesizedComment(comment);
87029 if (comment.hasTrailingNewLine) {
87030 writer.writeLine();
87031 }
87032 }
87033 function writeSynthesizedComment(comment) {
87034 var text = formatSynthesizedComment(comment);
87035 var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
87036 ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
87037 }
87038 function formatSynthesizedComment(comment) {
87039 return comment.kind === 3 /* MultiLineCommentTrivia */
87040 ? "/*" + comment.text + "*/"
87041 : "//" + comment.text;
87042 }
87043 function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
87044 enterComment();
87045 var pos = detachedRange.pos, end = detachedRange.end;
87046 var emitFlags = ts.getEmitFlags(node);
87047 var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
87048 var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
87049 if (!skipLeadingComments) {
87050 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
87051 }
87052 exitComment();
87053 if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
87054 commentsDisabled = true;
87055 emitCallback(node);
87056 commentsDisabled = false;
87057 }
87058 else {
87059 emitCallback(node);
87060 }
87061 enterComment();
87062 if (!skipTrailingComments) {
87063 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
87064 if (hasWrittenComment && !writer.isAtStartOfLine()) {
87065 writer.writeLine();
87066 }
87067 }
87068 exitComment();
87069 }
87070 function emitLeadingComments(pos, isEmittedNode) {
87071 hasWrittenComment = false;
87072 if (isEmittedNode) {
87073 forEachLeadingCommentToEmit(pos, emitLeadingComment);
87074 }
87075 else if (pos === 0) {
87076 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
87077 // unless it is a triple slash comment at the top of the file.
87078 // For Example:
87079 // /// <reference-path ...>
87080 // declare var x;
87081 // /// <reference-path ...>
87082 // interface F {}
87083 // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
87084 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
87085 }
87086 }
87087 function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
87088 if (isTripleSlashComment(commentPos, commentEnd)) {
87089 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
87090 }
87091 }
87092 function shouldWriteComment(text, pos) {
87093 if (printerOptions.onlyPrintJsDocStyle) {
87094 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
87095 }
87096 return true;
87097 }
87098 function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
87099 if (!shouldWriteComment(currentSourceFile.text, commentPos))
87100 return;
87101 if (!hasWrittenComment) {
87102 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
87103 hasWrittenComment = true;
87104 }
87105 // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
87106 emitPos(commentPos);
87107 ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
87108 emitPos(commentEnd);
87109 if (hasTrailingNewLine) {
87110 writer.writeLine();
87111 }
87112 else if (kind === 3 /* MultiLineCommentTrivia */) {
87113 writer.writeSpace(" ");
87114 }
87115 }
87116 function emitLeadingCommentsOfPosition(pos) {
87117 if (commentsDisabled || pos === -1) {
87118 return;
87119 }
87120 emitLeadingComments(pos, /*isEmittedNode*/ true);
87121 }
87122 function emitTrailingComments(pos) {
87123 forEachTrailingCommentToEmit(pos, emitTrailingComment);
87124 }
87125 function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
87126 if (!shouldWriteComment(currentSourceFile.text, commentPos))
87127 return;
87128 // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
87129 if (!writer.isAtStartOfLine()) {
87130 writer.writeSpace(" ");
87131 }
87132 emitPos(commentPos);
87133 ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
87134 emitPos(commentEnd);
87135 if (hasTrailingNewLine) {
87136 writer.writeLine();
87137 }
87138 }
87139 function emitTrailingCommentsOfPosition(pos, prefixSpace) {
87140 if (commentsDisabled) {
87141 return;
87142 }
87143 enterComment();
87144 forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
87145 exitComment();
87146 }
87147 function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
87148 // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
87149 emitPos(commentPos);
87150 ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
87151 emitPos(commentEnd);
87152 if (hasTrailingNewLine) {
87153 writer.writeLine();
87154 }
87155 else {
87156 writer.writeSpace(" ");
87157 }
87158 }
87159 function forEachLeadingCommentToEmit(pos, cb) {
87160 // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
87161 if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
87162 if (hasDetachedComments(pos)) {
87163 forEachLeadingCommentWithoutDetachedComments(cb);
87164 }
87165 else {
87166 ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
87167 }
87168 }
87169 }
87170 function forEachTrailingCommentToEmit(end, cb) {
87171 // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
87172 if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
87173 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
87174 }
87175 }
87176 function hasDetachedComments(pos) {
87177 return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
87178 }
87179 function forEachLeadingCommentWithoutDetachedComments(cb) {
87180 // get the leading comments from detachedPos
87181 var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
87182 if (detachedCommentsInfo.length - 1) {
87183 detachedCommentsInfo.pop();
87184 }
87185 else {
87186 detachedCommentsInfo = undefined;
87187 }
87188 ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
87189 }
87190 function emitDetachedCommentsAndUpdateCommentsInfo(range) {
87191 var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
87192 if (currentDetachedCommentInfo) {
87193 if (detachedCommentsInfo) {
87194 detachedCommentsInfo.push(currentDetachedCommentInfo);
87195 }
87196 else {
87197 detachedCommentsInfo = [currentDetachedCommentInfo];
87198 }
87199 }
87200 }
87201 function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
87202 if (!shouldWriteComment(currentSourceFile.text, commentPos))
87203 return;
87204 emitPos(commentPos);
87205 ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
87206 emitPos(commentEnd);
87207 }
87208 /**
87209 * Determine if the given comment is a triple-slash
87210 *
87211 * @return true if the comment is a triple-slash comment else false
87212 */
87213 function isTripleSlashComment(commentPos, commentEnd) {
87214 return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
87215 }
87216 // Source Maps
87217 function getParsedSourceMap(node) {
87218 if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
87219 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
87220 }
87221 return node.parsedSourceMap || undefined;
87222 }
87223 function pipelineEmitWithSourceMap(hint, node) {
87224 var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
87225 if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
87226 pipelinePhase(hint, node);
87227 }
87228 else if (ts.isUnparsedNode(node)) {
87229 var parsed = getParsedSourceMap(node.parent);
87230 if (parsed && sourceMapGenerator) {
87231 sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
87232 }
87233 pipelinePhase(hint, node);
87234 }
87235 else {
87236 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
87237 var emitFlags = ts.getEmitFlags(node);
87238 if (node.kind !== 312 /* NotEmittedStatement */
87239 && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
87240 && pos >= 0) {
87241 emitSourcePos(source, skipSourceTrivia(source, pos));
87242 }
87243 if (emitFlags & 64 /* NoNestedSourceMaps */) {
87244 sourceMapsDisabled = true;
87245 pipelinePhase(hint, node);
87246 sourceMapsDisabled = false;
87247 }
87248 else {
87249 pipelinePhase(hint, node);
87250 }
87251 if (node.kind !== 312 /* NotEmittedStatement */
87252 && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
87253 && end >= 0) {
87254 emitSourcePos(source, end);
87255 }
87256 }
87257 }
87258 /**
87259 * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
87260 */
87261 function skipSourceTrivia(source, pos) {
87262 return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
87263 }
87264 /**
87265 * Emits a mapping.
87266 *
87267 * If the position is synthetic (undefined or a negative value), no mapping will be
87268 * created.
87269 *
87270 * @param pos The position.
87271 */
87272 function emitPos(pos) {
87273 if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
87274 return;
87275 }
87276 var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
87277 sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter,
87278 /*nameIndex*/ undefined);
87279 }
87280 function emitSourcePos(source, pos) {
87281 if (source !== sourceMapSource) {
87282 var savedSourceMapSource = sourceMapSource;
87283 setSourceMapSource(source);
87284 emitPos(pos);
87285 setSourceMapSource(savedSourceMapSource);
87286 }
87287 else {
87288 emitPos(pos);
87289 }
87290 }
87291 /**
87292 * Emits a token of a node with possible leading and trailing source maps.
87293 *
87294 * @param node The node containing the token.
87295 * @param token The token to emit.
87296 * @param tokenStartPos The start pos of the token.
87297 * @param emitCallback The callback used to emit the token.
87298 */
87299 function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
87300 if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
87301 return emitCallback(token, writer, tokenPos);
87302 }
87303 var emitNode = node && node.emitNode;
87304 var emitFlags = emitNode && emitNode.flags || 0 /* None */;
87305 var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
87306 var source = range && range.source || sourceMapSource;
87307 tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
87308 if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
87309 emitSourcePos(source, tokenPos);
87310 }
87311 tokenPos = emitCallback(token, writer, tokenPos);
87312 if (range)
87313 tokenPos = range.end;
87314 if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
87315 emitSourcePos(source, tokenPos);
87316 }
87317 return tokenPos;
87318 }
87319 function setSourceMapSource(source) {
87320 if (sourceMapsDisabled) {
87321 return;
87322 }
87323 sourceMapSource = source;
87324 if (isJsonSourceMapSource(source)) {
87325 return;
87326 }
87327 sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
87328 if (printerOptions.inlineSources) {
87329 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
87330 }
87331 }
87332 function isJsonSourceMapSource(sourceFile) {
87333 return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
87334 }
87335 }
87336 ts.createPrinter = createPrinter;
87337 function createBracketsMap() {
87338 var brackets = [];
87339 brackets[1024 /* Braces */] = ["{", "}"];
87340 brackets[2048 /* Parenthesis */] = ["(", ")"];
87341 brackets[4096 /* AngleBrackets */] = ["<", ">"];
87342 brackets[8192 /* SquareBrackets */] = ["[", "]"];
87343 return brackets;
87344 }
87345 function getOpeningBracket(format) {
87346 return brackets[format & 15360 /* BracketsMask */][0];
87347 }
87348 function getClosingBracket(format) {
87349 return brackets[format & 15360 /* BracketsMask */][1];
87350 }
87351 // Flags enum to track count of temp variables and a few dedicated names
87352 var TempFlags;
87353 (function (TempFlags) {
87354 TempFlags[TempFlags["Auto"] = 0] = "Auto";
87355 TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
87356 TempFlags[TempFlags["_i"] = 268435456] = "_i";
87357 })(TempFlags || (TempFlags = {}));
87358})(ts || (ts = {}));
87359/* @internal */
87360var ts;
87361(function (ts) {
87362 function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
87363 if (!host.getDirectories || !host.readDirectory) {
87364 return undefined;
87365 }
87366 var cachedReadDirectoryResult = ts.createMap();
87367 var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
87368 return {
87369 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
87370 fileExists: fileExists,
87371 readFile: function (path, encoding) { return host.readFile(path, encoding); },
87372 directoryExists: host.directoryExists && directoryExists,
87373 getDirectories: getDirectories,
87374 readDirectory: readDirectory,
87375 createDirectory: host.createDirectory && createDirectory,
87376 writeFile: host.writeFile && writeFile,
87377 addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
87378 addOrDeleteFile: addOrDeleteFile,
87379 clearCache: clearCache,
87380 realpath: host.realpath && realpath
87381 };
87382 function toPath(fileName) {
87383 return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
87384 }
87385 function getCachedFileSystemEntries(rootDirPath) {
87386 return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
87387 }
87388 function getCachedFileSystemEntriesForBaseDir(path) {
87389 return getCachedFileSystemEntries(ts.getDirectoryPath(path));
87390 }
87391 function getBaseNameOfFileName(fileName) {
87392 return ts.getBaseFileName(ts.normalizePath(fileName));
87393 }
87394 function createCachedFileSystemEntries(rootDir, rootDirPath) {
87395 var resultFromHost = {
87396 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
87397 directories: host.getDirectories(rootDir) || []
87398 };
87399 cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
87400 return resultFromHost;
87401 }
87402 /**
87403 * If the readDirectory result was already cached, it returns that
87404 * Otherwise gets result from host and caches it.
87405 * The host request is done under try catch block to avoid caching incorrect result
87406 */
87407 function tryReadDirectory(rootDir, rootDirPath) {
87408 rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
87409 var cachedResult = getCachedFileSystemEntries(rootDirPath);
87410 if (cachedResult) {
87411 return cachedResult;
87412 }
87413 try {
87414 return createCachedFileSystemEntries(rootDir, rootDirPath);
87415 }
87416 catch (_e) {
87417 // If there is exception to read directories, dont cache the result and direct the calls to host
87418 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
87419 return undefined;
87420 }
87421 }
87422 function fileNameEqual(name1, name2) {
87423 return getCanonicalFileName(name1) === getCanonicalFileName(name2);
87424 }
87425 function hasEntry(entries, name) {
87426 return ts.some(entries, function (file) { return fileNameEqual(file, name); });
87427 }
87428 function updateFileSystemEntry(entries, baseName, isValid) {
87429 if (hasEntry(entries, baseName)) {
87430 if (!isValid) {
87431 return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
87432 }
87433 }
87434 else if (isValid) {
87435 return entries.push(baseName);
87436 }
87437 }
87438 function writeFile(fileName, data, writeByteOrderMark) {
87439 var path = toPath(fileName);
87440 var result = getCachedFileSystemEntriesForBaseDir(path);
87441 if (result) {
87442 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
87443 }
87444 return host.writeFile(fileName, data, writeByteOrderMark);
87445 }
87446 function fileExists(fileName) {
87447 var path = toPath(fileName);
87448 var result = getCachedFileSystemEntriesForBaseDir(path);
87449 return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
87450 host.fileExists(fileName);
87451 }
87452 function directoryExists(dirPath) {
87453 var path = toPath(dirPath);
87454 return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
87455 }
87456 function createDirectory(dirPath) {
87457 var path = toPath(dirPath);
87458 var result = getCachedFileSystemEntriesForBaseDir(path);
87459 var baseFileName = getBaseNameOfFileName(dirPath);
87460 if (result) {
87461 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
87462 }
87463 host.createDirectory(dirPath);
87464 }
87465 function getDirectories(rootDir) {
87466 var rootDirPath = toPath(rootDir);
87467 var result = tryReadDirectory(rootDir, rootDirPath);
87468 if (result) {
87469 return result.directories.slice();
87470 }
87471 return host.getDirectories(rootDir);
87472 }
87473 function readDirectory(rootDir, extensions, excludes, includes, depth) {
87474 var rootDirPath = toPath(rootDir);
87475 var result = tryReadDirectory(rootDir, rootDirPath);
87476 if (result) {
87477 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
87478 }
87479 return host.readDirectory(rootDir, extensions, excludes, includes, depth);
87480 function getFileSystemEntries(dir) {
87481 var path = toPath(dir);
87482 if (path === rootDirPath) {
87483 return result;
87484 }
87485 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
87486 }
87487 }
87488 function realpath(s) {
87489 return host.realpath ? host.realpath(s) : s;
87490 }
87491 function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
87492 var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
87493 if (existingResult) {
87494 // Just clear the cache for now
87495 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
87496 clearCache();
87497 return undefined;
87498 }
87499 var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
87500 if (!parentResult) {
87501 return undefined;
87502 }
87503 // This was earlier a file (hence not in cached directory contents)
87504 // or we never cached the directory containing it
87505 if (!host.directoryExists) {
87506 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
87507 clearCache();
87508 return undefined;
87509 }
87510 var baseName = getBaseNameOfFileName(fileOrDirectory);
87511 var fsQueryResult = {
87512 fileExists: host.fileExists(fileOrDirectoryPath),
87513 directoryExists: host.directoryExists(fileOrDirectoryPath)
87514 };
87515 if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
87516 // Folder added or removed, clear the cache instead of updating the folder and its structure
87517 clearCache();
87518 }
87519 else {
87520 // No need to update the directory structure, just files
87521 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
87522 }
87523 return fsQueryResult;
87524 }
87525 function addOrDeleteFile(fileName, filePath, eventKind) {
87526 if (eventKind === ts.FileWatcherEventKind.Changed) {
87527 return;
87528 }
87529 var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
87530 if (parentResult) {
87531 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
87532 }
87533 }
87534 function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
87535 updateFileSystemEntry(parentResult.files, baseName, fileExists);
87536 }
87537 function clearCache() {
87538 cachedReadDirectoryResult.clear();
87539 }
87540 }
87541 ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
87542 var ConfigFileProgramReloadLevel;
87543 (function (ConfigFileProgramReloadLevel) {
87544 ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
87545 /** Update the file name list from the disk */
87546 ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
87547 /** Reload completely by re-reading contents of config file from disk and updating program */
87548 ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
87549 })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
87550 /**
87551 * Updates the existing missing file watches with the new set of missing files after new program is created
87552 */
87553 function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
87554 var missingFilePaths = program.getMissingFilePaths();
87555 var newMissingFilePathMap = ts.arrayToSet(missingFilePaths);
87556 // Update the missing file paths watcher
87557 ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
87558 // Watch the missing files
87559 createNewValue: createMissingFileWatch,
87560 // Files that are no longer missing (e.g. because they are no longer required)
87561 // should no longer be watched.
87562 onDeleteValue: ts.closeFileWatcher
87563 });
87564 }
87565 ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
87566 /**
87567 * Updates the existing wild card directory watches with the new set of wild card directories from the config file
87568 * after new program is created because the config file was reloaded or program was created first time from the config file
87569 * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
87570 * as wildcard directories wont change unless reloading config file
87571 */
87572 function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
87573 ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
87574 // Create new watch and recursive info
87575 createNewValue: createWildcardDirectoryWatcher,
87576 // Close existing watch thats not needed any more
87577 onDeleteValue: closeFileWatcherOf,
87578 // Close existing watch that doesnt match in the flags
87579 onExistingValue: updateWildcardDirectoryWatcher
87580 });
87581 function createWildcardDirectoryWatcher(directory, flags) {
87582 // Create new watch and recursive info
87583 return {
87584 watcher: watchDirectory(directory, flags),
87585 flags: flags
87586 };
87587 }
87588 function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
87589 // Watcher needs to be updated if the recursive flags dont match
87590 if (existingWatcher.flags === flags) {
87591 return;
87592 }
87593 existingWatcher.watcher.close();
87594 existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
87595 }
87596 }
87597 ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
87598 function isEmittedFileOfProgram(program, file) {
87599 if (!program) {
87600 return false;
87601 }
87602 return program.isEmittedFile(file);
87603 }
87604 ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
87605 var WatchLogLevel;
87606 (function (WatchLogLevel) {
87607 WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
87608 WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
87609 WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
87610 })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
87611 function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
87612 return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
87613 }
87614 ts.getWatchFactory = getWatchFactory;
87615 function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
87616 var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
87617 var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
87618 var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
87619 return {
87620 watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) {
87621 return createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
87622 },
87623 watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) {
87624 return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
87625 },
87626 watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) {
87627 return createDirectoryWatcher(host, directory, callback, flags, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
87628 }
87629 };
87630 function watchFilePath(host, file, callback, pollingInterval, path) {
87631 return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval);
87632 }
87633 }
87634 function watchFile(host, file, callback, pollingInterval) {
87635 return host.watchFile(file, callback, pollingInterval);
87636 }
87637 function watchDirectory(host, directory, callback, flags) {
87638 return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0);
87639 }
87640 function getCreateFileWatcher(watchLogLevel, addWatch) {
87641 switch (watchLogLevel) {
87642 case WatchLogLevel.None:
87643 return addWatch;
87644 case WatchLogLevel.TriggerOnly:
87645 return createFileWatcherWithTriggerLogging;
87646 case WatchLogLevel.Verbose:
87647 return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
87648 }
87649 }
87650 function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
87651 log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo));
87652 var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
87653 return {
87654 close: function () {
87655 log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo));
87656 watcher.close();
87657 }
87658 };
87659 }
87660 function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
87661 var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo);
87662 log(watchInfo);
87663 var start = ts.timestamp();
87664 var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
87665 var elapsed = ts.timestamp() - start;
87666 log("Elapsed:: " + elapsed + "ms " + watchInfo);
87667 return {
87668 close: function () {
87669 var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo);
87670 log(watchInfo);
87671 var start = ts.timestamp();
87672 watcher.close();
87673 var elapsed = ts.timestamp() - start;
87674 log("Elapsed:: " + elapsed + "ms " + watchInfo);
87675 }
87676 };
87677 }
87678 function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
87679 return addWatch(host, file, function (fileName, cbOptional) {
87680 var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo);
87681 log(triggerredInfo);
87682 var start = ts.timestamp();
87683 cb(fileName, cbOptional, passThrough);
87684 var elapsed = ts.timestamp() - start;
87685 log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
87686 }, flags);
87687 }
87688 function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) {
87689 return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
87690 }
87691 function closeFileWatcherOf(objWithWatcher) {
87692 objWithWatcher.watcher.close();
87693 }
87694 ts.closeFileWatcherOf = closeFileWatcherOf;
87695})(ts || (ts = {}));
87696var ts;
87697(function (ts) {
87698 var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/;
87699 function findConfigFile(searchPath, fileExists, configName) {
87700 if (configName === void 0) { configName = "tsconfig.json"; }
87701 return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
87702 var fileName = ts.combinePaths(ancestor, configName);
87703 return fileExists(fileName) ? fileName : undefined;
87704 });
87705 }
87706 ts.findConfigFile = findConfigFile;
87707 function resolveTripleslashReference(moduleName, containingFile) {
87708 var basePath = ts.getDirectoryPath(containingFile);
87709 var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
87710 return ts.normalizePath(referencedFileName);
87711 }
87712 ts.resolveTripleslashReference = resolveTripleslashReference;
87713 /* @internal */
87714 function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
87715 var commonPathComponents;
87716 var failed = ts.forEach(fileNames, function (sourceFile) {
87717 // Each file contributes into common source file path
87718 var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
87719 sourcePathComponents.pop(); // The base file name is not part of the common directory path
87720 if (!commonPathComponents) {
87721 // first file
87722 commonPathComponents = sourcePathComponents;
87723 return;
87724 }
87725 var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
87726 for (var i = 0; i < n; i++) {
87727 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
87728 if (i === 0) {
87729 // Failed to find any common path component
87730 return true;
87731 }
87732 // New common path found that is 0 -> i-1
87733 commonPathComponents.length = i;
87734 break;
87735 }
87736 }
87737 // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
87738 if (sourcePathComponents.length < commonPathComponents.length) {
87739 commonPathComponents.length = sourcePathComponents.length;
87740 }
87741 });
87742 // A common path can not be found when paths span multiple drives on windows, for example
87743 if (failed) {
87744 return "";
87745 }
87746 if (!commonPathComponents) { // Can happen when all input files are .d.ts files
87747 return currentDirectory;
87748 }
87749 return ts.getPathFromPathComponents(commonPathComponents);
87750 }
87751 ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
87752 function createCompilerHost(options, setParentNodes) {
87753 return createCompilerHostWorker(options, setParentNodes);
87754 }
87755 ts.createCompilerHost = createCompilerHost;
87756 /*@internal*/
87757 // TODO(shkamat): update this after reworking ts build API
87758 function createCompilerHostWorker(options, setParentNodes, system) {
87759 if (system === void 0) { system = ts.sys; }
87760 var existingDirectories = ts.createMap();
87761 var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
87762 function getSourceFile(fileName, languageVersion, onError) {
87763 var text;
87764 try {
87765 ts.performance.mark("beforeIORead");
87766 text = compilerHost.readFile(fileName);
87767 ts.performance.mark("afterIORead");
87768 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
87769 }
87770 catch (e) {
87771 if (onError) {
87772 onError(e.message);
87773 }
87774 text = "";
87775 }
87776 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
87777 }
87778 function directoryExists(directoryPath) {
87779 if (existingDirectories.has(directoryPath)) {
87780 return true;
87781 }
87782 if (system.directoryExists(directoryPath)) {
87783 existingDirectories.set(directoryPath, true);
87784 return true;
87785 }
87786 return false;
87787 }
87788 function ensureDirectoriesExist(directoryPath) {
87789 if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
87790 var parentDirectory = ts.getDirectoryPath(directoryPath);
87791 ensureDirectoriesExist(parentDirectory);
87792 if (compilerHost.createDirectory) {
87793 compilerHost.createDirectory(directoryPath);
87794 }
87795 else {
87796 system.createDirectory(directoryPath);
87797 }
87798 }
87799 }
87800 var outputFingerprints;
87801 function writeFileIfUpdated(fileName, data, writeByteOrderMark) {
87802 if (!outputFingerprints) {
87803 outputFingerprints = ts.createMap();
87804 }
87805 var hash = system.createHash(data); // TODO: GH#18217
87806 var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217
87807 if (mtimeBefore) {
87808 var fingerprint = outputFingerprints.get(fileName);
87809 // If output has not been changed, and the file has no external modification
87810 if (fingerprint &&
87811 fingerprint.byteOrderMark === writeByteOrderMark &&
87812 fingerprint.hash === hash &&
87813 fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
87814 return;
87815 }
87816 }
87817 system.writeFile(fileName, data, writeByteOrderMark);
87818 var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217
87819 outputFingerprints.set(fileName, {
87820 hash: hash,
87821 byteOrderMark: writeByteOrderMark,
87822 mtime: mtimeAfter
87823 });
87824 }
87825 function writeFile(fileName, data, writeByteOrderMark, onError) {
87826 try {
87827 ts.performance.mark("beforeIOWrite");
87828 ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName)));
87829 if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) {
87830 writeFileIfUpdated(fileName, data, writeByteOrderMark);
87831 }
87832 else {
87833 system.writeFile(fileName, data, writeByteOrderMark);
87834 }
87835 ts.performance.mark("afterIOWrite");
87836 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
87837 }
87838 catch (e) {
87839 if (onError) {
87840 onError(e.message);
87841 }
87842 }
87843 }
87844 function getDefaultLibLocation() {
87845 return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
87846 }
87847 var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
87848 var realpath = system.realpath && (function (path) { return system.realpath(path); });
87849 var compilerHost = {
87850 getSourceFile: getSourceFile,
87851 getDefaultLibLocation: getDefaultLibLocation,
87852 getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
87853 writeFile: writeFile,
87854 getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
87855 useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
87856 getCanonicalFileName: getCanonicalFileName,
87857 getNewLine: function () { return newLine; },
87858 fileExists: function (fileName) { return system.fileExists(fileName); },
87859 readFile: function (fileName) { return system.readFile(fileName); },
87860 trace: function (s) { return system.write(s + newLine); },
87861 directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
87862 getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
87863 getDirectories: function (path) { return system.getDirectories(path); },
87864 realpath: realpath,
87865 readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
87866 createDirectory: function (d) { return system.createDirectory(d); }
87867 };
87868 return compilerHost;
87869 }
87870 ts.createCompilerHostWorker = createCompilerHostWorker;
87871 /*@internal*/
87872 function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
87873 var originalReadFile = host.readFile;
87874 var originalFileExists = host.fileExists;
87875 var originalDirectoryExists = host.directoryExists;
87876 var originalCreateDirectory = host.createDirectory;
87877 var originalWriteFile = host.writeFile;
87878 var readFileCache = ts.createMap();
87879 var fileExistsCache = ts.createMap();
87880 var directoryExistsCache = ts.createMap();
87881 var sourceFileCache = ts.createMap();
87882 var readFileWithCache = function (fileName) {
87883 var key = toPath(fileName);
87884 var value = readFileCache.get(key);
87885 if (value !== undefined)
87886 return value !== false ? value : undefined;
87887 return setReadFileCache(key, fileName);
87888 };
87889 var setReadFileCache = function (key, fileName) {
87890 var newValue = originalReadFile.call(host, fileName);
87891 readFileCache.set(key, newValue !== undefined ? newValue : false);
87892 return newValue;
87893 };
87894 host.readFile = function (fileName) {
87895 var key = toPath(fileName);
87896 var value = readFileCache.get(key);
87897 if (value !== undefined)
87898 return value !== false ? value : undefined; // could be .d.ts from output
87899 // Cache json or buildInfo
87900 if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
87901 return originalReadFile.call(host, fileName);
87902 }
87903 return setReadFileCache(key, fileName);
87904 };
87905 var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
87906 var key = toPath(fileName);
87907 var value = sourceFileCache.get(key);
87908 if (value)
87909 return value;
87910 var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
87911 if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
87912 sourceFileCache.set(key, sourceFile);
87913 }
87914 return sourceFile;
87915 } : undefined;
87916 // fileExists for any kind of extension
87917 host.fileExists = function (fileName) {
87918 var key = toPath(fileName);
87919 var value = fileExistsCache.get(key);
87920 if (value !== undefined)
87921 return value;
87922 var newValue = originalFileExists.call(host, fileName);
87923 fileExistsCache.set(key, !!newValue);
87924 return newValue;
87925 };
87926 if (originalWriteFile) {
87927 host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
87928 var key = toPath(fileName);
87929 fileExistsCache.delete(key);
87930 var value = readFileCache.get(key);
87931 if (value !== undefined && value !== data) {
87932 readFileCache.delete(key);
87933 sourceFileCache.delete(key);
87934 }
87935 else if (getSourceFileWithCache) {
87936 var sourceFile = sourceFileCache.get(key);
87937 if (sourceFile && sourceFile.text !== data) {
87938 sourceFileCache.delete(key);
87939 }
87940 }
87941 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
87942 };
87943 }
87944 // directoryExists
87945 if (originalDirectoryExists && originalCreateDirectory) {
87946 host.directoryExists = function (directory) {
87947 var key = toPath(directory);
87948 var value = directoryExistsCache.get(key);
87949 if (value !== undefined)
87950 return value;
87951 var newValue = originalDirectoryExists.call(host, directory);
87952 directoryExistsCache.set(key, !!newValue);
87953 return newValue;
87954 };
87955 host.createDirectory = function (directory) {
87956 var key = toPath(directory);
87957 directoryExistsCache.delete(key);
87958 originalCreateDirectory.call(host, directory);
87959 };
87960 }
87961 return {
87962 originalReadFile: originalReadFile,
87963 originalFileExists: originalFileExists,
87964 originalDirectoryExists: originalDirectoryExists,
87965 originalCreateDirectory: originalCreateDirectory,
87966 originalWriteFile: originalWriteFile,
87967 getSourceFileWithCache: getSourceFileWithCache,
87968 readFileWithCache: readFileWithCache
87969 };
87970 }
87971 ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
87972 function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
87973 var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
87974 if (ts.getEmitDeclarations(program.getCompilerOptions())) {
87975 ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
87976 }
87977 return ts.sortAndDeduplicateDiagnostics(diagnostics);
87978 }
87979 ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
87980 function formatDiagnostics(diagnostics, host) {
87981 var output = "";
87982 for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
87983 var diagnostic = diagnostics_2[_i];
87984 output += formatDiagnostic(diagnostic, host);
87985 }
87986 return output;
87987 }
87988 ts.formatDiagnostics = formatDiagnostics;
87989 function formatDiagnostic(diagnostic, host) {
87990 var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
87991 if (diagnostic.file) {
87992 var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
87993 var fileName = diagnostic.file.fileName;
87994 var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
87995 return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
87996 }
87997 return errorMessage;
87998 }
87999 ts.formatDiagnostic = formatDiagnostic;
88000 /** @internal */
88001 var ForegroundColorEscapeSequences;
88002 (function (ForegroundColorEscapeSequences) {
88003 ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
88004 ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
88005 ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
88006 ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
88007 ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
88008 })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
88009 var gutterStyleSequence = "\u001b[7m";
88010 var gutterSeparator = " ";
88011 var resetEscapeSequence = "\u001b[0m";
88012 var ellipsis = "...";
88013 var halfIndent = " ";
88014 var indent = " ";
88015 function getCategoryFormat(category) {
88016 switch (category) {
88017 case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
88018 case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
88019 case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
88020 case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
88021 }
88022 }
88023 /** @internal */
88024 function formatColorAndReset(text, formatStyle) {
88025 return formatStyle + text + resetEscapeSequence;
88026 }
88027 ts.formatColorAndReset = formatColorAndReset;
88028 function padLeft(s, length) {
88029 while (s.length < length) {
88030 s = " " + s;
88031 }
88032 return s;
88033 }
88034 function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
88035 var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
88036 var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
88037 var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
88038 var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
88039 var gutterWidth = (lastLine + 1 + "").length;
88040 if (hasMoreThanFiveLines) {
88041 gutterWidth = Math.max(ellipsis.length, gutterWidth);
88042 }
88043 var context = "";
88044 for (var i = firstLine; i <= lastLine; i++) {
88045 context += host.getNewLine();
88046 // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
88047 // so we'll skip ahead to the second-to-last line.
88048 if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
88049 context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
88050 i = lastLine - 1;
88051 }
88052 var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
88053 var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
88054 var lineContent = file.text.slice(lineStart, lineEnd);
88055 lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
88056 lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
88057 // Output the gutter and the actual contents of the line.
88058 context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
88059 context += lineContent + host.getNewLine();
88060 // Output the gutter and the error span for the line using tildes.
88061 context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
88062 context += squiggleColor;
88063 if (i === firstLine) {
88064 // If we're on the last line, then limit it to the last character of the last line.
88065 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
88066 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
88067 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
88068 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
88069 }
88070 else if (i === lastLine) {
88071 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
88072 }
88073 else {
88074 // Squiggle the entire line.
88075 context += lineContent.replace(/./g, "~");
88076 }
88077 context += resetEscapeSequence;
88078 }
88079 return context;
88080 }
88081 /* @internal */
88082 function formatLocation(file, start, host, color) {
88083 if (color === void 0) { color = formatColorAndReset; }
88084 var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
88085 var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
88086 var output = "";
88087 output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
88088 output += ":";
88089 output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
88090 output += ":";
88091 output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
88092 return output;
88093 }
88094 ts.formatLocation = formatLocation;
88095 function formatDiagnosticsWithColorAndContext(diagnostics, host) {
88096 var output = "";
88097 for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
88098 var diagnostic = diagnostics_3[_i];
88099 if (diagnostic.file) {
88100 var file = diagnostic.file, start = diagnostic.start;
88101 output += formatLocation(file, start, host); // TODO: GH#18217
88102 output += " - ";
88103 }
88104 output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
88105 output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
88106 output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
88107 if (diagnostic.file) {
88108 output += host.getNewLine();
88109 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
88110 if (diagnostic.relatedInformation) {
88111 output += host.getNewLine();
88112 for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
88113 var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText;
88114 if (file) {
88115 output += host.getNewLine();
88116 output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
88117 output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
88118 }
88119 output += host.getNewLine();
88120 output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
88121 }
88122 }
88123 }
88124 output += host.getNewLine();
88125 }
88126 return output;
88127 }
88128 ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
88129 function flattenDiagnosticMessageText(messageText, newLine) {
88130 if (ts.isString(messageText)) {
88131 return messageText;
88132 }
88133 else {
88134 var diagnosticChain = messageText;
88135 var result = "";
88136 var indent_1 = 0;
88137 while (diagnosticChain) {
88138 if (indent_1) {
88139 result += newLine;
88140 for (var i = 0; i < indent_1; i++) {
88141 result += " ";
88142 }
88143 }
88144 result += diagnosticChain.messageText;
88145 indent_1++;
88146 diagnosticChain = diagnosticChain.next;
88147 }
88148 return result;
88149 }
88150 }
88151 ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
88152 function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
88153 if (names.length === 0) {
88154 return [];
88155 }
88156 var resolutions = [];
88157 var cache = ts.createMap();
88158 for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
88159 var name = names_1[_i];
88160 var result = void 0;
88161 if (cache.has(name)) {
88162 result = cache.get(name);
88163 }
88164 else {
88165 cache.set(name, result = loader(name, containingFile, redirectedReference));
88166 }
88167 resolutions.push(result);
88168 }
88169 return resolutions;
88170 }
88171 /**
88172 * Determines if program structure is upto date or needs to be recreated
88173 */
88174 /* @internal */
88175 function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
88176 // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
88177 if (!program || hasChangedAutomaticTypeDirectiveNames) {
88178 return false;
88179 }
88180 // If number of files in the program do not match, it is not up-to-date
88181 if (program.getRootFileNames().length !== rootFileNames.length) {
88182 return false;
88183 }
88184 var seenResolvedRefs;
88185 // If project references dont match
88186 if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
88187 return false;
88188 }
88189 // If any file is not up-to-date, then the whole program is not up-to-date
88190 if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
88191 return false;
88192 }
88193 // If any of the missing file paths are now created
88194 if (program.getMissingFilePaths().some(fileExists)) {
88195 return false;
88196 }
88197 var currentOptions = program.getCompilerOptions();
88198 // If the compilation settings do no match, then the program is not up-to-date
88199 if (!ts.compareDataObjects(currentOptions, newOptions)) {
88200 return false;
88201 }
88202 // If everything matches but the text of config file is changed,
88203 // error locations can change for program options, so update the program
88204 if (currentOptions.configFile && newOptions.configFile) {
88205 return currentOptions.configFile.text === newOptions.configFile.text;
88206 }
88207 return true;
88208 function sourceFileNotUptoDate(sourceFile) {
88209 return !sourceFileVersionUptoDate(sourceFile) ||
88210 hasInvalidatedResolution(sourceFile.path);
88211 }
88212 function sourceFileVersionUptoDate(sourceFile) {
88213 return sourceFile.version === getSourceVersion(sourceFile.resolvedPath);
88214 }
88215 function projectReferenceUptoDate(oldRef, newRef, index) {
88216 if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
88217 return false;
88218 }
88219 return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
88220 }
88221 function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
88222 if (oldResolvedRef) {
88223 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
88224 // Assume true
88225 return true;
88226 }
88227 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
88228 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
88229 return false;
88230 }
88231 // Add to seen before checking the referenced paths of this config file
88232 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
88233 // If child project references are upto date, this project reference is uptodate
88234 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
88235 return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
88236 });
88237 }
88238 // In old program, not able to resolve project reference path,
88239 // so if config file doesnt exist, it is uptodate.
88240 return !fileExists(resolveProjectReferencePath(oldRef));
88241 }
88242 }
88243 ts.isProgramUptoDate = isProgramUptoDate;
88244 function getConfigFileParsingDiagnostics(configFileParseResult) {
88245 return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) :
88246 configFileParseResult.errors;
88247 }
88248 ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
88249 /**
88250 * Determine if source file needs to be re-created even if its text hasn't changed
88251 */
88252 function shouldProgramCreateNewSourceFiles(program, newOptions) {
88253 if (!program)
88254 return false;
88255 // If any compiler options change, we can't reuse old source file even if version match
88256 // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
88257 var oldOptions = program.getCompilerOptions();
88258 return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
88259 return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
88260 });
88261 }
88262 function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
88263 return {
88264 rootNames: rootNames,
88265 options: options,
88266 host: host,
88267 oldProgram: oldProgram,
88268 configFileParsingDiagnostics: configFileParsingDiagnostics
88269 };
88270 }
88271 function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
88272 var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
88273 var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
88274 var oldProgram = createProgramOptions.oldProgram;
88275 var program;
88276 var processingDefaultLibFiles;
88277 var processingOtherFiles;
88278 var files;
88279 var commonSourceDirectory;
88280 var diagnosticsProducingTypeChecker;
88281 var noDiagnosticsTypeChecker;
88282 var classifiableNames;
88283 var ambientModuleNameToUnmodifiedFileName = ts.createMap();
88284 var cachedSemanticDiagnosticsForFile = {};
88285 var cachedDeclarationDiagnosticsForFile = {};
88286 var resolvedTypeReferenceDirectives = ts.createMap();
88287 var fileProcessingDiagnostics = ts.createDiagnosticCollection();
88288 // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
88289 // This works as imported modules are discovered recursively in a depth first manner, specifically:
88290 // - For each root file, findSourceFile is called.
88291 // - This calls processImportedModules for each module imported in the source file.
88292 // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
88293 // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
88294 // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
88295 var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
88296 var currentNodeModulesDepth = 0;
88297 // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
88298 // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
88299 var modulesWithElidedImports = ts.createMap();
88300 // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
88301 var sourceFilesFoundSearchingNodeModules = ts.createMap();
88302 ts.performance.mark("beforeProgram");
88303 var host = createProgramOptions.host || createCompilerHost(options);
88304 var configParsingHost = parseConfigHostFromCompilerHostLike(host);
88305 var skipDefaultLib = options.noLib;
88306 var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
88307 var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
88308 var programDiagnostics = ts.createDiagnosticCollection();
88309 var currentDirectory = host.getCurrentDirectory();
88310 var supportedExtensions = ts.getSupportedExtensions(options);
88311 var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
88312 // Map storing if there is emit blocking diagnostics for given input
88313 var hasEmitBlockingDiagnostics = ts.createMap();
88314 var _compilerOptionsObjectLiteralSyntax;
88315 var moduleResolutionCache;
88316 var resolveModuleNamesWorker;
88317 var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
88318 if (host.resolveModuleNames) {
88319 resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(function (resolved) {
88320 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
88321 if (!resolved || resolved.extension !== undefined) {
88322 return resolved;
88323 }
88324 var withExtension = ts.clone(resolved);
88325 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
88326 return withExtension;
88327 }); };
88328 }
88329 else {
88330 moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); });
88331 var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
88332 resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
88333 }
88334 var resolveTypeReferenceDirectiveNamesWorker;
88335 if (host.resolveTypeReferenceDirectives) {
88336 resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); };
88337 }
88338 else {
88339 var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
88340 resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
88341 }
88342 // Map from a stringified PackageId to the source file with that id.
88343 // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
88344 // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
88345 var packageIdToSourceFile = ts.createMap();
88346 // Maps from a SourceFile's `.path` to the name of the package it was imported with.
88347 var sourceFileToPackageName = ts.createMap();
88348 // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
88349 var redirectTargetsMap = ts.createMultiMap();
88350 /**
88351 * map with
88352 * - SourceFile if present
88353 * - false if sourceFile missing for source of project reference redirect
88354 * - undefined otherwise
88355 */
88356 var filesByName = ts.createMap();
88357 var missingFilePaths;
88358 // stores 'filename -> file association' ignoring case
88359 // used to track cases when two file names differ only in casing
88360 var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
88361 // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
88362 var resolvedProjectReferences;
88363 var projectReferenceRedirects;
88364 var mapFromFileToProjectReferenceRedirects;
88365 var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
88366 var structuralIsReused = tryReuseStructureFromOldProgram();
88367 if (structuralIsReused !== 2 /* Completely */) {
88368 processingDefaultLibFiles = [];
88369 processingOtherFiles = [];
88370 if (projectReferences) {
88371 if (!resolvedProjectReferences) {
88372 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
88373 }
88374 if (rootNames.length) {
88375 for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
88376 var parsedRef = resolvedProjectReferences_1[_i];
88377 if (!parsedRef)
88378 continue;
88379 var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
88380 if (out) {
88381 processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
88382 }
88383 else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
88384 for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) {
88385 var fileName = _b[_a];
88386 if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(fileName)) {
88387 processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
88388 }
88389 }
88390 }
88391 }
88392 }
88393 }
88394 ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
88395 // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
88396 var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
88397 if (typeReferences.length) {
88398 // This containingFilename needs to match with the one used in managed-side
88399 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
88400 var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts");
88401 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
88402 for (var i = 0; i < typeReferences.length; i++) {
88403 processTypeReferenceDirective(typeReferences[i], resolutions[i]);
88404 }
88405 }
88406 // Do not process the default library if:
88407 // - The '--noLib' flag is used.
88408 // - A 'no-default-lib' reference comment is encountered in
88409 // processing the root files.
88410 if (rootNames.length && !skipDefaultLib) {
88411 // If '--lib' is not specified, include default library file according to '--target'
88412 // otherwise, using options specified in '--lib' instead of '--target' default library file
88413 var defaultLibraryFileName = getDefaultLibraryFileName();
88414 if (!options.lib && defaultLibraryFileName) {
88415 processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
88416 }
88417 else {
88418 ts.forEach(options.lib, function (libFileName) {
88419 processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
88420 });
88421 }
88422 }
88423 missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
88424 var path = _a[0], file = _a[1];
88425 return file === undefined ? path : undefined;
88426 }));
88427 files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
88428 processingDefaultLibFiles = undefined;
88429 processingOtherFiles = undefined;
88430 }
88431 ts.Debug.assert(!!missingFilePaths);
88432 // Release any files we have acquired in the old program but are
88433 // not part of the new program.
88434 if (oldProgram && host.onReleaseOldSourceFile) {
88435 var oldSourceFiles = oldProgram.getSourceFiles();
88436 for (var _c = 0, oldSourceFiles_1 = oldSourceFiles; _c < oldSourceFiles_1.length; _c++) {
88437 var oldSourceFile = oldSourceFiles_1[_c];
88438 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
88439 if (shouldCreateNewSourceFile || !newFile ||
88440 // old file wasnt redirect but new file is
88441 (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
88442 host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
88443 }
88444 }
88445 oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) {
88446 if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) {
88447 host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
88448 }
88449 });
88450 }
88451 // unconditionally set oldProgram to undefined to prevent it from being captured in closure
88452 oldProgram = undefined;
88453 program = {
88454 getRootFileNames: function () { return rootNames; },
88455 getSourceFile: getSourceFile,
88456 getSourceFileByPath: getSourceFileByPath,
88457 getSourceFiles: function () { return files; },
88458 getMissingFilePaths: function () { return missingFilePaths; },
88459 getCompilerOptions: function () { return options; },
88460 getSyntacticDiagnostics: getSyntacticDiagnostics,
88461 getOptionsDiagnostics: getOptionsDiagnostics,
88462 getGlobalDiagnostics: getGlobalDiagnostics,
88463 getSemanticDiagnostics: getSemanticDiagnostics,
88464 getSuggestionDiagnostics: getSuggestionDiagnostics,
88465 getDeclarationDiagnostics: getDeclarationDiagnostics,
88466 getTypeChecker: getTypeChecker,
88467 getClassifiableNames: getClassifiableNames,
88468 getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
88469 getCommonSourceDirectory: getCommonSourceDirectory,
88470 emit: emit,
88471 getCurrentDirectory: function () { return currentDirectory; },
88472 getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
88473 getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
88474 getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
88475 getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
88476 getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
88477 getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
88478 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
88479 isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
88480 dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
88481 getSourceFileFromReference: getSourceFileFromReference,
88482 getLibFileFromReference: getLibFileFromReference,
88483 sourceFileToPackageName: sourceFileToPackageName,
88484 redirectTargetsMap: redirectTargetsMap,
88485 isEmittedFile: isEmittedFile,
88486 getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
88487 getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
88488 getProjectReferences: getProjectReferences,
88489 getResolvedProjectReferences: getResolvedProjectReferences,
88490 getProjectReferenceRedirect: getProjectReferenceRedirect,
88491 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
88492 getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
88493 forEachResolvedProjectReference: forEachResolvedProjectReference,
88494 emitBuildInfo: emitBuildInfo
88495 };
88496 verifyCompilerOptions();
88497 ts.performance.mark("afterProgram");
88498 ts.performance.measure("Program", "beforeProgram", "afterProgram");
88499 return program;
88500 function compareDefaultLibFiles(a, b) {
88501 return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
88502 }
88503 function getDefaultLibFilePriority(a) {
88504 if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
88505 var basename = ts.getBaseFileName(a.fileName);
88506 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
88507 return 0;
88508 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
88509 var index = ts.libs.indexOf(name);
88510 if (index !== -1)
88511 return index + 1;
88512 }
88513 return ts.libs.length + 2;
88514 }
88515 function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
88516 return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
88517 }
88518 function toPath(fileName) {
88519 return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
88520 }
88521 function getCommonSourceDirectory() {
88522 if (commonSourceDirectory === undefined) {
88523 var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
88524 if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
88525 // If a rootDir is specified use it as the commonSourceDirectory
88526 commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
88527 }
88528 else if (options.composite && options.configFilePath) {
88529 // Project compilations never infer their root from the input source paths
88530 commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
88531 checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
88532 }
88533 else {
88534 commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
88535 }
88536 if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
88537 // Make sure directory path ends with directory separator so this string can directly
88538 // used to replace with "" to get the relative path of the source file and the relative path doesn't
88539 // start with / making it rooted path
88540 commonSourceDirectory += ts.directorySeparator;
88541 }
88542 }
88543 return commonSourceDirectory;
88544 }
88545 function getClassifiableNames() {
88546 if (!classifiableNames) {
88547 // Initialize a checker so that all our files are bound.
88548 getTypeChecker();
88549 classifiableNames = ts.createUnderscoreEscapedMap();
88550 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
88551 var sourceFile = files_2[_i];
88552 ts.copyEntries(sourceFile.classifiableNames, classifiableNames);
88553 }
88554 }
88555 return classifiableNames;
88556 }
88557 function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) {
88558 if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
88559 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
88560 // the best we can do is fallback to the default logic.
88561 return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName));
88562 }
88563 var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile);
88564 if (oldSourceFile !== file && file.resolvedModules) {
88565 // `file` was created for the new program.
88566 //
88567 // We only set `file.resolvedModules` via work from the current function,
88568 // so it is defined iff we already called the current function on `file`.
88569 // That call happened no later than the creation of the `file` object,
88570 // which per above occurred during the current program creation.
88571 // Since we assume the filesystem does not change during program creation,
88572 // it is safe to reuse resolutions from the earlier call.
88573 var result_6 = [];
88574 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
88575 var moduleName = moduleNames_1[_i];
88576 var resolvedModule = file.resolvedModules.get(moduleName);
88577 result_6.push(resolvedModule);
88578 }
88579 return result_6;
88580 }
88581 // At this point, we know at least one of the following hold:
88582 // - file has local declarations for ambient modules
88583 // - old program state is available
88584 // With this information, we can infer some module resolutions without performing resolution.
88585 /** An ordered list of module names for which we cannot recover the resolution. */
88586 var unknownModuleNames;
88587 /**
88588 * The indexing of elements in this list matches that of `moduleNames`.
88589 *
88590 * Before combining results, result[i] is in one of the following states:
88591 * * undefined: needs to be recomputed,
88592 * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
88593 * Needs to be reset to undefined before returning,
88594 * * ResolvedModuleFull instance: can be reused.
88595 */
88596 var result;
88597 var reusedNames;
88598 /** A transient placeholder used to mark predicted resolution in the result list. */
88599 var predictedToResolveToAmbientModuleMarker = {};
88600 for (var i = 0; i < moduleNames.length; i++) {
88601 var moduleName = moduleNames[i];
88602 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
88603 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
88604 var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName);
88605 if (oldResolvedModule) {
88606 if (ts.isTraceEnabled(options, host)) {
88607 ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
88608 }
88609 (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
88610 (reusedNames || (reusedNames = [])).push(moduleName);
88611 continue;
88612 }
88613 }
88614 // We know moduleName resolves to an ambient module provided that moduleName:
88615 // - is in the list of ambient modules locally declared in the current source file.
88616 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
88617 // (so the same module declaration will land in the new program)
88618 var resolvesToAmbientModuleInNonModifiedFile = false;
88619 if (ts.contains(file.ambientModuleNames, moduleName)) {
88620 resolvesToAmbientModuleInNonModifiedFile = true;
88621 if (ts.isTraceEnabled(options, host)) {
88622 ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile);
88623 }
88624 }
88625 else {
88626 resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
88627 }
88628 if (resolvesToAmbientModuleInNonModifiedFile) {
88629 (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
88630 }
88631 else {
88632 // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
88633 (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
88634 }
88635 }
88636 var resolutions = unknownModuleNames && unknownModuleNames.length
88637 ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName))
88638 : ts.emptyArray;
88639 // Combine results of resolutions and predicted results
88640 if (!result) {
88641 // There were no unresolved/ambient resolutions.
88642 ts.Debug.assert(resolutions.length === moduleNames.length);
88643 return resolutions;
88644 }
88645 var j = 0;
88646 for (var i = 0; i < result.length; i++) {
88647 if (result[i]) {
88648 // `result[i]` is either a `ResolvedModuleFull` or a marker.
88649 // If it is the former, we can leave it as is.
88650 if (result[i] === predictedToResolveToAmbientModuleMarker) {
88651 result[i] = undefined; // TODO: GH#18217
88652 }
88653 }
88654 else {
88655 result[i] = resolutions[j];
88656 j++;
88657 }
88658 }
88659 ts.Debug.assert(j === resolutions.length);
88660 return result;
88661 // If we change our policy of rechecking failed lookups on each program create,
88662 // we should adjust the value returned here.
88663 function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
88664 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
88665 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
88666 if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) {
88667 // In the old program, we resolved to an ambient module that was in the same
88668 // place as we expected to find an actual module file.
88669 // We actually need to return 'false' here even though this seems like a 'true' case
88670 // because the normal module resolution algorithm will find this anyway.
88671 return false;
88672 }
88673 // at least one of declarations should come from non-modified source file
88674 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
88675 if (!unmodifiedFile) {
88676 return false;
88677 }
88678 if (ts.isTraceEnabled(options, host)) {
88679 ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
88680 }
88681 return true;
88682 }
88683 }
88684 function canReuseProjectReferences() {
88685 return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) {
88686 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
88687 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
88688 if (oldResolvedRef) {
88689 // Resolved project reference has gone missing or changed
88690 return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
88691 }
88692 else {
88693 // A previously-unresolved reference may be resolved now
88694 return newResolvedRef !== undefined;
88695 }
88696 }, function (oldProjectReferences, parent) {
88697 // If array of references is changed, we cant resue old program
88698 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
88699 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
88700 });
88701 }
88702 function tryReuseStructureFromOldProgram() {
88703 if (!oldProgram) {
88704 return 0 /* Not */;
88705 }
88706 // check properties that can affect structure of the program or module resolution strategy
88707 // if any of these properties has changed - structure cannot be reused
88708 var oldOptions = oldProgram.getCompilerOptions();
88709 if (ts.changesAffectModuleResolution(oldOptions, options)) {
88710 return oldProgram.structureIsReused = 0 /* Not */;
88711 }
88712 ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */)));
88713 // there is an old program, check if we can reuse its structure
88714 var oldRootNames = oldProgram.getRootFileNames();
88715 if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
88716 return oldProgram.structureIsReused = 0 /* Not */;
88717 }
88718 if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
88719 return oldProgram.structureIsReused = 0 /* Not */;
88720 }
88721 // Check if any referenced project tsconfig files are different
88722 if (!canReuseProjectReferences()) {
88723 return oldProgram.structureIsReused = 0 /* Not */;
88724 }
88725 if (projectReferences) {
88726 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
88727 }
88728 // check if program source files has changed in the way that can affect structure of the program
88729 var newSourceFiles = [];
88730 var modifiedSourceFiles = [];
88731 oldProgram.structureIsReused = 2 /* Completely */;
88732 // If the missing file paths are now present, it can change the progam structure,
88733 // and hence cant reuse the structure.
88734 // This is same as how we dont reuse the structure if one of the file from old program is now missing
88735 if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
88736 return oldProgram.structureIsReused = 0 /* Not */;
88737 }
88738 var oldSourceFiles = oldProgram.getSourceFiles();
88739 var SeenPackageName;
88740 (function (SeenPackageName) {
88741 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
88742 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
88743 })(SeenPackageName || (SeenPackageName = {}));
88744 var seenPackageNames = ts.createMap();
88745 for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
88746 var oldSourceFile = oldSourceFiles_2[_i];
88747 var newSourceFile = host.getSourceFileByPath
88748 ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
88749 : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
88750 if (!newSourceFile) {
88751 return oldProgram.structureIsReused = 0 /* Not */;
88752 }
88753 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
88754 var fileChanged = void 0;
88755 if (oldSourceFile.redirectInfo) {
88756 // We got `newSourceFile` by path, so it is actually for the unredirected file.
88757 // This lets us know if the unredirected file has changed. If it has we should break the redirect.
88758 if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
88759 // Underlying file has changed. Might not redirect anymore. Must rebuild program.
88760 return oldProgram.structureIsReused = 0 /* Not */;
88761 }
88762 fileChanged = false;
88763 newSourceFile = oldSourceFile; // Use the redirect.
88764 }
88765 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
88766 // If a redirected-to source file changes, the redirect may be broken.
88767 if (newSourceFile !== oldSourceFile) {
88768 return oldProgram.structureIsReused = 0 /* Not */;
88769 }
88770 fileChanged = false;
88771 }
88772 else {
88773 fileChanged = newSourceFile !== oldSourceFile;
88774 }
88775 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
88776 newSourceFile.path = oldSourceFile.path;
88777 newSourceFile.originalFileName = oldSourceFile.originalFileName;
88778 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
88779 newSourceFile.fileName = oldSourceFile.fileName;
88780 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
88781 if (packageName !== undefined) {
88782 // If there are 2 different source files for the same package name and at least one of them changes,
88783 // they might become redirects. So we must rebuild the program.
88784 var prevKind = seenPackageNames.get(packageName);
88785 var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
88786 if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
88787 return oldProgram.structureIsReused = 0 /* Not */;
88788 }
88789 seenPackageNames.set(packageName, newKind);
88790 }
88791 if (fileChanged) {
88792 // The `newSourceFile` object was created for the new program.
88793 if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
88794 // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
88795 return oldProgram.structureIsReused = 0 /* Not */;
88796 }
88797 if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
88798 // value of no-default-lib has changed
88799 // this will affect if default library is injected into the list of files
88800 oldProgram.structureIsReused = 1 /* SafeModules */;
88801 }
88802 // check tripleslash references
88803 if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
88804 // tripleslash references has changed
88805 oldProgram.structureIsReused = 1 /* SafeModules */;
88806 }
88807 // check imports and module augmentations
88808 collectExternalModuleReferences(newSourceFile);
88809 if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
88810 // imports has changed
88811 oldProgram.structureIsReused = 1 /* SafeModules */;
88812 }
88813 if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
88814 // moduleAugmentations has changed
88815 oldProgram.structureIsReused = 1 /* SafeModules */;
88816 }
88817 if ((oldSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */)) {
88818 // dynamicImport has changed
88819 oldProgram.structureIsReused = 1 /* SafeModules */;
88820 }
88821 if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
88822 // 'types' references has changed
88823 oldProgram.structureIsReused = 1 /* SafeModules */;
88824 }
88825 // tentatively approve the file
88826 modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
88827 }
88828 else if (hasInvalidatedResolution(oldSourceFile.path)) {
88829 // 'module/types' references could have changed
88830 oldProgram.structureIsReused = 1 /* SafeModules */;
88831 // add file to the modified list so that we will resolve it later
88832 modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
88833 }
88834 // if file has passed all checks it should be safe to reuse it
88835 newSourceFiles.push(newSourceFile);
88836 }
88837 if (oldProgram.structureIsReused !== 2 /* Completely */) {
88838 return oldProgram.structureIsReused;
88839 }
88840 var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
88841 for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) {
88842 var oldFile = oldSourceFiles_3[_a];
88843 if (!ts.contains(modifiedFiles, oldFile)) {
88844 for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) {
88845 var moduleName = _c[_b];
88846 ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
88847 }
88848 }
88849 }
88850 // try to verify results of module resolution
88851 for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) {
88852 var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile;
88853 var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory);
88854 if (resolveModuleNamesWorker) {
88855 var moduleNames = getModuleNames(newSourceFile);
88856 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile);
88857 // ensure that module resolution results are still correct
88858 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
88859 if (resolutionsChanged) {
88860 oldProgram.structureIsReused = 1 /* SafeModules */;
88861 newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
88862 }
88863 else {
88864 newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
88865 }
88866 }
88867 if (resolveTypeReferenceDirectiveNamesWorker) {
88868 // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
88869 var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); });
88870 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName));
88871 // ensure that types resolutions are still correct
88872 var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
88873 if (resolutionsChanged) {
88874 oldProgram.structureIsReused = 1 /* SafeModules */;
88875 newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions);
88876 }
88877 else {
88878 newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
88879 }
88880 }
88881 }
88882 if (oldProgram.structureIsReused !== 2 /* Completely */) {
88883 return oldProgram.structureIsReused;
88884 }
88885 if (host.hasChangedAutomaticTypeDirectiveNames) {
88886 return oldProgram.structureIsReused = 1 /* SafeModules */;
88887 }
88888 missingFilePaths = oldProgram.getMissingFilePaths();
88889 // update fileName -> file mapping
88890 for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) {
88891 var newSourceFile = newSourceFiles_1[_f];
88892 var filePath = newSourceFile.path;
88893 addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath);
88894 // Set the file as found during node modules search if it was found that way in old progra,
88895 if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath))) {
88896 sourceFilesFoundSearchingNodeModules.set(filePath, true);
88897 }
88898 }
88899 files = newSourceFiles;
88900 fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
88901 for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) {
88902 var modifiedFile = modifiedSourceFiles_2[_g];
88903 fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
88904 }
88905 resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
88906 sourceFileToPackageName = oldProgram.sourceFileToPackageName;
88907 redirectTargetsMap = oldProgram.redirectTargetsMap;
88908 return oldProgram.structureIsReused = 2 /* Completely */;
88909 }
88910 function getEmitHost(writeFileCallback) {
88911 return __assign({ getPrependNodes: getPrependNodes,
88912 getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
88913 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) {
88914 // Use local caches
88915 var path = toPath(f);
88916 if (getSourceFileByPath(path))
88917 return true;
88918 if (ts.contains(missingFilePaths, path))
88919 return false;
88920 // Before falling back to the host
88921 return host.fileExists(f);
88922 } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
88923 }
88924 function emitBuildInfo(writeFileCallback) {
88925 ts.Debug.assert(!options.out && !options.outFile);
88926 ts.performance.mark("beforeEmit");
88927 var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
88928 /*targetSourceFile*/ undefined,
88929 /*emitOnlyDtsFiles*/ false,
88930 /*transformers*/ undefined,
88931 /*declaraitonTransformers*/ undefined,
88932 /*onlyBuildInfo*/ true);
88933 ts.performance.mark("afterEmit");
88934 ts.performance.measure("Emit", "beforeEmit", "afterEmit");
88935 return emitResult;
88936 }
88937 function getResolvedProjectReferences() {
88938 return resolvedProjectReferences;
88939 }
88940 function getProjectReferences() {
88941 return projectReferences;
88942 }
88943 function getPrependNodes() {
88944 return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
88945 var path = toPath(fileName);
88946 var sourceFile = getSourceFileByPath(path);
88947 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
88948 });
88949 }
88950 function isSourceFileFromExternalLibrary(file) {
88951 return !!sourceFilesFoundSearchingNodeModules.get(file.path);
88952 }
88953 function isSourceFileDefaultLibrary(file) {
88954 if (file.hasNoDefaultLib) {
88955 return true;
88956 }
88957 if (!options.noLib) {
88958 return false;
88959 }
88960 // If '--lib' is not specified, include default library file according to '--target'
88961 // otherwise, using options specified in '--lib' instead of '--target' default library file
88962 var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
88963 if (!options.lib) {
88964 return equalityComparer(file.fileName, getDefaultLibraryFileName());
88965 }
88966 else {
88967 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
88968 }
88969 }
88970 function getDiagnosticsProducingTypeChecker() {
88971 return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
88972 }
88973 function dropDiagnosticsProducingTypeChecker() {
88974 diagnosticsProducingTypeChecker = undefined;
88975 }
88976 function getTypeChecker() {
88977 return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
88978 }
88979 function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) {
88980 return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); });
88981 }
88982 function isEmitBlocked(emitFileName) {
88983 return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
88984 }
88985 function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) {
88986 var declarationDiagnostics = [];
88987 if (!emitOnlyDtsFiles) {
88988 if (options.noEmit) {
88989 return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
88990 }
88991 // If the noEmitOnError flag is set, then check if we have any errors so far. If so,
88992 // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
88993 // get any preEmit diagnostics, not just the ones
88994 if (options.noEmitOnError) {
88995 var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
88996 if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
88997 declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
88998 }
88999 if (diagnostics.length > 0 || declarationDiagnostics.length > 0) {
89000 return {
89001 diagnostics: ts.concatenate(diagnostics, declarationDiagnostics),
89002 sourceMaps: undefined,
89003 emittedFiles: undefined,
89004 emitSkipped: true
89005 };
89006 }
89007 }
89008 }
89009 // Create the emit resolver outside of the "emitTime" tracking code below. That way
89010 // any cost associated with it (like type checking) are appropriate associated with
89011 // the type-checking counter.
89012 //
89013 // If the -out option is specified, we should not pass the source file to getEmitResolver.
89014 // This is because in the -out scenario all files need to be emitted, and therefore all
89015 // files need to be type checked. And the way to specify that all files need to be type
89016 // checked is to not pass the file to getEmitResolver.
89017 var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
89018 ts.performance.mark("beforeEmit");
89019 var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
89020 var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
89021 ts.performance.mark("afterEmit");
89022 ts.performance.measure("Emit", "beforeEmit", "afterEmit");
89023 return emitResult;
89024 }
89025 function getSourceFile(fileName) {
89026 return getSourceFileByPath(toPath(fileName));
89027 }
89028 function getSourceFileByPath(path) {
89029 return filesByName.get(path) || undefined;
89030 }
89031 function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
89032 if (sourceFile) {
89033 return getDiagnostics(sourceFile, cancellationToken);
89034 }
89035 return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
89036 if (cancellationToken) {
89037 cancellationToken.throwIfCancellationRequested();
89038 }
89039 return getDiagnostics(sourceFile, cancellationToken);
89040 }));
89041 }
89042 function getSyntacticDiagnostics(sourceFile, cancellationToken) {
89043 return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
89044 }
89045 function getSemanticDiagnostics(sourceFile, cancellationToken) {
89046 return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
89047 }
89048 function getDeclarationDiagnostics(sourceFile, cancellationToken) {
89049 var options = program.getCompilerOptions();
89050 // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
89051 if (!sourceFile || options.out || options.outFile) {
89052 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
89053 }
89054 else {
89055 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
89056 }
89057 }
89058 function getSyntacticDiagnosticsForFile(sourceFile) {
89059 // For JavaScript files, we report semantic errors for using TypeScript-only
89060 // constructs from within a JavaScript file as syntactic errors.
89061 if (ts.isSourceFileJS(sourceFile)) {
89062 if (!sourceFile.additionalSyntacticDiagnostics) {
89063 sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
89064 }
89065 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
89066 }
89067 return sourceFile.parseDiagnostics;
89068 }
89069 function runWithCancellationToken(func) {
89070 try {
89071 return func();
89072 }
89073 catch (e) {
89074 if (e instanceof ts.OperationCanceledException) {
89075 // We were canceled while performing the operation. Because our type checker
89076 // might be a bad state, we need to throw it away.
89077 //
89078 // Note: we are overly aggressive here. We do not actually *have* to throw away
89079 // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep
89080 // the lifetimes of these two TypeCheckers the same. Also, we generally only
89081 // cancel when the user has made a change anyways. And, in that case, we (the
89082 // program instance) will get thrown away anyways. So trying to keep one of
89083 // these type checkers alive doesn't serve much purpose.
89084 noDiagnosticsTypeChecker = undefined;
89085 diagnosticsProducingTypeChecker = undefined;
89086 }
89087 throw e;
89088 }
89089 }
89090 function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
89091 return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache);
89092 }
89093 function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
89094 return runWithCancellationToken(function () {
89095 if (ts.skipTypeChecking(sourceFile, options)) {
89096 return ts.emptyArray;
89097 }
89098 var typeChecker = getDiagnosticsProducingTypeChecker();
89099 ts.Debug.assert(!!sourceFile.bindDiagnostics);
89100 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
89101 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
89102 var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
89103 sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */;
89104 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
89105 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
89106 var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
89107 var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
89108 var diagnostics;
89109 for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) {
89110 var diags = _a[_i];
89111 if (diags) {
89112 for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) {
89113 var diag = diags_1[_b];
89114 if (shouldReportDiagnostic(diag)) {
89115 diagnostics = ts.append(diagnostics, diag);
89116 }
89117 }
89118 }
89119 }
89120 return diagnostics;
89121 });
89122 }
89123 function getSuggestionDiagnostics(sourceFile, cancellationToken) {
89124 return runWithCancellationToken(function () {
89125 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
89126 });
89127 }
89128 /**
89129 * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines
89130 */
89131 function shouldReportDiagnostic(diagnostic) {
89132 var file = diagnostic.file, start = diagnostic.start;
89133 if (file) {
89134 var lineStarts = ts.getLineStarts(file);
89135 var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217
89136 while (line > 0) {
89137 var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]);
89138 var result = ignoreDiagnosticCommentRegEx.exec(previousLineText);
89139 if (!result) {
89140 // non-empty line
89141 return true;
89142 }
89143 if (result[3]) {
89144 // @ts-ignore
89145 return false;
89146 }
89147 line--;
89148 }
89149 }
89150 return true;
89151 }
89152 function getJSSyntacticDiagnosticsForFile(sourceFile) {
89153 return runWithCancellationToken(function () {
89154 var diagnostics = [];
89155 var parent = sourceFile;
89156 walk(sourceFile);
89157 return diagnostics;
89158 function walk(node) {
89159 // Return directly from the case if the given node doesnt want to visit each child
89160 // Otherwise break to visit each child
89161 switch (parent.kind) {
89162 case 151 /* Parameter */:
89163 case 154 /* PropertyDeclaration */:
89164 if (parent.questionToken === node) {
89165 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
89166 return;
89167 }
89168 // falls through
89169 case 156 /* MethodDeclaration */:
89170 case 155 /* MethodSignature */:
89171 case 157 /* Constructor */:
89172 case 158 /* GetAccessor */:
89173 case 159 /* SetAccessor */:
89174 case 196 /* FunctionExpression */:
89175 case 239 /* FunctionDeclaration */:
89176 case 197 /* ArrowFunction */:
89177 case 237 /* VariableDeclaration */:
89178 // type annotation
89179 if (parent.type === node) {
89180 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file));
89181 return;
89182 }
89183 }
89184 switch (node.kind) {
89185 case 248 /* ImportEqualsDeclaration */:
89186 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file));
89187 return;
89188 case 254 /* ExportAssignment */:
89189 if (node.isExportEquals) {
89190 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file));
89191 return;
89192 }
89193 break;
89194 case 273 /* HeritageClause */:
89195 var heritageClause = node;
89196 if (heritageClause.token === 109 /* ImplementsKeyword */) {
89197 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file));
89198 return;
89199 }
89200 break;
89201 case 241 /* InterfaceDeclaration */:
89202 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file));
89203 return;
89204 case 244 /* ModuleDeclaration */:
89205 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file));
89206 return;
89207 case 242 /* TypeAliasDeclaration */:
89208 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file));
89209 return;
89210 case 243 /* EnumDeclaration */:
89211 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file));
89212 return;
89213 case 213 /* NonNullExpression */:
89214 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file));
89215 return;
89216 case 212 /* AsExpression */:
89217 diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file));
89218 return;
89219 case 194 /* TypeAssertionExpression */:
89220 ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
89221 }
89222 var prevParent = parent;
89223 parent = node;
89224 ts.forEachChild(node, walk, walkArray);
89225 parent = prevParent;
89226 }
89227 function walkArray(nodes) {
89228 if (parent.decorators === nodes && !options.experimentalDecorators) {
89229 diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning));
89230 }
89231 switch (parent.kind) {
89232 case 240 /* ClassDeclaration */:
89233 case 156 /* MethodDeclaration */:
89234 case 155 /* MethodSignature */:
89235 case 157 /* Constructor */:
89236 case 158 /* GetAccessor */:
89237 case 159 /* SetAccessor */:
89238 case 196 /* FunctionExpression */:
89239 case 239 /* FunctionDeclaration */:
89240 case 197 /* ArrowFunction */:
89241 // Check type parameters
89242 if (nodes === parent.typeParameters) {
89243 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file));
89244 return;
89245 }
89246 // falls through
89247 case 219 /* VariableStatement */:
89248 // Check modifiers
89249 if (nodes === parent.modifiers) {
89250 return checkModifiers(nodes, parent.kind === 219 /* VariableStatement */);
89251 }
89252 break;
89253 case 154 /* PropertyDeclaration */:
89254 // Check modifiers of property declaration
89255 if (nodes === parent.modifiers) {
89256 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
89257 var modifier = _a[_i];
89258 if (modifier.kind !== 116 /* StaticKeyword */) {
89259 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind)));
89260 }
89261 }
89262 return;
89263 }
89264 break;
89265 case 151 /* Parameter */:
89266 // Check modifiers of parameter declaration
89267 if (nodes === parent.modifiers) {
89268 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file));
89269 return;
89270 }
89271 break;
89272 case 191 /* CallExpression */:
89273 case 192 /* NewExpression */:
89274 case 211 /* ExpressionWithTypeArguments */:
89275 case 261 /* JsxSelfClosingElement */:
89276 case 262 /* JsxOpeningElement */:
89277 // Check type arguments
89278 if (nodes === parent.typeArguments) {
89279 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file));
89280 return;
89281 }
89282 break;
89283 }
89284 for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) {
89285 var node = nodes_6[_b];
89286 walk(node);
89287 }
89288 }
89289 function checkModifiers(modifiers, isConstValid) {
89290 for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
89291 var modifier = modifiers_1[_i];
89292 switch (modifier.kind) {
89293 case 77 /* ConstKeyword */:
89294 if (isConstValid) {
89295 continue;
89296 }
89297 // to report error,
89298 // falls through
89299 case 115 /* PublicKeyword */:
89300 case 113 /* PrivateKeyword */:
89301 case 114 /* ProtectedKeyword */:
89302 case 133 /* ReadonlyKeyword */:
89303 case 125 /* DeclareKeyword */:
89304 case 118 /* AbstractKeyword */:
89305 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind)));
89306 break;
89307 // These are all legal modifiers.
89308 case 116 /* StaticKeyword */:
89309 case 85 /* ExportKeyword */:
89310 case 80 /* DefaultKeyword */:
89311 }
89312 }
89313 }
89314 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
89315 var start = nodes.pos;
89316 return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
89317 }
89318 // Since these are syntactic diagnostics, parent might not have been set
89319 // this means the sourceFile cannot be infered from the node
89320 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
89321 return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
89322 }
89323 });
89324 }
89325 function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
89326 return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
89327 }
89328 function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
89329 return runWithCancellationToken(function () {
89330 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
89331 // Don't actually write any files since we're just getting diagnostics.
89332 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile);
89333 });
89334 }
89335 function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
89336 var cachedResult = sourceFile
89337 ? cache.perFile && cache.perFile.get(sourceFile.path)
89338 : cache.allDiagnostics;
89339 if (cachedResult) {
89340 return cachedResult;
89341 }
89342 var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217
89343 if (sourceFile) {
89344 if (!cache.perFile) {
89345 cache.perFile = ts.createMap();
89346 }
89347 cache.perFile.set(sourceFile.path, result);
89348 }
89349 else {
89350 cache.allDiagnostics = result;
89351 }
89352 return result;
89353 }
89354 function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
89355 return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
89356 }
89357 function getOptionsDiagnostics() {
89358 return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
89359 }
89360 function getOptionsDiagnosticsOfConfigFile() {
89361 if (!options.configFile) {
89362 return ts.emptyArray;
89363 }
89364 var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
89365 forEachResolvedProjectReference(function (resolvedRef) {
89366 if (resolvedRef) {
89367 diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
89368 }
89369 });
89370 return diagnostics;
89371 }
89372 function getGlobalDiagnostics() {
89373 return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
89374 }
89375 function getConfigFileParsingDiagnostics() {
89376 return configFileParsingDiagnostics || ts.emptyArray;
89377 }
89378 function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
89379 processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
89380 }
89381 function fileReferenceIsEqualTo(a, b) {
89382 return a.fileName === b.fileName;
89383 }
89384 function moduleNameIsEqualTo(a, b) {
89385 return a.kind === 72 /* Identifier */
89386 ? b.kind === 72 /* Identifier */ && a.escapedText === b.escapedText
89387 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
89388 }
89389 function collectExternalModuleReferences(file) {
89390 if (file.imports) {
89391 return;
89392 }
89393 var isJavaScriptFile = ts.isSourceFileJS(file);
89394 var isExternalModuleFile = ts.isExternalModule(file);
89395 // file.imports may not be undefined if there exists dynamic import
89396 var imports;
89397 var moduleAugmentations;
89398 var ambientModules;
89399 // If we are importing helpers, we need to add a synthetic reference to resolve the
89400 // helpers library.
89401 if (options.importHelpers
89402 && (options.isolatedModules || isExternalModuleFile)
89403 && !file.isDeclarationFile) {
89404 // synthesize 'import "tslib"' declaration
89405 var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText);
89406 var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
89407 ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
89408 externalHelpersModuleReference.parent = importDecl;
89409 importDecl.parent = file;
89410 imports = [externalHelpersModuleReference];
89411 }
89412 for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
89413 var node = _a[_i];
89414 collectModuleReferences(node, /*inAmbientModule*/ false);
89415 }
89416 if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
89417 collectDynamicImportOrRequireCalls(file);
89418 }
89419 file.imports = imports || ts.emptyArray;
89420 file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
89421 file.ambientModuleNames = ambientModules || ts.emptyArray;
89422 return;
89423 function collectModuleReferences(node, inAmbientModule) {
89424 if (ts.isAnyImportOrReExport(node)) {
89425 var moduleNameExpr = ts.getExternalModuleName(node);
89426 // TypeScript 1.0 spec (April 2014): 12.1.6
89427 // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
89428 // only through top - level external module names. Relative external module names are not permitted.
89429 if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
89430 imports = ts.append(imports, moduleNameExpr);
89431 }
89432 }
89433 else if (ts.isModuleDeclaration(node)) {
89434 if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
89435 var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
89436 // Ambient module declarations can be interpreted as augmentations for some existing external modules.
89437 // This will happen in two cases:
89438 // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
89439 // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
89440 // immediately nested in top level ambient module declaration .
89441 if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
89442 (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
89443 }
89444 else if (!inAmbientModule) {
89445 if (file.isDeclarationFile) {
89446 // for global .d.ts files record name of ambient module
89447 (ambientModules || (ambientModules = [])).push(nameText);
89448 }
89449 // An AmbientExternalModuleDeclaration declares an external module.
89450 // This type of declaration is permitted only in the global module.
89451 // The StringLiteral must specify a top - level external module name.
89452 // Relative external module names are not permitted
89453 // NOTE: body of ambient module is always a module block, if it exists
89454 var body = node.body;
89455 if (body) {
89456 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
89457 var statement = _a[_i];
89458 collectModuleReferences(statement, /*inAmbientModule*/ true);
89459 }
89460 }
89461 }
89462 }
89463 }
89464 }
89465 function collectDynamicImportOrRequireCalls(file) {
89466 var r = /import|require/g;
89467 while (r.exec(file.text) !== null) {
89468 var node = getNodeAtPosition(file, r.lastIndex);
89469 if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
89470 imports = ts.append(imports, node.arguments[0]);
89471 }
89472 // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
89473 else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
89474 imports = ts.append(imports, node.arguments[0]);
89475 }
89476 else if (ts.isLiteralImportTypeNode(node)) {
89477 imports = ts.append(imports, node.argument.literal);
89478 }
89479 }
89480 }
89481 /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
89482 function getNodeAtPosition(sourceFile, position) {
89483 var current = sourceFile;
89484 var getContainingChild = function (child) {
89485 if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
89486 return child;
89487 }
89488 };
89489 while (true) {
89490 var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
89491 if (!child) {
89492 return current;
89493 }
89494 current = child;
89495 }
89496 }
89497 }
89498 function getLibFileFromReference(ref) {
89499 var libName = ref.fileName.toLocaleLowerCase();
89500 var libFileName = ts.libMap.get(libName);
89501 if (libFileName) {
89502 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
89503 }
89504 }
89505 /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
89506 function getSourceFileFromReference(referencingFile, ref) {
89507 return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
89508 }
89509 function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
89510 if (ts.hasExtension(fileName)) {
89511 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) {
89512 if (fail)
89513 fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
89514 return undefined;
89515 }
89516 var sourceFile = getSourceFile(fileName);
89517 if (fail) {
89518 if (!sourceFile) {
89519 var redirect = getProjectReferenceRedirect(fileName);
89520 if (redirect) {
89521 fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
89522 }
89523 else {
89524 fail(ts.Diagnostics.File_0_not_found, fileName);
89525 }
89526 }
89527 else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
89528 fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
89529 }
89530 }
89531 return sourceFile;
89532 }
89533 else {
89534 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
89535 if (sourceFileNoExtension)
89536 return sourceFileNoExtension;
89537 if (fail && options.allowNonTsExtensions) {
89538 fail(ts.Diagnostics.File_0_not_found, fileName);
89539 return undefined;
89540 }
89541 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
89542 if (fail && !sourceFileWithAddedExtension)
89543 fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */);
89544 return sourceFileWithAddedExtension;
89545 }
89546 }
89547 /** This has side effects through `findSourceFile`. */
89548 function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile, refPos, refEnd) {
89549 getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217
89550 function (diagnostic) {
89551 var args = [];
89552 for (var _i = 1; _i < arguments.length; _i++) {
89553 args[_i - 1] = arguments[_i];
89554 }
89555 fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined
89556 ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args)));
89557 }, refFile);
89558 }
89559 function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) {
89560 if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
89561 fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
89562 }
89563 else {
89564 fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
89565 }
89566 }
89567 function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
89568 var redirect = Object.create(redirectTarget);
89569 redirect.fileName = fileName;
89570 redirect.path = path;
89571 redirect.resolvedPath = resolvedPath;
89572 redirect.originalFileName = originalFileName;
89573 redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
89574 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
89575 Object.defineProperties(redirect, {
89576 id: {
89577 get: function () { return this.redirectInfo.redirectTarget.id; },
89578 set: function (value) { this.redirectInfo.redirectTarget.id = value; },
89579 },
89580 symbol: {
89581 get: function () { return this.redirectInfo.redirectTarget.symbol; },
89582 set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
89583 },
89584 });
89585 return redirect;
89586 }
89587 // Get source file from normalized fileName
89588 function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) {
89589 var originalFileName = fileName;
89590 if (filesByName.has(path)) {
89591 var file_1 = filesByName.get(path);
89592 // try to check if we've already seen this file but with a different casing in path
89593 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
89594 if (file_1 && options.forceConsistentCasingInFileNames) {
89595 var inputName = fileName;
89596 var checkedName = file_1.fileName;
89597 var isRedirect = toPath(checkedName) !== toPath(inputName);
89598 if (isRedirect) {
89599 inputName = getProjectReferenceRedirect(fileName) || fileName;
89600 }
89601 if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) {
89602 reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd);
89603 }
89604 }
89605 // If the file was previously found via a node_modules search, but is now being processed as a root file,
89606 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
89607 if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) {
89608 sourceFilesFoundSearchingNodeModules.set(file_1.path, false);
89609 if (!options.noResolve) {
89610 processReferencedFiles(file_1, isDefaultLib);
89611 processTypeReferenceDirectives(file_1);
89612 }
89613 if (!options.noLib) {
89614 processLibReferenceDirectives(file_1);
89615 }
89616 modulesWithElidedImports.set(file_1.path, false);
89617 processImportedModules(file_1);
89618 }
89619 // See if we need to reprocess the imports due to prior skipped imports
89620 else if (file_1 && modulesWithElidedImports.get(file_1.path)) {
89621 if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
89622 modulesWithElidedImports.set(file_1.path, false);
89623 processImportedModules(file_1);
89624 }
89625 }
89626 return file_1 || undefined;
89627 }
89628 var redirectedPath;
89629 if (refFile) {
89630 var redirect = getProjectReferenceRedirect(fileName);
89631 if (redirect) {
89632 fileName = redirect;
89633 // Once we start redirecting to a file, we can potentially come back to it
89634 // via a back-reference from another file in the .d.ts folder. If that happens we'll
89635 // end up trying to add it to the program *again* because we were tracking it via its
89636 // original (un-redirected) name. So we have to map both the original path and the redirected path
89637 // to the source file we're about to find/create
89638 redirectedPath = toPath(redirect);
89639 }
89640 }
89641 // We haven't looked for this file, do so now and cache result
89642 var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) {
89643 if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
89644 fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
89645 }
89646 else {
89647 fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
89648 }
89649 }, shouldCreateNewSourceFile);
89650 if (packageId) {
89651 var packageIdKey = ts.packageIdToString(packageId);
89652 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
89653 if (fileFromPackageId) {
89654 // Some other SourceFile already exists with this package name and version.
89655 // Instead of creating a duplicate, just redirect to the existing one.
89656 var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
89657 redirectTargetsMap.add(fileFromPackageId.path, fileName);
89658 addFileToFilesByName(dupFile, path, redirectedPath);
89659 sourceFileToPackageName.set(path, packageId.name);
89660 processingOtherFiles.push(dupFile);
89661 return dupFile;
89662 }
89663 else if (file) {
89664 // This is the first source file to have this packageId.
89665 packageIdToSourceFile.set(packageIdKey, file);
89666 sourceFileToPackageName.set(path, packageId.name);
89667 }
89668 }
89669 addFileToFilesByName(file, path, redirectedPath);
89670 if (file) {
89671 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
89672 file.path = path;
89673 file.resolvedPath = toPath(fileName);
89674 file.originalFileName = originalFileName;
89675 if (host.useCaseSensitiveFileNames()) {
89676 var pathLowerCase = path.toLowerCase();
89677 // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
89678 var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
89679 if (existingFile) {
89680 reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd);
89681 }
89682 else {
89683 filesByNameIgnoreCase.set(pathLowerCase, file);
89684 }
89685 }
89686 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
89687 if (!options.noResolve) {
89688 processReferencedFiles(file, isDefaultLib);
89689 processTypeReferenceDirectives(file);
89690 }
89691 if (!options.noLib) {
89692 processLibReferenceDirectives(file);
89693 }
89694 // always process imported modules to record module name resolutions
89695 processImportedModules(file);
89696 if (isDefaultLib) {
89697 processingDefaultLibFiles.push(file);
89698 }
89699 else {
89700 processingOtherFiles.push(file);
89701 }
89702 }
89703 return file;
89704 }
89705 function addFileToFilesByName(file, path, redirectedPath) {
89706 if (redirectedPath) {
89707 filesByName.set(redirectedPath, file);
89708 filesByName.set(path, file || false);
89709 }
89710 else {
89711 filesByName.set(path, file);
89712 }
89713 }
89714 function getProjectReferenceRedirect(fileName) {
89715 // Ignore dts or any of the non ts files
89716 if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) {
89717 return undefined;
89718 }
89719 // If this file is produced by a referenced project, we need to rewrite it to
89720 // look in the output folder of the referenced project rather than the input
89721 var referencedProject = getResolvedProjectReferenceToRedirect(fileName);
89722 if (!referencedProject) {
89723 return undefined;
89724 }
89725 var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
89726 return out ?
89727 ts.changeExtension(out, ".d.ts" /* Dts */) :
89728 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
89729 }
89730 /**
89731 * Get the referenced project if the file is input file from that reference project
89732 */
89733 function getResolvedProjectReferenceToRedirect(fileName) {
89734 if (mapFromFileToProjectReferenceRedirects === undefined) {
89735 mapFromFileToProjectReferenceRedirects = ts.createMap();
89736 forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
89737 // not input file from the referenced project, ignore
89738 if (referencedProject &&
89739 toPath(options.configFilePath) !== referenceProjectPath) {
89740 referencedProject.commandLine.fileNames.forEach(function (f) {
89741 return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
89742 });
89743 }
89744 });
89745 }
89746 var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
89747 return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
89748 }
89749 function forEachResolvedProjectReference(cb) {
89750 return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
89751 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
89752 var resolvedRefPath = toPath(resolveProjectReferencePath(ref));
89753 return cb(resolvedRef, resolvedRefPath);
89754 });
89755 }
89756 function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
89757 var seenResolvedRefs;
89758 return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef);
89759 function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) {
89760 // Visit project references first
89761 if (cbRef) {
89762 var result = cbRef(projectReferences, parent);
89763 if (result) {
89764 return result;
89765 }
89766 }
89767 return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
89768 if (ts.contains(seenResolvedRefs, resolvedRef)) {
89769 // ignore recursives
89770 return undefined;
89771 }
89772 var result = cbResolvedRef(resolvedRef, index, parent);
89773 if (result) {
89774 return result;
89775 }
89776 if (!resolvedRef)
89777 return undefined;
89778 (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef);
89779 return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef);
89780 });
89781 }
89782 }
89783 function getResolvedProjectReferenceByPath(projectReferencePath) {
89784 if (!projectReferenceRedirects) {
89785 return undefined;
89786 }
89787 return projectReferenceRedirects.get(projectReferencePath) || undefined;
89788 }
89789 function processReferencedFiles(file, isDefaultLib) {
89790 ts.forEach(file.referencedFiles, function (ref) {
89791 var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName);
89792 processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end);
89793 });
89794 }
89795 function processTypeReferenceDirectives(file) {
89796 // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
89797 var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); });
89798 if (!typeDirectives) {
89799 return;
89800 }
89801 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName));
89802 for (var i = 0; i < typeDirectives.length; i++) {
89803 var ref = file.typeReferenceDirectives[i];
89804 var resolvedTypeReferenceDirective = resolutions[i];
89805 // store resolved type directive on the file
89806 var fileName = ref.fileName.toLocaleLowerCase();
89807 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
89808 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end);
89809 }
89810 }
89811 function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) {
89812 // If we already found this library as a primary reference - nothing to do
89813 var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
89814 if (previousResolution && previousResolution.primary) {
89815 return;
89816 }
89817 var saveResolution = true;
89818 if (resolvedTypeReferenceDirective) {
89819 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
89820 currentNodeModulesDepth++;
89821 if (resolvedTypeReferenceDirective.primary) {
89822 // resolved from the primary path
89823 processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217
89824 }
89825 else {
89826 // If we already resolved to this file, it must have been a secondary reference. Check file contents
89827 // for sameness and possibly issue an error
89828 if (previousResolution) {
89829 // Don't bother reading the file again if it's the same file.
89830 if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
89831 var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
89832 if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) {
89833 fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217
89834 ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName));
89835 }
89836 }
89837 // don't overwrite previous resolution result
89838 saveResolution = false;
89839 }
89840 else {
89841 // First resolution of this library
89842 processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd);
89843 }
89844 }
89845 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
89846 currentNodeModulesDepth--;
89847 }
89848 else {
89849 fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217
89850 }
89851 if (saveResolution) {
89852 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
89853 }
89854 }
89855 function processLibReferenceDirectives(file) {
89856 ts.forEach(file.libReferenceDirectives, function (libReference) {
89857 var libName = libReference.fileName.toLocaleLowerCase();
89858 var libFileName = ts.libMap.get(libName);
89859 if (libFileName) {
89860 // we ignore any 'no-default-lib' reference set on this file.
89861 processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
89862 }
89863 else {
89864 var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
89865 var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
89866 var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
89867 fileProcessingDiagnostics.add(createDiagnostic(file, libReference.pos, libReference.end, message, libName, suggestion));
89868 }
89869 });
89870 }
89871 function createDiagnostic(refFile, refPos, refEnd, message) {
89872 var args = [];
89873 for (var _i = 4; _i < arguments.length; _i++) {
89874 args[_i - 4] = arguments[_i];
89875 }
89876 if (refFile === undefined || refPos === undefined || refEnd === undefined) {
89877 return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args));
89878 }
89879 else {
89880 return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args));
89881 }
89882 }
89883 function getCanonicalFileName(fileName) {
89884 return host.getCanonicalFileName(fileName);
89885 }
89886 function processImportedModules(file) {
89887 collectExternalModuleReferences(file);
89888 if (file.imports.length || file.moduleAugmentations.length) {
89889 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
89890 var moduleNames = getModuleNames(file);
89891 var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file);
89892 ts.Debug.assert(resolutions.length === moduleNames.length);
89893 for (var i = 0; i < moduleNames.length; i++) {
89894 var resolution = resolutions[i];
89895 ts.setResolvedModule(file, moduleNames[i], resolution);
89896 if (!resolution) {
89897 continue;
89898 }
89899 var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
89900 var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
89901 var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
89902 var resolvedFileName = resolution.resolvedFileName;
89903 if (isFromNodeModulesSearch) {
89904 currentNodeModulesDepth++;
89905 }
89906 // add file to program only if:
89907 // - resolution was successful
89908 // - noResolve is falsy
89909 // - module name comes from the list of imports
89910 // - it's not a top level JavaScript module that exceeded the search max
89911 var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
89912 // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
89913 // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
89914 var shouldAddFile = resolvedFileName
89915 && !getResolutionDiagnostic(options, resolution)
89916 && !options.noResolve
89917 && i < file.imports.length
89918 && !elideImport
89919 && !(isJsFile && !options.allowJs)
89920 && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */));
89921 if (elideImport) {
89922 modulesWithElidedImports.set(file.path, true);
89923 }
89924 else if (shouldAddFile) {
89925 var path = toPath(resolvedFileName);
89926 var pos = ts.skipTrivia(file.text, file.imports[i].pos);
89927 findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId);
89928 }
89929 if (isFromNodeModulesSearch) {
89930 currentNodeModulesDepth--;
89931 }
89932 }
89933 }
89934 else {
89935 // no imports - drop cached module resolutions
89936 file.resolvedModules = undefined;
89937 }
89938 }
89939 function computeCommonSourceDirectory(sourceFiles) {
89940 var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
89941 return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
89942 }
89943 function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
89944 var allFilesBelongToPath = true;
89945 var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
89946 for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
89947 var sourceFile = sourceFiles_2[_i];
89948 if (!sourceFile.isDeclarationFile) {
89949 var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
89950 if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
89951 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory));
89952 allFilesBelongToPath = false;
89953 }
89954 }
89955 }
89956 return allFilesBelongToPath;
89957 }
89958 function parseProjectReferenceConfigFile(ref) {
89959 if (!projectReferenceRedirects) {
89960 projectReferenceRedirects = ts.createMap();
89961 }
89962 // The actual filename (i.e. add "/tsconfig.json" if necessary)
89963 var refPath = resolveProjectReferencePath(ref);
89964 var sourceFilePath = toPath(refPath);
89965 var fromCache = projectReferenceRedirects.get(sourceFilePath);
89966 if (fromCache !== undefined) {
89967 return fromCache || undefined;
89968 }
89969 // An absolute path pointing to the containing directory of the config file
89970 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
89971 var sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
89972 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
89973 if (sourceFile === undefined) {
89974 projectReferenceRedirects.set(sourceFilePath, false);
89975 return undefined;
89976 }
89977 sourceFile.path = sourceFilePath;
89978 sourceFile.resolvedPath = sourceFilePath;
89979 sourceFile.originalFileName = refPath;
89980 var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
89981 var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
89982 projectReferenceRedirects.set(sourceFilePath, resolvedRef);
89983 if (commandLine.projectReferences) {
89984 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
89985 }
89986 return resolvedRef;
89987 }
89988 function verifyCompilerOptions() {
89989 if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
89990 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
89991 }
89992 if (options.isolatedModules) {
89993 if (ts.getEmitDeclarations(options)) {
89994 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules");
89995 }
89996 if (options.noEmitOnError) {
89997 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules");
89998 }
89999 if (options.out) {
90000 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
90001 }
90002 if (options.outFile) {
90003 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
90004 }
90005 }
90006 if (options.inlineSourceMap) {
90007 if (options.sourceMap) {
90008 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
90009 }
90010 if (options.mapRoot) {
90011 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
90012 }
90013 }
90014 if (options.paths && options.baseUrl === undefined) {
90015 createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
90016 }
90017 if (options.composite) {
90018 if (options.declaration === false) {
90019 createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
90020 }
90021 if (options.incremental === false) {
90022 createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
90023 }
90024 }
90025 if (options.tsBuildInfoFile) {
90026 if (!ts.isIncrementalCompilation(options)) {
90027 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
90028 }
90029 }
90030 verifyProjectReferences();
90031 // List of collected files is complete; validate exhautiveness if this is a project with a file list
90032 if (options.composite) {
90033 var rootPaths = rootNames.map(toPath);
90034 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
90035 var file = files_3[_i];
90036 // Ignore declaration files
90037 if (file.isDeclarationFile)
90038 continue;
90039 // Ignore json file thats from project reference
90040 if (ts.isJsonSourceFile(file) && getResolvedProjectReferenceToRedirect(file.fileName))
90041 continue;
90042 if (rootPaths.indexOf(file.path) === -1) {
90043 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file.fileName));
90044 }
90045 }
90046 }
90047 if (options.paths) {
90048 for (var key in options.paths) {
90049 if (!ts.hasProperty(options.paths, key)) {
90050 continue;
90051 }
90052 if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
90053 createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
90054 }
90055 if (ts.isArray(options.paths[key])) {
90056 var len = options.paths[key].length;
90057 if (len === 0) {
90058 createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
90059 }
90060 for (var i = 0; i < len; i++) {
90061 var subst = options.paths[key][i];
90062 var typeOfSubst = typeof subst;
90063 if (typeOfSubst === "string") {
90064 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
90065 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key);
90066 }
90067 }
90068 else {
90069 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
90070 }
90071 }
90072 }
90073 else {
90074 createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
90075 }
90076 }
90077 }
90078 if (!options.sourceMap && !options.inlineSourceMap) {
90079 if (options.inlineSources) {
90080 createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
90081 }
90082 if (options.sourceRoot) {
90083 createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
90084 }
90085 }
90086 if (options.out && options.outFile) {
90087 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
90088 }
90089 if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
90090 // Error to specify --mapRoot without --sourcemap
90091 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
90092 }
90093 if (options.declarationDir) {
90094 if (!ts.getEmitDeclarations(options)) {
90095 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
90096 }
90097 if (options.out || options.outFile) {
90098 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
90099 }
90100 }
90101 if (options.declarationMap && !ts.getEmitDeclarations(options)) {
90102 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
90103 }
90104 if (options.lib && options.noLib) {
90105 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
90106 }
90107 if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
90108 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
90109 }
90110 var languageVersion = options.target || 0 /* ES3 */;
90111 var outFile = options.outFile || options.out;
90112 var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
90113 if (options.isolatedModules) {
90114 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
90115 createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
90116 }
90117 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
90118 if (firstNonExternalModuleSourceFile) {
90119 var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
90120 programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
90121 }
90122 }
90123 else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
90124 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
90125 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
90126 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
90127 }
90128 // Cannot specify module gen that isn't amd or system with --out
90129 if (outFile && !options.emitDeclarationOnly) {
90130 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
90131 createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
90132 }
90133 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
90134 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
90135 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
90136 }
90137 }
90138 if (options.resolveJsonModule) {
90139 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
90140 createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
90141 }
90142 // Any emit other than common js, amd, es2015 or esnext is error
90143 else if (!ts.hasJsonModuleEmitEnabled(options)) {
90144 createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
90145 }
90146 }
90147 // there has to be common source directory if user specified --outdir || --sourceRoot
90148 // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
90149 if (options.outDir || // there is --outDir specified
90150 options.sourceRoot || // there is --sourceRoot specified
90151 options.mapRoot) { // there is --mapRoot specified
90152 // Precalculate and cache the common source directory
90153 var dir = getCommonSourceDirectory();
90154 // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
90155 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
90156 createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
90157 }
90158 }
90159 if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) {
90160 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options));
90161 }
90162 if (options.checkJs && !options.allowJs) {
90163 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
90164 }
90165 if (options.emitDeclarationOnly) {
90166 if (!ts.getEmitDeclarations(options)) {
90167 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
90168 }
90169 if (options.noEmit) {
90170 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
90171 }
90172 }
90173 if (options.emitDecoratorMetadata &&
90174 !options.experimentalDecorators) {
90175 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
90176 }
90177 if (options.jsxFactory) {
90178 if (options.reactNamespace) {
90179 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
90180 }
90181 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
90182 createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
90183 }
90184 }
90185 else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
90186 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
90187 }
90188 // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
90189 if (!options.noEmit && !options.suppressOutputPathCheck) {
90190 var emitHost = getEmitHost();
90191 var emitFilesSeen_1 = ts.createMap();
90192 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
90193 if (!options.emitDeclarationOnly) {
90194 verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
90195 }
90196 verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
90197 });
90198 }
90199 // Verify that all the emit files are unique and don't overwrite input files
90200 function verifyEmitFilePath(emitFileName, emitFilesSeen) {
90201 if (emitFileName) {
90202 var emitFilePath = toPath(emitFileName);
90203 // Report error if the output overwrites input file
90204 if (filesByName.has(emitFilePath)) {
90205 var chain_2;
90206 if (!options.configFilePath) {
90207 // The program is from either an inferred project or an external project
90208 chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.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);
90209 }
90210 chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
90211 blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2));
90212 }
90213 var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath;
90214 // Report error if multiple files write into same file
90215 if (emitFilesSeen.has(emitFileKey)) {
90216 // Already seen the same emit file - report error
90217 blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
90218 }
90219 else {
90220 emitFilesSeen.set(emitFileKey, true);
90221 }
90222 }
90223 }
90224 }
90225 function verifyProjectReferences() {
90226 var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
90227 forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
90228 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
90229 var parentFile = parent && parent.sourceFile;
90230 if (!resolvedRef) {
90231 createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
90232 return;
90233 }
90234 var options = resolvedRef.commandLine.options;
90235 if (!options.composite) {
90236 // ok to not have composite if the current program is container only
90237 var inputs = parent ? parent.commandLine.fileNames : rootNames;
90238 if (inputs.length) {
90239 createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
90240 }
90241 }
90242 if (ref.prepend) {
90243 var out = options.outFile || options.out;
90244 if (out) {
90245 if (!host.fileExists(out)) {
90246 createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
90247 }
90248 }
90249 else {
90250 createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
90251 }
90252 }
90253 if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
90254 createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
90255 hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
90256 }
90257 });
90258 }
90259 function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
90260 var needCompilerDiagnostic = true;
90261 var pathsSyntax = getOptionPathsSyntax();
90262 for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
90263 var pathProp = pathsSyntax_1[_i];
90264 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
90265 for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
90266 var keyProps = _b[_a];
90267 var initializer = keyProps.initializer;
90268 if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
90269 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
90270 needCompilerDiagnostic = false;
90271 }
90272 }
90273 }
90274 }
90275 if (needCompilerDiagnostic) {
90276 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
90277 }
90278 }
90279 function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
90280 var needCompilerDiagnostic = true;
90281 var pathsSyntax = getOptionPathsSyntax();
90282 for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
90283 var pathProp = pathsSyntax_2[_i];
90284 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
90285 createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
90286 needCompilerDiagnostic = false;
90287 }
90288 }
90289 if (needCompilerDiagnostic) {
90290 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
90291 }
90292 }
90293 function getOptionsSyntaxByName(name) {
90294 var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
90295 if (compilerOptionsObjectLiteralSyntax) {
90296 return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
90297 }
90298 return undefined;
90299 }
90300 function getOptionPathsSyntax() {
90301 return getOptionsSyntaxByName("paths") || ts.emptyArray;
90302 }
90303 function createDiagnosticForOptionName(message, option1, option2, option3) {
90304 createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
90305 }
90306 function createOptionValueDiagnostic(option1, message, arg0) {
90307 createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
90308 }
90309 function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
90310 var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
90311 if (referencesSyntax && referencesSyntax.elements.length > index) {
90312 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
90313 }
90314 else {
90315 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
90316 }
90317 }
90318 function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
90319 var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
90320 var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
90321 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
90322 if (needCompilerDiagnostic) {
90323 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
90324 }
90325 }
90326 function getCompilerOptionsObjectLiteralSyntax() {
90327 if (_compilerOptionsObjectLiteralSyntax === undefined) {
90328 _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword
90329 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
90330 if (jsonObjectLiteral) {
90331 for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
90332 var prop = _a[_i];
90333 if (ts.isObjectLiteralExpression(prop.initializer)) {
90334 _compilerOptionsObjectLiteralSyntax = prop.initializer;
90335 break;
90336 }
90337 }
90338 }
90339 }
90340 return _compilerOptionsObjectLiteralSyntax;
90341 }
90342 function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
90343 var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
90344 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
90345 var prop = props_2[_i];
90346 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
90347 }
90348 return !!props.length;
90349 }
90350 function blockEmittingOfFile(emitFileName, diag) {
90351 hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
90352 programDiagnostics.add(diag);
90353 }
90354 function isEmittedFile(file) {
90355 if (options.noEmit) {
90356 return false;
90357 }
90358 // If this is source file, its not emitted file
90359 var filePath = toPath(file);
90360 if (getSourceFileByPath(filePath)) {
90361 return false;
90362 }
90363 // If options have --outFile or --out just check that
90364 var out = options.outFile || options.out;
90365 if (out) {
90366 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
90367 }
90368 // If declarationDir is specified, return if its a file in that directory
90369 if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
90370 return true;
90371 }
90372 // If --outDir, check if file is in that directory
90373 if (options.outDir) {
90374 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
90375 }
90376 if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
90377 // Otherwise just check if sourceFile with the name exists
90378 var filePathWithoutExtension = ts.removeFileExtension(filePath);
90379 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
90380 !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
90381 }
90382 return false;
90383 }
90384 function isSameFile(file1, file2) {
90385 return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
90386 }
90387 }
90388 ts.createProgram = createProgram;
90389 /* @internal */
90390 function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
90391 if (directoryStructureHost === void 0) { directoryStructureHost = host; }
90392 return {
90393 fileExists: function (f) { return directoryStructureHost.fileExists(f); },
90394 readDirectory: function (root, extensions, excludes, includes, depth) {
90395 ts.Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
90396 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
90397 },
90398 readFile: function (f) { return directoryStructureHost.readFile(f); },
90399 useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
90400 getCurrentDirectory: function () { return host.getCurrentDirectory(); },
90401 onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
90402 trace: host.trace ? function (s) { return host.trace(s); } : undefined
90403 };
90404 }
90405 ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
90406 /* @internal */
90407 function createPrependNodes(projectReferences, getCommandLine, readFile) {
90408 if (!projectReferences)
90409 return ts.emptyArray;
90410 var nodes;
90411 for (var i = 0; i < projectReferences.length; i++) {
90412 var ref = projectReferences[i];
90413 var resolvedRefOpts = getCommandLine(ref, i);
90414 if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
90415 var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
90416 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
90417 if (!out)
90418 continue;
90419 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
90420 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
90421 (nodes || (nodes = [])).push(node);
90422 }
90423 }
90424 return nodes || ts.emptyArray;
90425 }
90426 ts.createPrependNodes = createPrependNodes;
90427 function resolveProjectReferencePath(hostOrRef, ref) {
90428 var passedInRef = ref ? ref : hostOrRef;
90429 return ts.resolveConfigFileProjectName(passedInRef.path);
90430 }
90431 ts.resolveProjectReferencePath = resolveProjectReferencePath;
90432 function getEmitDeclarationOptionName(options) {
90433 return options.declaration ? "declaration" : "composite";
90434 }
90435 /* @internal */
90436 /**
90437 * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
90438 * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
90439 * This returns a diagnostic even if the module will be an untyped module.
90440 */
90441 function getResolutionDiagnostic(options, _a) {
90442 var extension = _a.extension;
90443 switch (extension) {
90444 case ".ts" /* Ts */:
90445 case ".d.ts" /* Dts */:
90446 // These are always allowed.
90447 return undefined;
90448 case ".tsx" /* Tsx */:
90449 return needJsx();
90450 case ".jsx" /* Jsx */:
90451 return needJsx() || needAllowJs();
90452 case ".js" /* Js */:
90453 return needAllowJs();
90454 case ".json" /* Json */:
90455 return needResolveJsonModule();
90456 }
90457 function needJsx() {
90458 return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
90459 }
90460 function needAllowJs() {
90461 return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
90462 }
90463 function needResolveJsonModule() {
90464 return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
90465 }
90466 }
90467 ts.getResolutionDiagnostic = getResolutionDiagnostic;
90468 function getModuleNames(_a) {
90469 var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
90470 var res = imports.map(function (i) { return i.text; });
90471 for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
90472 var aug = moduleAugmentations_1[_i];
90473 if (aug.kind === 10 /* StringLiteral */) {
90474 res.push(aug.text);
90475 }
90476 // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
90477 }
90478 return res;
90479 }
90480})(ts || (ts = {}));
90481/*@internal*/
90482var ts;
90483(function (ts) {
90484 function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) {
90485 var outputFiles = [];
90486 var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
90487 return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit };
90488 function writeFile(fileName, text, writeByteOrderMark) {
90489 outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
90490 }
90491 }
90492 ts.getFileEmitOutput = getFileEmitOutput;
90493 function cloneMapOrUndefined(map) {
90494 return map ? ts.cloneMap(map) : undefined;
90495 }
90496 ts.cloneMapOrUndefined = cloneMapOrUndefined;
90497})(ts || (ts = {}));
90498/*@internal*/
90499(function (ts) {
90500 var BuilderState;
90501 (function (BuilderState) {
90502 /**
90503 * Get the referencedFile from the imported module symbol
90504 */
90505 function getReferencedFileFromImportedModuleSymbol(symbol) {
90506 if (symbol.declarations && symbol.declarations[0]) {
90507 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
90508 return declarationSourceFile && declarationSourceFile.resolvedPath;
90509 }
90510 }
90511 /**
90512 * Get the referencedFile from the import name node from file
90513 */
90514 function getReferencedFileFromImportLiteral(checker, importName) {
90515 var symbol = checker.getSymbolAtLocation(importName);
90516 return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
90517 }
90518 /**
90519 * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
90520 */
90521 function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
90522 return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
90523 }
90524 /**
90525 * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
90526 */
90527 function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
90528 var referencedFiles;
90529 // We need to use a set here since the code can contain the same import twice,
90530 // but that will only be one dependency.
90531 // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
90532 if (sourceFile.imports && sourceFile.imports.length > 0) {
90533 var checker = program.getTypeChecker();
90534 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
90535 var importName = _a[_i];
90536 var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
90537 if (declarationSourceFilePath) {
90538 addReferencedFile(declarationSourceFilePath);
90539 }
90540 }
90541 }
90542 var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path);
90543 // Handle triple slash references
90544 if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
90545 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
90546 var referencedFile = _c[_b];
90547 var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
90548 addReferencedFile(referencedPath);
90549 }
90550 }
90551 // Handle type reference directives
90552 if (sourceFile.resolvedTypeReferenceDirectiveNames) {
90553 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
90554 if (!resolvedTypeReferenceDirective) {
90555 return;
90556 }
90557 var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
90558 var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
90559 addReferencedFile(typeFilePath);
90560 });
90561 }
90562 // Add module augmentation as references
90563 if (sourceFile.moduleAugmentations.length) {
90564 var checker = program.getTypeChecker();
90565 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
90566 var moduleName = _e[_d];
90567 if (!ts.isStringLiteral(moduleName)) {
90568 continue;
90569 }
90570 var symbol = checker.getSymbolAtLocation(moduleName);
90571 if (!symbol) {
90572 continue;
90573 }
90574 // Add any file other than our own as reference
90575 addReferenceFromAmbientModule(symbol);
90576 }
90577 }
90578 // From ambient modules
90579 for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
90580 var ambientModule = _g[_f];
90581 if (ambientModule.declarations.length > 1) {
90582 addReferenceFromAmbientModule(ambientModule);
90583 }
90584 }
90585 return referencedFiles;
90586 function addReferenceFromAmbientModule(symbol) {
90587 // Add any file other than our own as reference
90588 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
90589 var declaration = _a[_i];
90590 var declarationSourceFile = ts.getSourceFileOfNode(declaration);
90591 if (declarationSourceFile &&
90592 declarationSourceFile !== sourceFile) {
90593 addReferencedFile(declarationSourceFile.resolvedPath);
90594 }
90595 }
90596 }
90597 function addReferencedFile(referencedPath) {
90598 if (!referencedFiles) {
90599 referencedFiles = ts.createMap();
90600 }
90601 referencedFiles.set(referencedPath, true);
90602 }
90603 }
90604 /**
90605 * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
90606 */
90607 function canReuseOldState(newReferencedMap, oldState) {
90608 return oldState && !oldState.referencedMap === !newReferencedMap;
90609 }
90610 BuilderState.canReuseOldState = canReuseOldState;
90611 /**
90612 * Creates the state of file references and signature for the new program from oldState if it is safe
90613 */
90614 function create(newProgram, getCanonicalFileName, oldState) {
90615 var fileInfos = ts.createMap();
90616 var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined;
90617 var exportedModulesMap = referencedMap ? ts.createMap() : undefined;
90618 var hasCalledUpdateShapeSignature = ts.createMap();
90619 var useOldState = canReuseOldState(referencedMap, oldState);
90620 // Create the reference map, and set the file infos
90621 for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
90622 var sourceFile = _a[_i];
90623 var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
90624 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined;
90625 if (referencedMap) {
90626 var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
90627 if (newReferences) {
90628 referencedMap.set(sourceFile.path, newReferences);
90629 }
90630 // Copy old visible to outside files map
90631 if (useOldState) {
90632 var exportedModules = oldState.exportedModulesMap.get(sourceFile.path);
90633 if (exportedModules) {
90634 exportedModulesMap.set(sourceFile.path, exportedModules);
90635 }
90636 }
90637 }
90638 fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature });
90639 }
90640 return {
90641 fileInfos: fileInfos,
90642 referencedMap: referencedMap,
90643 exportedModulesMap: exportedModulesMap,
90644 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
90645 };
90646 }
90647 BuilderState.create = create;
90648 /**
90649 * Releases needed properties
90650 */
90651 function releaseCache(state) {
90652 state.allFilesExcludingDefaultLibraryFile = undefined;
90653 state.allFileNames = undefined;
90654 }
90655 BuilderState.releaseCache = releaseCache;
90656 /**
90657 * Creates a clone of the state
90658 */
90659 function clone(state) {
90660 var fileInfos = ts.createMap();
90661 state.fileInfos.forEach(function (value, key) {
90662 fileInfos.set(key, __assign({}, value));
90663 });
90664 // Dont need to backup allFiles info since its cache anyway
90665 return {
90666 fileInfos: fileInfos,
90667 referencedMap: ts.cloneMapOrUndefined(state.referencedMap),
90668 exportedModulesMap: ts.cloneMapOrUndefined(state.exportedModulesMap),
90669 hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature),
90670 };
90671 }
90672 BuilderState.clone = clone;
90673 /**
90674 * Gets the files affected by the path from the program
90675 */
90676 function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
90677 // Since the operation could be cancelled, the signatures are always stored in the cache
90678 // They will be committed once it is safe to use them
90679 // eg when calling this api from tsserver, if there is no cancellation of the operation
90680 // In the other cases the affected files signatures are committed only after the iteration through the result is complete
90681 var signatureCache = cacheToUpdateSignature || ts.createMap();
90682 var sourceFile = programOfThisState.getSourceFileByPath(path);
90683 if (!sourceFile) {
90684 return ts.emptyArray;
90685 }
90686 if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
90687 return [sourceFile];
90688 }
90689 var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
90690 if (!cacheToUpdateSignature) {
90691 // Commit all the signatures in the signature cache
90692 updateSignaturesFromCache(state, signatureCache);
90693 }
90694 return result;
90695 }
90696 BuilderState.getFilesAffectedBy = getFilesAffectedBy;
90697 /**
90698 * Updates the signatures from the cache into state's fileinfo signatures
90699 * This should be called whenever it is safe to commit the state of the builder
90700 */
90701 function updateSignaturesFromCache(state, signatureCache) {
90702 signatureCache.forEach(function (signature, path) {
90703 state.fileInfos.get(path).signature = signature;
90704 state.hasCalledUpdateShapeSignature.set(path, true);
90705 });
90706 }
90707 BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
90708 /**
90709 * Returns if the shape of the signature has changed since last emit
90710 */
90711 function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
90712 ts.Debug.assert(!!sourceFile);
90713 ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
90714 // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
90715 if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) {
90716 return false;
90717 }
90718 var info = state.fileInfos.get(sourceFile.path);
90719 if (!info)
90720 return ts.Debug.fail();
90721 var prevSignature = info.signature;
90722 var latestSignature;
90723 if (sourceFile.isDeclarationFile) {
90724 latestSignature = sourceFile.version;
90725 if (exportedModulesMapCache && latestSignature !== prevSignature) {
90726 // All the references in this file are exported
90727 var references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined;
90728 exportedModulesMapCache.set(sourceFile.path, references || false);
90729 }
90730 }
90731 else {
90732 var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken);
90733 if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) {
90734 latestSignature = computeHash(emitOutput.outputFiles[0].text);
90735 if (exportedModulesMapCache && latestSignature !== prevSignature) {
90736 updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
90737 }
90738 }
90739 else {
90740 latestSignature = prevSignature; // TODO: GH#18217
90741 }
90742 }
90743 cacheToUpdateSignature.set(sourceFile.path, latestSignature);
90744 return !prevSignature || latestSignature !== prevSignature;
90745 }
90746 /**
90747 * Coverts the declaration emit result into exported modules map
90748 */
90749 function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
90750 if (!exportedModulesFromDeclarationEmit) {
90751 exportedModulesMapCache.set(sourceFile.path, false);
90752 return;
90753 }
90754 var exportedModules;
90755 exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
90756 exportedModulesMapCache.set(sourceFile.path, exportedModules || false);
90757 function addExportedModule(exportedModulePath) {
90758 if (exportedModulePath) {
90759 if (!exportedModules) {
90760 exportedModules = ts.createMap();
90761 }
90762 exportedModules.set(exportedModulePath, true);
90763 }
90764 }
90765 }
90766 /**
90767 * Updates the exported modules from cache into state's exported modules map
90768 * This should be called whenever it is safe to commit the state of the builder
90769 */
90770 function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
90771 if (exportedModulesMapCache) {
90772 ts.Debug.assert(!!state.exportedModulesMap);
90773 exportedModulesMapCache.forEach(function (exportedModules, path) {
90774 if (exportedModules) {
90775 state.exportedModulesMap.set(path, exportedModules);
90776 }
90777 else {
90778 state.exportedModulesMap.delete(path);
90779 }
90780 });
90781 }
90782 }
90783 BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
90784 /**
90785 * Get all the dependencies of the sourceFile
90786 */
90787 function getAllDependencies(state, programOfThisState, sourceFile) {
90788 var _a;
90789 var compilerOptions = programOfThisState.getCompilerOptions();
90790 // With --out or --outFile all outputs go into single file, all files depend on each other
90791 if (compilerOptions.outFile || compilerOptions.out) {
90792 return getAllFileNames(state, programOfThisState);
90793 }
90794 // If this is non module emit, or its a global file, it depends on all the source files
90795 if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
90796 return getAllFileNames(state, programOfThisState);
90797 }
90798 // Get the references, traversing deep from the referenceMap
90799 var seenMap = ts.createMap();
90800 var queue = [sourceFile.path];
90801 while (queue.length) {
90802 var path = queue.pop();
90803 if (!seenMap.has(path)) {
90804 seenMap.set(path, true);
90805 var references = state.referencedMap.get(path);
90806 if (references) {
90807 var iterator = references.keys();
90808 for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
90809 queue.push(value);
90810 }
90811 }
90812 }
90813 }
90814 return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) {
90815 var file = programOfThisState.getSourceFileByPath(path);
90816 return file ? file.fileName : path;
90817 }));
90818 }
90819 BuilderState.getAllDependencies = getAllDependencies;
90820 /**
90821 * Gets the names of all files from the program
90822 */
90823 function getAllFileNames(state, programOfThisState) {
90824 if (!state.allFileNames) {
90825 var sourceFiles = programOfThisState.getSourceFiles();
90826 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
90827 }
90828 return state.allFileNames;
90829 }
90830 /**
90831 * Gets the files referenced by the the file path
90832 */
90833 function getReferencedByPaths(state, referencedFilePath) {
90834 return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
90835 var filePath = _a[0], referencesInFile = _a[1];
90836 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
90837 }));
90838 }
90839 /**
90840 * For script files that contains only ambient external modules, although they are not actually external module files,
90841 * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
90842 * there are no point to rebuild all script files if these special files have changed. However, if any statement
90843 * in the file is not ambient external module, we treat it as a regular script file.
90844 */
90845 function containsOnlyAmbientModules(sourceFile) {
90846 for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
90847 var statement = _a[_i];
90848 if (!ts.isModuleWithStringLiteralName(statement)) {
90849 return false;
90850 }
90851 }
90852 return true;
90853 }
90854 /**
90855 * Return true if file contains anything that augments to global scope we need to build them as if
90856 * they are global files as well as module
90857 */
90858 function containsGlobalScopeAugmentation(sourceFile) {
90859 return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
90860 }
90861 /**
90862 * Return true if the file will invalidate all files because it affectes global scope
90863 */
90864 function isFileAffectingGlobalScope(sourceFile) {
90865 return containsGlobalScopeAugmentation(sourceFile) ||
90866 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
90867 }
90868 /**
90869 * Gets all files of the program excluding the default library file
90870 */
90871 function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
90872 // Use cached result
90873 if (state.allFilesExcludingDefaultLibraryFile) {
90874 return state.allFilesExcludingDefaultLibraryFile;
90875 }
90876 var result;
90877 addSourceFile(firstSourceFile);
90878 for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
90879 var sourceFile = _a[_i];
90880 if (sourceFile !== firstSourceFile) {
90881 addSourceFile(sourceFile);
90882 }
90883 }
90884 state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
90885 return state.allFilesExcludingDefaultLibraryFile;
90886 function addSourceFile(sourceFile) {
90887 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
90888 (result || (result = [])).push(sourceFile);
90889 }
90890 }
90891 }
90892 /**
90893 * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
90894 */
90895 function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
90896 var compilerOptions = programOfThisState.getCompilerOptions();
90897 // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
90898 // so returning the file itself is good enough.
90899 if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) {
90900 return [sourceFileWithUpdatedShape];
90901 }
90902 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
90903 }
90904 /**
90905 * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
90906 */
90907 function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
90908 if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
90909 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
90910 }
90911 var compilerOptions = programOfThisState.getCompilerOptions();
90912 if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) {
90913 return [sourceFileWithUpdatedShape];
90914 }
90915 // Now we need to if each file in the referencedBy list has a shape change as well.
90916 // Because if so, its own referencedBy files need to be saved as well to make the
90917 // emitting result consistent with files on disk.
90918 var seenFileNamesMap = ts.createMap();
90919 // Start with the paths this file was referenced by
90920 seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape);
90921 var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
90922 while (queue.length > 0) {
90923 var currentPath = queue.pop();
90924 if (!seenFileNamesMap.has(currentPath)) {
90925 var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
90926 seenFileNamesMap.set(currentPath, currentSourceFile);
90927 if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217
90928 queue.push.apply(// TODO: GH#18217
90929 queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
90930 }
90931 }
90932 }
90933 // Return array of values that needs emit
90934 // Return array of values that needs emit
90935 return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
90936 }
90937 })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
90938})(ts || (ts = {}));
90939/*@internal*/
90940var ts;
90941(function (ts) {
90942 function hasSameKeys(map1, map2) {
90943 // Has same size and every key is present in both maps
90944 return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
90945 }
90946 /**
90947 * Create the state so that we can iterate on changedFiles/affected files
90948 */
90949 function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
90950 var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
90951 state.program = newProgram;
90952 var compilerOptions = newProgram.getCompilerOptions();
90953 state.compilerOptions = compilerOptions;
90954 // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
90955 // With --isolatedModules, emitting changed file doesnt emit dependent files so we cant know of dependent files to retrieve errors so dont cache the errors
90956 if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) {
90957 state.semanticDiagnosticsPerFile = ts.createMap();
90958 }
90959 state.changedFilesSet = ts.createMap();
90960 var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
90961 var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
90962 var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
90963 !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
90964 if (useOldState) {
90965 // Verify the sanity of old state
90966 if (!oldState.currentChangedFilePath) {
90967 var affectedSignatures = oldState.currentAffectedFilesSignatures;
90968 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
90969 }
90970 var changedFilesSet = oldState.changedFilesSet;
90971 if (canCopySemanticDiagnostics) {
90972 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
90973 }
90974 // Copy old state's changed files set
90975 if (changedFilesSet) {
90976 ts.copyEntries(changedFilesSet, state.changedFilesSet);
90977 }
90978 if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
90979 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
90980 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
90981 }
90982 }
90983 // Update changed files and copy semantic diagnostics if we can
90984 var referencedMap = state.referencedMap;
90985 var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
90986 var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
90987 var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
90988 state.fileInfos.forEach(function (info, sourceFilePath) {
90989 var oldInfo;
90990 var newReferences;
90991 // if not using old state, every file is changed
90992 if (!useOldState ||
90993 // File wasnt present in old state
90994 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
90995 // versions dont match
90996 oldInfo.version !== info.version ||
90997 // Referenced files changed
90998 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
90999 // Referenced file was deleted in the new program
91000 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
91001 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
91002 state.changedFilesSet.set(sourceFilePath, true);
91003 }
91004 else if (canCopySemanticDiagnostics) {
91005 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
91006 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
91007 return;
91008 }
91009 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
91010 return;
91011 }
91012 // Unchanged file copy diagnostics
91013 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
91014 if (diagnostics) {
91015 state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
91016 if (!state.semanticDiagnosticsFromOldState) {
91017 state.semanticDiagnosticsFromOldState = ts.createMap();
91018 }
91019 state.semanticDiagnosticsFromOldState.set(sourceFilePath, true);
91020 }
91021 }
91022 });
91023 if (oldCompilerOptions &&
91024 (oldCompilerOptions.outDir !== compilerOptions.outDir ||
91025 oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
91026 (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
91027 // Add all files to affectedFilesPendingEmit since emit changed
91028 state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
91029 if (state.affectedFilesPendingEmitIndex === undefined) {
91030 state.affectedFilesPendingEmitIndex = 0;
91031 }
91032 ts.Debug.assert(state.seenAffectedFiles === undefined);
91033 state.seenAffectedFiles = ts.createMap();
91034 }
91035 return state;
91036 }
91037 function convertToDiagnostics(diagnostics, newProgram) {
91038 if (!diagnostics.length)
91039 return ts.emptyArray;
91040 return diagnostics.map(function (diagnostic) {
91041 var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
91042 result.reportsUnnecessary = diagnostic.reportsUnnecessary;
91043 result.source = diagnostic.source;
91044 var relatedInformation = diagnostic.relatedInformation;
91045 result.relatedInformation = relatedInformation ?
91046 relatedInformation.length ?
91047 relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
91048 ts.emptyArray :
91049 undefined;
91050 return result;
91051 });
91052 }
91053 function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
91054 var file = diagnostic.file, messageText = diagnostic.messageText;
91055 return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
91056 messageText :
91057 convertToDiagnosticMessageChain(messageText, newProgram) });
91058 }
91059 function convertToDiagnosticMessageChain(diagnostic, newProgram) {
91060 return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
91061 }
91062 /**
91063 * Releases program and other related not needed properties
91064 */
91065 function releaseCache(state) {
91066 ts.BuilderState.releaseCache(state);
91067 state.program = undefined;
91068 }
91069 /**
91070 * Creates a clone of the state
91071 */
91072 function cloneBuilderProgramState(state) {
91073 var newState = ts.BuilderState.clone(state);
91074 newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile);
91075 newState.changedFilesSet = ts.cloneMap(state.changedFilesSet);
91076 newState.affectedFiles = state.affectedFiles;
91077 newState.affectedFilesIndex = state.affectedFilesIndex;
91078 newState.currentChangedFilePath = state.currentChangedFilePath;
91079 newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures);
91080 newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap);
91081 newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles);
91082 newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
91083 newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState);
91084 newState.program = state.program;
91085 newState.compilerOptions = state.compilerOptions;
91086 newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit;
91087 newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
91088 newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles);
91089 newState.programEmitComplete = state.programEmitComplete;
91090 return newState;
91091 }
91092 /**
91093 * Verifies that source file is ok to be used in calls that arent handled by next
91094 */
91095 function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
91096 ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path));
91097 }
91098 /**
91099 * This function returns the next affected file to be processed.
91100 * Note that until doneAffected is called it would keep reporting same result
91101 * This is to allow the callers to be able to actually remove affected file only when the operation is complete
91102 * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
91103 */
91104 function getNextAffectedFile(state, cancellationToken, computeHash) {
91105 while (true) {
91106 var affectedFiles = state.affectedFiles;
91107 if (affectedFiles) {
91108 var seenAffectedFiles = state.seenAffectedFiles;
91109 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
91110 while (affectedFilesIndex < affectedFiles.length) {
91111 var affectedFile = affectedFiles[affectedFilesIndex];
91112 if (!seenAffectedFiles.has(affectedFile.path)) {
91113 // Set the next affected file as seen and remove the cached semantic diagnostics
91114 state.affectedFilesIndex = affectedFilesIndex;
91115 cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile);
91116 return affectedFile;
91117 }
91118 seenAffectedFiles.set(affectedFile.path, true);
91119 affectedFilesIndex++;
91120 }
91121 // Remove the changed file from the change set
91122 state.changedFilesSet.delete(state.currentChangedFilePath);
91123 state.currentChangedFilePath = undefined;
91124 // Commit the changes in file signature
91125 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
91126 state.currentAffectedFilesSignatures.clear();
91127 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
91128 state.affectedFiles = undefined;
91129 }
91130 // Get next changed file
91131 var nextKey = state.changedFilesSet.keys().next();
91132 if (nextKey.done) {
91133 // Done
91134 return undefined;
91135 }
91136 // With --out or --outFile all outputs go into single file
91137 // so operations are performed directly on program, return program
91138 var program = ts.Debug.assertDefined(state.program);
91139 var compilerOptions = program.getCompilerOptions();
91140 if (compilerOptions.outFile || compilerOptions.out) {
91141 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
91142 return program;
91143 }
91144 // Get next batch of affected files
91145 state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap();
91146 if (state.exportedModulesMap) {
91147 state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap();
91148 }
91149 state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
91150 state.currentChangedFilePath = nextKey.value;
91151 state.affectedFilesIndex = 0;
91152 state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
91153 }
91154 }
91155 /**
91156 * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
91157 */
91158 function getNextAffectedFilePendingEmit(state) {
91159 var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
91160 if (affectedFilesPendingEmit) {
91161 var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap());
91162 for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
91163 var affectedFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
91164 if (affectedFile && !seenEmittedFiles.has(affectedFile.path)) {
91165 // emit this file
91166 state.affectedFilesPendingEmitIndex = i;
91167 return affectedFile;
91168 }
91169 }
91170 state.affectedFilesPendingEmit = undefined;
91171 state.affectedFilesPendingEmitIndex = undefined;
91172 }
91173 return undefined;
91174 }
91175 /**
91176 * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file
91177 */
91178 function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) {
91179 if (removeSemanticDiagnosticsOf(state, affectedFile.path)) {
91180 // If there are no more diagnostics from old cache, done
91181 return;
91182 }
91183 // Clean lib file diagnostics if its all files excluding default files to emit
91184 if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) {
91185 state.cleanedDiagnosticsOfLibFiles = true;
91186 var program_1 = ts.Debug.assertDefined(state.program);
91187 var options_2 = program_1.getCompilerOptions();
91188 if (ts.forEach(program_1.getSourceFiles(), function (f) {
91189 return program_1.isSourceFileDefaultLibrary(f) &&
91190 !ts.skipTypeChecking(f, options_2) &&
91191 removeSemanticDiagnosticsOf(state, f.path);
91192 })) {
91193 return;
91194 }
91195 }
91196 // If there was change in signature for the changed file,
91197 // then delete the semantic diagnostics for files that are affected by using exports of this module
91198 if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) {
91199 return;
91200 }
91201 ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
91202 var seenFileAndExportsOfFile = ts.createMap();
91203 // Go through exported modules from cache first
91204 // If exported modules has path, all files referencing file exported from are affected
91205 if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
91206 return exportedModules &&
91207 exportedModules.has(affectedFile.path) &&
91208 removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile);
91209 })) {
91210 return;
91211 }
91212 // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
91213 ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
91214 return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
91215 exportedModules.has(affectedFile.path) &&
91216 removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile);
91217 });
91218 }
91219 /**
91220 * removes the semantic diagnostics of files referencing referencedPath and
91221 * returns true if there are no more semantic diagnostics from old state
91222 */
91223 function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile) {
91224 return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
91225 return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile);
91226 });
91227 }
91228 /**
91229 * Removes semantic diagnostics of file and anything that exports this file
91230 */
91231 function removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile) {
91232 if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) {
91233 return false;
91234 }
91235 if (removeSemanticDiagnosticsOf(state, filePath)) {
91236 // If there are no more diagnostics from old cache, done
91237 return true;
91238 }
91239 ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
91240 // Go through exported modules from cache first
91241 // If exported modules has path, all files referencing file exported from are affected
91242 if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
91243 return exportedModules &&
91244 exportedModules.has(filePath) &&
91245 removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile);
91246 })) {
91247 return true;
91248 }
91249 // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
91250 if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
91251 return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
91252 exportedModules.has(filePath) &&
91253 removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile);
91254 })) {
91255 return true;
91256 }
91257 // Remove diagnostics of files that import this file (without going to exports of referencing files)
91258 return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
91259 return referencesInFile.has(filePath) &&
91260 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
91261 removeSemanticDiagnosticsOf(state, referencingFilePath);
91262 } // Dont add to seen since this is not yet done with the export removal
91263 );
91264 }
91265 /**
91266 * Removes semantic diagnostics for path and
91267 * returns true if there are no more semantic diagnostics from the old state
91268 */
91269 function removeSemanticDiagnosticsOf(state, path) {
91270 if (!state.semanticDiagnosticsFromOldState) {
91271 return true;
91272 }
91273 state.semanticDiagnosticsFromOldState.delete(path);
91274 state.semanticDiagnosticsPerFile.delete(path);
91275 return !state.semanticDiagnosticsFromOldState.size;
91276 }
91277 /**
91278 * This is called after completing operation on the next affected file.
91279 * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
91280 */
91281 function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
91282 if (isBuildInfoEmit) {
91283 state.emittedBuildInfo = true;
91284 }
91285 else if (affected === state.program) {
91286 state.changedFilesSet.clear();
91287 state.programEmitComplete = true;
91288 }
91289 else {
91290 state.seenAffectedFiles.set(affected.path, true);
91291 if (isPendingEmit) {
91292 state.affectedFilesPendingEmitIndex++;
91293 }
91294 else {
91295 state.affectedFilesIndex++;
91296 }
91297 }
91298 }
91299 /**
91300 * Returns the result with affected file
91301 */
91302 function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
91303 doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
91304 return { result: result, affected: affected };
91305 }
91306 /**
91307 * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it
91308 * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set
91309 */
91310 function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
91311 var path = sourceFile.path;
91312 if (state.semanticDiagnosticsPerFile) {
91313 var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
91314 // Report the semantic diagnostics from the cache if we already have those diagnostics present
91315 if (cachedDiagnostics) {
91316 return cachedDiagnostics;
91317 }
91318 }
91319 // Diagnostics werent cached, get them from program, and cache the result
91320 var diagnostics = ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
91321 if (state.semanticDiagnosticsPerFile) {
91322 state.semanticDiagnosticsPerFile.set(path, diagnostics);
91323 }
91324 return diagnostics;
91325 }
91326 /**
91327 * Gets the program information to be emitted in buildInfo so that we can use it to create new program
91328 */
91329 function getProgramBuildInfo(state) {
91330 if (state.compilerOptions.outFile || state.compilerOptions.out)
91331 return undefined;
91332 var fileInfos = {};
91333 state.fileInfos.forEach(function (value, key) {
91334 var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
91335 fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
91336 });
91337 var result = { fileInfos: fileInfos, options: state.compilerOptions };
91338 if (state.referencedMap) {
91339 var referencedMap_1 = {};
91340 state.referencedMap.forEach(function (value, key) {
91341 referencedMap_1[key] = ts.arrayFrom(value.keys());
91342 });
91343 result.referencedMap = referencedMap_1;
91344 }
91345 if (state.exportedModulesMap) {
91346 var exportedModulesMap_1 = {};
91347 state.exportedModulesMap.forEach(function (value, key) {
91348 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
91349 // Not in temporary cache, use existing value
91350 if (newValue === undefined)
91351 exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
91352 // Value in cache and has updated value map, use that
91353 else if (newValue)
91354 exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
91355 });
91356 result.exportedModulesMap = exportedModulesMap_1;
91357 }
91358 if (state.semanticDiagnosticsPerFile) {
91359 var semanticDiagnosticsPerFile_1 = [];
91360 // Currently not recording actual errors since those mean no emit for tsc --build
91361 state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
91362 [
91363 key,
91364 state.hasReusableDiagnostic ?
91365 value :
91366 convertToReusableDiagnostics(value)
91367 ] :
91368 key); });
91369 result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
91370 }
91371 return result;
91372 }
91373 function convertToReusableDiagnostics(diagnostics) {
91374 ts.Debug.assert(!!diagnostics.length);
91375 return diagnostics.map(function (diagnostic) {
91376 var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
91377 result.reportsUnnecessary = diagnostic.reportsUnnecessary;
91378 result.source = diagnostic.source;
91379 var relatedInformation = diagnostic.relatedInformation;
91380 result.relatedInformation = relatedInformation ?
91381 relatedInformation.length ?
91382 relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
91383 ts.emptyArray :
91384 undefined;
91385 return result;
91386 });
91387 }
91388 function convertToReusableDiagnosticRelatedInformation(diagnostic) {
91389 var file = diagnostic.file, messageText = diagnostic.messageText;
91390 return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
91391 messageText :
91392 convertToReusableDiagnosticMessageChain(messageText) });
91393 }
91394 function convertToReusableDiagnosticMessageChain(diagnostic) {
91395 return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
91396 }
91397 var BuilderProgramKind;
91398 (function (BuilderProgramKind) {
91399 BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
91400 BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
91401 })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
91402 function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
91403 var host;
91404 var newProgram;
91405 var oldProgram;
91406 if (newProgramOrRootNames === undefined) {
91407 ts.Debug.assert(hostOrOptions === undefined);
91408 host = oldProgramOrHost;
91409 oldProgram = configFileParsingDiagnosticsOrOldProgram;
91410 ts.Debug.assert(!!oldProgram);
91411 newProgram = oldProgram.getProgram();
91412 }
91413 else if (ts.isArray(newProgramOrRootNames)) {
91414 oldProgram = configFileParsingDiagnosticsOrOldProgram;
91415 newProgram = ts.createProgram({
91416 rootNames: newProgramOrRootNames,
91417 options: hostOrOptions,
91418 host: oldProgramOrHost,
91419 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
91420 configFileParsingDiagnostics: configFileParsingDiagnostics,
91421 projectReferences: projectReferences
91422 });
91423 host = oldProgramOrHost;
91424 }
91425 else {
91426 newProgram = newProgramOrRootNames;
91427 host = hostOrOptions;
91428 oldProgram = oldProgramOrHost;
91429 configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
91430 }
91431 return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
91432 }
91433 ts.getBuilderCreationParameters = getBuilderCreationParameters;
91434 function createBuilderProgram(kind, _a) {
91435 var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
91436 // Return same program if underlying program doesnt change
91437 var oldState = oldProgram && oldProgram.getState();
91438 if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
91439 newProgram = undefined; // TODO: GH#18217
91440 oldState = undefined;
91441 return oldProgram;
91442 }
91443 /**
91444 * Create the canonical file name for identity
91445 */
91446 var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
91447 /**
91448 * Computing hash to for signature verification
91449 */
91450 var computeHash = host.createHash || ts.generateDjb2Hash;
91451 var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
91452 var backupState;
91453 newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
91454 // To ensure that we arent storing any references to old program or new program without state
91455 newProgram = undefined; // TODO: GH#18217
91456 oldProgram = undefined;
91457 oldState = undefined;
91458 var result = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
91459 result.getState = function () { return state; };
91460 result.backupState = function () {
91461 ts.Debug.assert(backupState === undefined);
91462 backupState = cloneBuilderProgramState(state);
91463 };
91464 result.restoreState = function () {
91465 state = ts.Debug.assertDefined(backupState);
91466 backupState = undefined;
91467 };
91468 result.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.assertDefined(state.program), sourceFile); };
91469 result.getSemanticDiagnostics = getSemanticDiagnostics;
91470 result.emit = emit;
91471 result.releaseProgram = function () {
91472 releaseCache(state);
91473 backupState = undefined;
91474 };
91475 if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
91476 result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
91477 }
91478 else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
91479 result.emitNextAffectedFile = emitNextAffectedFile;
91480 }
91481 else {
91482 ts.notImplemented();
91483 }
91484 return result;
91485 /**
91486 * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
91487 * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
91488 * in that order would be used to write the files
91489 */
91490 function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
91491 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
91492 var isPendingEmitFile = false;
91493 if (!affected) {
91494 if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
91495 affected = getNextAffectedFilePendingEmit(state);
91496 if (!affected) {
91497 if (state.emittedBuildInfo) {
91498 return undefined;
91499 }
91500 var affected_1 = ts.Debug.assertDefined(state.program);
91501 return toAffectedFileResult(state,
91502 // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
91503 // Otherwise just affected file
91504 affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
91505 /*isPendingEmitFile*/ false,
91506 /*isBuildInfoEmit*/ true);
91507 }
91508 isPendingEmitFile = true;
91509 }
91510 else {
91511 var program = ts.Debug.assertDefined(state.program);
91512 // Check if program uses any prepend project references, if thats the case we cant track of the js files of those, so emit even though there are no changes
91513 if (state.programEmitComplete || !ts.some(program.getProjectReferences(), function (ref) { return !!ref.prepend; })) {
91514 state.programEmitComplete = true;
91515 return undefined;
91516 }
91517 affected = program;
91518 }
91519 }
91520 // Mark seen emitted files if there are pending files to be emitted
91521 if (state.affectedFilesPendingEmit && state.program !== affected) {
91522 (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.path, true);
91523 }
91524 return toAffectedFileResult(state,
91525 // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
91526 // Otherwise just affected file
91527 ts.Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected, isPendingEmitFile);
91528 }
91529 /**
91530 * Emits the JavaScript and declaration files.
91531 * When targetSource file is specified, emits the files corresponding to that source file,
91532 * otherwise for the whole program.
91533 * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
91534 * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
91535 * it will only emit all the affected files instead of whole program
91536 *
91537 * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
91538 * in that order would be used to write the files
91539 */
91540 function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
91541 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
91542 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
91543 if (!targetSourceFile) {
91544 // Emit and report any errors we ran into.
91545 var sourceMaps = [];
91546 var emitSkipped = false;
91547 var diagnostics = void 0;
91548 var emittedFiles = [];
91549 var affectedEmitResult = void 0;
91550 while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
91551 emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
91552 diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
91553 emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
91554 sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
91555 }
91556 return {
91557 emitSkipped: emitSkipped,
91558 diagnostics: diagnostics || ts.emptyArray,
91559 emittedFiles: emittedFiles,
91560 sourceMaps: sourceMaps
91561 };
91562 }
91563 }
91564 return ts.Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
91565 }
91566 /**
91567 * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
91568 * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
91569 */
91570 function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
91571 while (true) {
91572 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
91573 if (!affected) {
91574 // Done
91575 return undefined;
91576 }
91577 else if (affected === state.program) {
91578 // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
91579 return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
91580 }
91581 // Get diagnostics for the affected file if its not ignored
91582 if (ignoreSourceFile && ignoreSourceFile(affected)) {
91583 // Get next affected file
91584 doneWithAffectedFile(state, affected);
91585 continue;
91586 }
91587 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
91588 }
91589 }
91590 /**
91591 * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
91592 * The semantic diagnostics are cached and managed here
91593 * Note that it is assumed that when asked about semantic diagnostics through this API,
91594 * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
91595 * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
91596 * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
91597 */
91598 function getSemanticDiagnostics(sourceFile, cancellationToken) {
91599 assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
91600 var compilerOptions = ts.Debug.assertDefined(state.program).getCompilerOptions();
91601 if (compilerOptions.outFile || compilerOptions.out) {
91602 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
91603 // We dont need to cache the diagnostics just return them from program
91604 return ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
91605 }
91606 if (sourceFile) {
91607 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
91608 }
91609 // When semantic builder asks for diagnostics of the whole program,
91610 // ensure that all the affected files are handled
91611 var affected;
91612 var affectedFilesPendingEmit;
91613 while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) {
91614 if (affected !== state.program && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
91615 (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push(affected.path);
91616 }
91617 doneWithAffectedFile(state, affected);
91618 }
91619 // In case of emit builder, cache the files to be emitted
91620 if (affectedFilesPendingEmit) {
91621 state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit);
91622 // affectedFilesPendingEmitIndex === undefined
91623 // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
91624 // so start from 0 as array would be affectedFilesPendingEmit
91625 // else, continue to iterate from existing index, the current set is appended to existing files
91626 if (state.affectedFilesPendingEmitIndex === undefined) {
91627 state.affectedFilesPendingEmitIndex = 0;
91628 }
91629 }
91630 var diagnostics;
91631 for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
91632 var sourceFile_1 = _a[_i];
91633 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
91634 }
91635 return diagnostics || ts.emptyArray;
91636 }
91637 }
91638 ts.createBuilderProgram = createBuilderProgram;
91639 function getMapOfReferencedSet(mapLike) {
91640 if (!mapLike)
91641 return undefined;
91642 var map = ts.createMap();
91643 // Copies keys/values from template. Note that for..in will not throw if
91644 // template is undefined, and instead will just exit the loop.
91645 for (var key in mapLike) {
91646 if (ts.hasProperty(mapLike, key)) {
91647 map.set(key, ts.arrayToSet(mapLike[key]));
91648 }
91649 }
91650 return map;
91651 }
91652 function createBuildProgramUsingProgramBuildInfo(program) {
91653 var fileInfos = ts.createMapFromTemplate(program.fileInfos);
91654 var state = {
91655 fileInfos: fileInfos,
91656 compilerOptions: program.options,
91657 referencedMap: getMapOfReferencedSet(program.referencedMap),
91658 exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
91659 semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
91660 hasReusableDiagnostic: true
91661 };
91662 return {
91663 getState: function () { return state; },
91664 backupState: ts.noop,
91665 restoreState: ts.noop,
91666 getProgram: ts.notImplemented,
91667 getProgramOrUndefined: ts.returnUndefined,
91668 releaseProgram: ts.noop,
91669 getCompilerOptions: function () { return state.compilerOptions; },
91670 getSourceFile: ts.notImplemented,
91671 getSourceFiles: ts.notImplemented,
91672 getOptionsDiagnostics: ts.notImplemented,
91673 getGlobalDiagnostics: ts.notImplemented,
91674 getConfigFileParsingDiagnostics: ts.notImplemented,
91675 getSyntacticDiagnostics: ts.notImplemented,
91676 getDeclarationDiagnostics: ts.notImplemented,
91677 getSemanticDiagnostics: ts.notImplemented,
91678 emit: ts.notImplemented,
91679 getAllDependencies: ts.notImplemented,
91680 getCurrentDirectory: ts.notImplemented,
91681 emitNextAffectedFile: ts.notImplemented,
91682 getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
91683 };
91684 }
91685 ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
91686 function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
91687 return {
91688 getState: ts.notImplemented,
91689 backupState: ts.noop,
91690 restoreState: ts.noop,
91691 getProgram: getProgram,
91692 getProgramOrUndefined: function () { return state.program; },
91693 releaseProgram: function () { return state.program = undefined; },
91694 getCompilerOptions: function () { return state.compilerOptions; },
91695 getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
91696 getSourceFiles: function () { return getProgram().getSourceFiles(); },
91697 getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
91698 getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
91699 getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
91700 getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
91701 getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
91702 getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
91703 emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
91704 getAllDependencies: ts.notImplemented,
91705 getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
91706 };
91707 function getProgram() {
91708 return ts.Debug.assertDefined(state.program);
91709 }
91710 }
91711 ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
91712})(ts || (ts = {}));
91713(function (ts) {
91714 function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
91715 return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
91716 }
91717 ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
91718 function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
91719 return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
91720 }
91721 ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
91722 function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
91723 var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
91724 return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
91725 }
91726 ts.createAbstractBuilder = createAbstractBuilder;
91727})(ts || (ts = {}));
91728/*@internal*/
91729var ts;
91730(function (ts) {
91731 function isPathIgnored(path) {
91732 return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
91733 }
91734 ts.isPathIgnored = isPathIgnored;
91735 ts.maxNumberOfFilesToIterateForInvalidation = 256;
91736 function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
91737 var filesWithChangedSetOfUnresolvedImports;
91738 var filesWithInvalidatedResolutions;
91739 var filesWithInvalidatedNonRelativeUnresolvedImports;
91740 var allFilesHaveInvalidatedResolution = false;
91741 var nonRelativeExternalModuleResolutions = ts.createMultiMap();
91742 var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
91743 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
91744 // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
91745 // The key in the map is source file's path.
91746 // The values are Map of resolutions with key being name lookedup.
91747 var resolvedModuleNames = ts.createMap();
91748 var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
91749 var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
91750 var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
91751 var resolvedTypeReferenceDirectives = ts.createMap();
91752 var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
91753 /**
91754 * These are the extensions that failed lookup files will have by default,
91755 * any other extension of failed lookup will be store that path in custom failed lookup path
91756 * This helps in not having to comb through all resolutions when files are added/removed
91757 * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
91758 */
91759 var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
91760 var customFailedLookupPaths = ts.createMap();
91761 var directoryWatchesOfFailedLookups = ts.createMap();
91762 var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
91763 var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
91764 // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
91765 var typeRootsWatches = ts.createMap();
91766 return {
91767 startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
91768 finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
91769 // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
91770 // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
91771 startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
91772 finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
91773 resolveModuleNames: resolveModuleNames,
91774 getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
91775 resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
91776 removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
91777 removeResolutionsOfFile: removeResolutionsOfFile,
91778 invalidateResolutionOfFile: invalidateResolutionOfFile,
91779 setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
91780 createHasInvalidatedResolution: createHasInvalidatedResolution,
91781 updateTypeRootsWatch: updateTypeRootsWatch,
91782 closeTypeRootsWatch: closeTypeRootsWatch,
91783 clear: clear
91784 };
91785 function getResolvedModule(resolution) {
91786 return resolution.resolvedModule;
91787 }
91788 function getResolvedTypeReferenceDirective(resolution) {
91789 return resolution.resolvedTypeReferenceDirective;
91790 }
91791 function isInDirectoryPath(dir, file) {
91792 if (dir === undefined || file.length <= dir.length) {
91793 return false;
91794 }
91795 return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
91796 }
91797 function clear() {
91798 ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
91799 customFailedLookupPaths.clear();
91800 nonRelativeExternalModuleResolutions.clear();
91801 closeTypeRootsWatch();
91802 resolvedModuleNames.clear();
91803 resolvedTypeReferenceDirectives.clear();
91804 allFilesHaveInvalidatedResolution = false;
91805 // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
91806 // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
91807 clearPerDirectoryResolutions();
91808 }
91809 function startRecordingFilesWithChangedResolutions() {
91810 filesWithChangedSetOfUnresolvedImports = [];
91811 }
91812 function finishRecordingFilesWithChangedResolutions() {
91813 var collected = filesWithChangedSetOfUnresolvedImports;
91814 filesWithChangedSetOfUnresolvedImports = undefined;
91815 return collected;
91816 }
91817 function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
91818 if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
91819 return false;
91820 }
91821 // Invalidated if file has unresolved imports
91822 var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
91823 return !!value && !!value.length;
91824 }
91825 function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
91826 if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) {
91827 // Any file asked would have invalidated resolution
91828 filesWithInvalidatedResolutions = undefined;
91829 return ts.returnTrue;
91830 }
91831 var collected = filesWithInvalidatedResolutions;
91832 filesWithInvalidatedResolutions = undefined;
91833 return function (path) { return (!!collected && collected.has(path)) ||
91834 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
91835 }
91836 function clearPerDirectoryResolutions() {
91837 perDirectoryResolvedModuleNames.clear();
91838 nonRelativeModuleNameCache.clear();
91839 perDirectoryResolvedTypeReferenceDirectives.clear();
91840 nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
91841 nonRelativeExternalModuleResolutions.clear();
91842 }
91843 function finishCachingPerDirectoryResolution() {
91844 allFilesHaveInvalidatedResolution = false;
91845 filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
91846 clearPerDirectoryResolutions();
91847 directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
91848 if (watcher.refCount === 0) {
91849 directoryWatchesOfFailedLookups.delete(path);
91850 watcher.watcher.close();
91851 }
91852 });
91853 }
91854 function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
91855 var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
91856 // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
91857 if (!resolutionHost.getGlobalCache) {
91858 return primaryResult;
91859 }
91860 // otherwise try to load typings from @types
91861 var globalCache = resolutionHost.getGlobalCache();
91862 if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
91863 // create different collection of failed lookup locations for second pass
91864 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
91865 var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
91866 if (resolvedModule) {
91867 return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) };
91868 }
91869 }
91870 // Default return the result from the first pass
91871 return primaryResult;
91872 }
91873 function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) {
91874 var path = resolutionHost.toPath(containingFile);
91875 var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path);
91876 var dirPath = ts.getDirectoryPath(path);
91877 var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
91878 var perDirectoryResolution = perDirectoryCache.get(dirPath);
91879 if (!perDirectoryResolution) {
91880 perDirectoryResolution = ts.createMap();
91881 perDirectoryCache.set(dirPath, perDirectoryResolution);
91882 }
91883 var resolvedModules = [];
91884 var compilerOptions = resolutionHost.getCompilationSettings();
91885 var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
91886 // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
91887 var program = resolutionHost.getCurrentProgram();
91888 var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
91889 var unmatchedRedirects = oldRedirect ?
91890 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
91891 !!redirectedReference;
91892 var seenNamesInFile = ts.createMap();
91893 for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
91894 var name = names_2[_i];
91895 var resolution = resolutionsInFile.get(name);
91896 // Resolution is valid if it is present and not invalidated
91897 if (!seenNamesInFile.has(name) &&
91898 allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated ||
91899 // If the name is unresolved import that was invalidated, recalculate
91900 (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
91901 var existingResolution = resolution;
91902 var resolutionInDirectory = perDirectoryResolution.get(name);
91903 if (resolutionInDirectory) {
91904 resolution = resolutionInDirectory;
91905 }
91906 else {
91907 resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference);
91908 perDirectoryResolution.set(name, resolution);
91909 }
91910 resolutionsInFile.set(name, resolution);
91911 watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution);
91912 if (existingResolution) {
91913 stopWatchFailedLookupLocationOfResolution(existingResolution);
91914 }
91915 if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
91916 filesWithChangedSetOfUnresolvedImports.push(path);
91917 // reset log changes to avoid recording the same file multiple times
91918 logChanges = false;
91919 }
91920 }
91921 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
91922 seenNamesInFile.set(name, true);
91923 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
91924 }
91925 // Stop watching and remove the unused name
91926 resolutionsInFile.forEach(function (resolution, name) {
91927 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
91928 stopWatchFailedLookupLocationOfResolution(resolution);
91929 resolutionsInFile.delete(name);
91930 }
91931 });
91932 return resolvedModules;
91933 function resolutionIsEqualTo(oldResolution, newResolution) {
91934 if (oldResolution === newResolution) {
91935 return true;
91936 }
91937 if (!oldResolution || !newResolution) {
91938 return false;
91939 }
91940 var oldResult = getResolutionWithResolvedFileName(oldResolution);
91941 var newResult = getResolutionWithResolvedFileName(newResolution);
91942 if (oldResult === newResult) {
91943 return true;
91944 }
91945 if (!oldResult || !newResult) {
91946 return false;
91947 }
91948 return oldResult.resolvedFileName === newResult.resolvedFileName;
91949 }
91950 }
91951 function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
91952 return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective,
91953 /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
91954 /*reusedNames*/ undefined, /*logChanges*/ false);
91955 }
91956 function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
91957 return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule,
91958 /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule);
91959 }
91960 function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
91961 var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
91962 return cache && cache.get(moduleName);
91963 }
91964 function isNodeModulesDirectory(dirPath) {
91965 return ts.endsWith(dirPath, "/node_modules");
91966 }
91967 function isNodeModulesAtTypesDirectory(dirPath) {
91968 return ts.endsWith(dirPath, "/node_modules/@types");
91969 }
91970 /**
91971 * Filter out paths like
91972 * "/", "/user", "/user/username", "/user/username/folderAtRoot",
91973 * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
91974 * @param dirPath
91975 */
91976 function canWatchDirectory(dirPath) {
91977 var rootLength = ts.getRootLength(dirPath);
91978 if (dirPath.length === rootLength) {
91979 // Ignore "/", "c:/"
91980 return false;
91981 }
91982 var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
91983 if (nextDirectorySeparator === -1) {
91984 // ignore "/user", "c:/users" or "c:/folderAtRoot"
91985 return false;
91986 }
91987 if (dirPath.charCodeAt(0) !== 47 /* slash */ &&
91988 dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) {
91989 // Paths like c:/folderAtRoot/subFolder are allowed
91990 return true;
91991 }
91992 for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
91993 searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
91994 if (searchIndex === 0) {
91995 // Folder isnt at expected minimun levels
91996 return false;
91997 }
91998 }
91999 return true;
92000 }
92001 function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
92002 if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
92003 // Ensure failed look up is normalized path
92004 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
92005 ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line
92006 var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1);
92007 if (subDirectoryInRoot !== -1) {
92008 // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
92009 return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) };
92010 }
92011 else {
92012 // Always watch root directory non recursively
92013 return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217
92014 }
92015 }
92016 return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
92017 }
92018 function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
92019 // If directory path contains node module, get the most parent node_modules directory for watching
92020 while (ts.pathContainsNodeModules(dirPath)) {
92021 dir = ts.getDirectoryPath(dir);
92022 dirPath = ts.getDirectoryPath(dirPath);
92023 }
92024 // If the directory is node_modules use it to watch, always watch it recursively
92025 if (isNodeModulesDirectory(dirPath)) {
92026 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
92027 }
92028 var nonRecursive = true;
92029 // Use some ancestor of the root directory
92030 var subDirectoryPath, subDirectory;
92031 if (rootPath !== undefined) {
92032 while (!isInDirectoryPath(dirPath, rootPath)) {
92033 var parentPath = ts.getDirectoryPath(dirPath);
92034 if (parentPath === dirPath) {
92035 break;
92036 }
92037 nonRecursive = false;
92038 subDirectoryPath = dirPath;
92039 subDirectory = dir;
92040 dirPath = parentPath;
92041 dir = ts.getDirectoryPath(dir);
92042 }
92043 }
92044 return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
92045 }
92046 function isPathWithDefaultFailedLookupExtension(path) {
92047 return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
92048 }
92049 function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) {
92050 // No need to set the resolution refCount
92051 if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) {
92052 if (resolution.refCount) {
92053 resolution.refCount++;
92054 }
92055 else {
92056 resolution.refCount = 1;
92057 if (ts.isExternalModuleNameRelative(name)) {
92058 watchFailedLookupLocationOfResolution(resolution);
92059 }
92060 else {
92061 nonRelativeExternalModuleResolutions.add(name, resolution);
92062 }
92063 }
92064 }
92065 }
92066 function watchFailedLookupLocationOfResolution(resolution) {
92067 ts.Debug.assert(!!resolution.refCount);
92068 var failedLookupLocations = resolution.failedLookupLocations;
92069 var setAtRoot = false;
92070 for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
92071 var failedLookupLocation = failedLookupLocations_1[_i];
92072 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
92073 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
92074 if (toWatch) {
92075 var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
92076 // If the failed lookup location path is not one of the supported extensions,
92077 // store it in the custom path
92078 if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
92079 var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
92080 customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
92081 }
92082 if (dirPath === rootPath) {
92083 ts.Debug.assert(!nonRecursive);
92084 setAtRoot = true;
92085 }
92086 else {
92087 setDirectoryWatcher(dir, dirPath, nonRecursive);
92088 }
92089 }
92090 }
92091 if (setAtRoot) {
92092 // This is always non recursive
92093 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
92094 }
92095 }
92096 function setRefCountToUndefined(resolution) {
92097 resolution.refCount = undefined;
92098 }
92099 function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
92100 var program = resolutionHost.getCurrentProgram();
92101 var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ?
92102 setRefCountToUndefined : watchFailedLookupLocationOfResolution;
92103 resolutions.forEach(updateResolution);
92104 }
92105 function setDirectoryWatcher(dir, dirPath, nonRecursive) {
92106 var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
92107 if (dirWatcher) {
92108 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
92109 dirWatcher.refCount++;
92110 }
92111 else {
92112 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
92113 }
92114 }
92115 function stopWatchFailedLookupLocationOfResolution(resolution) {
92116 if (!resolution.refCount) {
92117 return;
92118 }
92119 resolution.refCount--;
92120 if (resolution.refCount) {
92121 return;
92122 }
92123 var failedLookupLocations = resolution.failedLookupLocations;
92124 var removeAtRoot = false;
92125 for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
92126 var failedLookupLocation = failedLookupLocations_2[_i];
92127 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
92128 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
92129 if (toWatch) {
92130 var dirPath = toWatch.dirPath;
92131 var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
92132 if (refCount) {
92133 if (refCount === 1) {
92134 customFailedLookupPaths.delete(failedLookupLocationPath);
92135 }
92136 else {
92137 ts.Debug.assert(refCount > 1);
92138 customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
92139 }
92140 }
92141 if (dirPath === rootPath) {
92142 removeAtRoot = true;
92143 }
92144 else {
92145 removeDirectoryWatcher(dirPath);
92146 }
92147 }
92148 }
92149 if (removeAtRoot) {
92150 removeDirectoryWatcher(rootPath);
92151 }
92152 }
92153 function removeDirectoryWatcher(dirPath) {
92154 var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
92155 // Do not close the watcher yet since it might be needed by other failed lookup locations.
92156 dirWatcher.refCount--;
92157 }
92158 function createDirectoryWatcher(directory, dirPath, nonRecursive) {
92159 return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
92160 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
92161 if (cachedDirectoryStructureHost) {
92162 // Since the file existence changed, update the sourceFiles cache
92163 cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
92164 }
92165 if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
92166 resolutionHost.onInvalidatedResolution();
92167 }
92168 }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
92169 }
92170 function removeResolutionsOfFileFromCache(cache, filePath) {
92171 // Deleted file, stop watching failed lookups for all the resolutions in the file
92172 var resolutions = cache.get(filePath);
92173 if (resolutions) {
92174 resolutions.forEach(stopWatchFailedLookupLocationOfResolution);
92175 cache.delete(filePath);
92176 }
92177 }
92178 function removeResolutionsFromProjectReferenceRedirects(filePath) {
92179 if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
92180 return;
92181 }
92182 var program = resolutionHost.getCurrentProgram();
92183 if (!program) {
92184 return;
92185 }
92186 // If this file is input file for the referenced project, get it
92187 var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
92188 if (!resolvedProjectReference) {
92189 return;
92190 }
92191 // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
92192 resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
92193 }
92194 function removeResolutionsOfFile(filePath) {
92195 removeResolutionsOfFileFromCache(resolvedModuleNames, filePath);
92196 removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath);
92197 }
92198 function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) {
92199 var seen = ts.createMap();
92200 cache.forEach(function (resolutions, containingFilePath) {
92201 var dirPath = ts.getDirectoryPath(containingFilePath);
92202 var seenInDir = seen.get(dirPath);
92203 if (!seenInDir) {
92204 seenInDir = ts.createMap();
92205 seen.set(dirPath, seenInDir);
92206 }
92207 resolutions.forEach(function (resolution, name) {
92208 if (seenInDir.has(name)) {
92209 return;
92210 }
92211 seenInDir.set(name, true);
92212 if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) {
92213 // Mark the file as needing re-evaluation of module resolution instead of using it blindly.
92214 resolution.isInvalidated = true;
92215 (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true);
92216 }
92217 });
92218 });
92219 }
92220 function hasReachedResolutionIterationLimit() {
92221 var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation;
92222 return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize;
92223 }
92224 function invalidateResolutions(isInvalidatedResolution) {
92225 // If more than maxNumberOfFilesToIterateForInvalidation present,
92226 // just invalidated all files and recalculate the resolutions for files instead
92227 if (hasReachedResolutionIterationLimit()) {
92228 allFilesHaveInvalidatedResolution = true;
92229 return;
92230 }
92231 invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule);
92232 invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective);
92233 }
92234 function invalidateResolutionOfFile(filePath) {
92235 removeResolutionsOfFile(filePath);
92236 invalidateResolutions(
92237 // Resolution is invalidated if the resulting file name is same as the deleted file path
92238 function (resolution, getResolutionWithResolvedFileName) {
92239 var result = getResolutionWithResolvedFileName(resolution);
92240 return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217
92241 });
92242 }
92243 function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
92244 ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
92245 filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
92246 }
92247 function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
92248 var isChangedFailedLookupLocation;
92249 if (isCreatingWatchedDirectory) {
92250 // Watching directory is created
92251 // Invalidate any resolution has failed lookup in this directory
92252 isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
92253 }
92254 else {
92255 // If something to do with folder/file starting with "." in node_modules folder, skip it
92256 if (isPathIgnored(fileOrDirectoryPath))
92257 return false;
92258 // Some file or directory in the watching directory is created
92259 // Return early if it does not have any of the watching extension or not the custom failed lookup path
92260 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
92261 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) ||
92262 isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) {
92263 // Invalidate any resolution from this directory
92264 isChangedFailedLookupLocation = function (location) {
92265 var locationPath = resolutionHost.toPath(location);
92266 return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath);
92267 };
92268 }
92269 else {
92270 if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
92271 return false;
92272 }
92273 // Ignore emits from the program
92274 if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
92275 return false;
92276 }
92277 // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
92278 isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; };
92279 }
92280 }
92281 var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); };
92282 var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size;
92283 invalidateResolutions(
92284 // Resolution is invalidated if the resulting file name is same as the deleted file path
92285 hasChangedFailedLookupLocation);
92286 return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount;
92287 }
92288 function closeTypeRootsWatch() {
92289 ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
92290 }
92291 function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
92292 if (allFilesHaveInvalidatedResolution) {
92293 return undefined;
92294 }
92295 if (isInDirectoryPath(rootPath, typeRootPath)) {
92296 return rootPath;
92297 }
92298 var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
92299 return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
92300 }
92301 function createTypeRootsWatch(typeRootPath, typeRoot) {
92302 // Create new watch and recursive info
92303 return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
92304 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
92305 if (cachedDirectoryStructureHost) {
92306 // Since the file existence changed, update the sourceFiles cache
92307 cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
92308 }
92309 // For now just recompile
92310 // We could potentially store more data here about whether it was/would be really be used or not
92311 // and with that determine to trigger compilation but for now this is enough
92312 resolutionHost.onChangedAutomaticTypeDirectiveNames();
92313 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
92314 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
92315 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
92316 if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
92317 resolutionHost.onInvalidatedResolution();
92318 }
92319 }, 1 /* Recursive */);
92320 }
92321 /**
92322 * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
92323 * To be called when compiler options change
92324 */
92325 function updateTypeRootsWatch() {
92326 var options = resolutionHost.getCompilationSettings();
92327 if (options.types) {
92328 // No need to do any watch since resolution cache is going to handle the failed lookups
92329 // for the types added by this
92330 closeTypeRootsWatch();
92331 return;
92332 }
92333 // we need to assume the directories exist to ensure that we can get all the type root directories that get included
92334 // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
92335 var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
92336 if (typeRoots) {
92337 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
92338 createNewValue: createTypeRootsWatch,
92339 onDeleteValue: ts.closeFileWatcher
92340 });
92341 }
92342 else {
92343 closeTypeRootsWatch();
92344 }
92345 }
92346 /**
92347 * Use this function to return if directory exists to get type roots to watch
92348 * If we return directory exists then only the paths will be added to type roots
92349 * Hence return true for all directories except root directories which are filtered from watching
92350 */
92351 function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
92352 var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
92353 var dirPath = resolutionHost.toPath(dir);
92354 return dirPath === rootPath || canWatchDirectory(dirPath);
92355 }
92356 }
92357 ts.createResolutionCache = createResolutionCache;
92358})(ts || (ts = {}));
92359// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
92360/* @internal */
92361var ts;
92362(function (ts) {
92363 var moduleSpecifiers;
92364 (function (moduleSpecifiers) {
92365 var RelativePreference;
92366 (function (RelativePreference) {
92367 RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
92368 RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
92369 RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
92370 })(RelativePreference || (RelativePreference = {}));
92371 // See UserPreferences#importPathEnding
92372 var Ending;
92373 (function (Ending) {
92374 Ending[Ending["Minimal"] = 0] = "Minimal";
92375 Ending[Ending["Index"] = 1] = "Index";
92376 Ending[Ending["JsExtension"] = 2] = "JsExtension";
92377 })(Ending || (Ending = {}));
92378 function getPreferences(_a, compilerOptions, importingSourceFile) {
92379 var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
92380 return {
92381 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
92382 ending: getEnding(),
92383 };
92384 function getEnding() {
92385 switch (importModuleSpecifierEnding) {
92386 case "minimal": return 0 /* Minimal */;
92387 case "index": return 1 /* Index */;
92388 case "js": return 2 /* JsExtension */;
92389 default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
92390 : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
92391 }
92392 }
92393 }
92394 function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
92395 return {
92396 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
92397 ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */
92398 : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
92399 };
92400 }
92401 function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) {
92402 var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
92403 if (res === oldImportSpecifier)
92404 return undefined;
92405 return res;
92406 }
92407 moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
92408 // Note: importingSourceFile is just for usesJsExtensionOnImports
92409 function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) {
92410 if (preferences === void 0) { preferences = {}; }
92411 return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile));
92412 }
92413 moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
92414 function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) {
92415 var info = getInfo(importingSourceFileName, host);
92416 var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap);
92417 return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
92418 getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
92419 }
92420 // Returns an import for each symlink and for the realpath.
92421 function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) {
92422 var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
92423 if (ambient)
92424 return [ambient];
92425 var info = getInfo(importingSourceFile.path, host);
92426 var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
92427 var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap);
92428 var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
92429 var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
92430 return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
92431 }
92432 moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
92433 // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
92434 function getInfo(importingSourceFileName, host) {
92435 var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
92436 var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
92437 return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
92438 }
92439 function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
92440 var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
92441 var ending = _b.ending, relativePreference = _b.relativePreference;
92442 var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
92443 var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) ||
92444 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
92445 if (!baseUrl || relativePreference === 0 /* Relative */) {
92446 return relativePath;
92447 }
92448 var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
92449 if (!relativeToBaseUrl) {
92450 return relativePath;
92451 }
92452 var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
92453 var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
92454 var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
92455 if (relativePreference === 1 /* NonRelative */) {
92456 return nonRelative;
92457 }
92458 if (relativePreference !== 2 /* Auto */)
92459 ts.Debug.assertNever(relativePreference);
92460 // Prefer a relative import over a baseUrl import if it has fewer components.
92461 return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
92462 }
92463 function countPathComponents(path) {
92464 var count = 0;
92465 for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
92466 if (path.charCodeAt(i) === 47 /* slash */)
92467 count++;
92468 }
92469 return count;
92470 }
92471 moduleSpecifiers.countPathComponents = countPathComponents;
92472 function usesJsExtensionOnImports(_a) {
92473 var imports = _a.imports;
92474 return ts.firstDefined(imports, function (_a) {
92475 var text = _a.text;
92476 return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined;
92477 }) || false;
92478 }
92479 function stringsEqual(a, b, getCanonicalFileName) {
92480 return getCanonicalFileName(a) === getCanonicalFileName(b);
92481 }
92482 // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
92483 // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
92484 function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
92485 return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
92486 }
92487 function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
92488 var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
92489 var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
92490 while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
92491 !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
92492 stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) {
92493 aParts.pop();
92494 bParts.pop();
92495 }
92496 return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)];
92497 }
92498 function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
92499 var result = ts.createMap();
92500 var symlinks = ts.mapDefined(files, function (sf) {
92501 return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) {
92502 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
92503 });
92504 });
92505 for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
92506 var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
92507 var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1];
92508 result.set(commonOriginal, commonResolved);
92509 }
92510 return result;
92511 }
92512 /**
92513 * Looks for existing imports that use symlinks to this module.
92514 * Symlinks will be returned first so they are preferred over the real path.
92515 */
92516 function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) {
92517 var redirects = redirectTargetsMap.get(importedFileName);
92518 var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName];
92519 var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : "";
92520 var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
92521 var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd);
92522 var result = [];
92523 var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive;
92524 links.forEach(function (resolved, path) {
92525 if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) {
92526 return; // Don't want to a package to globally import from itself
92527 }
92528 var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; });
92529 if (target === undefined)
92530 return;
92531 var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName);
92532 var option = ts.resolvePath(path, relative);
92533 if (!host.fileExists || host.fileExists(option)) {
92534 result.push(option);
92535 }
92536 });
92537 result.push.apply(result, targets);
92538 return result;
92539 }
92540 function tryGetModuleNameFromAmbientModule(moduleSymbol) {
92541 var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
92542 if (decl) {
92543 return decl.name.text;
92544 }
92545 }
92546 function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
92547 for (var key in paths) {
92548 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
92549 var patternText_1 = _a[_i];
92550 var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
92551 var indexOfStar = pattern.indexOf("*");
92552 if (indexOfStar !== -1) {
92553 var prefix = pattern.substr(0, indexOfStar);
92554 var suffix = pattern.substr(indexOfStar + 1);
92555 if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
92556 ts.startsWith(relativeToBaseUrl, prefix) &&
92557 ts.endsWith(relativeToBaseUrl, suffix) ||
92558 !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
92559 var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
92560 return key.replace("*", matchedStar);
92561 }
92562 }
92563 else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
92564 return key;
92565 }
92566 }
92567 }
92568 }
92569 function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) {
92570 var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
92571 if (normalizedTargetPath === undefined) {
92572 return undefined;
92573 }
92574 var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
92575 var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
92576 return ts.removeFileExtension(relativePath);
92577 }
92578 function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) {
92579 var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
92580 if (!host.fileExists || !host.readFile) {
92581 return undefined;
92582 }
92583 var parts = getNodeModulePathParts(moduleFileName);
92584 if (!parts) {
92585 return undefined;
92586 }
92587 var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex);
92588 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
92589 var packageJsonContent = host.fileExists(packageJsonPath)
92590 ? JSON.parse(host.readFile(packageJsonPath))
92591 : undefined;
92592 var versionPaths = packageJsonContent && packageJsonContent.typesVersions
92593 ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
92594 : undefined;
92595 if (versionPaths) {
92596 var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1);
92597 var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
92598 if (fromPaths !== undefined) {
92599 moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths);
92600 }
92601 }
92602 // Simplify the full file path to something that can be resolved by Node.
92603 // If the module could be imported by a directory name, use that directory's name
92604 var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName);
92605 // Get a path that's relative to node_modules or the importing file's path
92606 // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
92607 if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex))))
92608 return undefined;
92609 // If the module was found in @types, get the actual Node package name
92610 var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
92611 var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
92612 // For classic resolution, only allow importing from node_modules/@types, not other node_modules
92613 return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
92614 function getDirectoryOrExtensionlessFileName(path) {
92615 // If the file is the main module, it can be imported by the package name
92616 if (packageJsonContent) {
92617 var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
92618 if (mainFileRelative) {
92619 var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
92620 if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) {
92621 return packageRootPath;
92622 }
92623 }
92624 }
92625 // We still have a file name - remove the extension
92626 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
92627 // If the file is /index, it can be imported by its directory name
92628 // IFF there is not _also_ a file by the same name
92629 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
92630 return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
92631 }
92632 return fullModulePathWithoutExtension;
92633 }
92634 }
92635 function tryGetAnyFileFromPath(host, path) {
92636 if (!host.fileExists)
92637 return;
92638 // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
92639 var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
92640 for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
92641 var e = extensions_3[_i];
92642 var fullPath = path + e;
92643 if (host.fileExists(fullPath)) {
92644 return fullPath;
92645 }
92646 }
92647 }
92648 function getNodeModulePathParts(fullPath) {
92649 // If fullPath can't be valid module file within node_modules, returns undefined.
92650 // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
92651 // Returns indices: ^ ^ ^ ^
92652 var topLevelNodeModulesIndex = 0;
92653 var topLevelPackageNameIndex = 0;
92654 var packageRootIndex = 0;
92655 var fileNameIndex = 0;
92656 var States;
92657 (function (States) {
92658 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
92659 States[States["NodeModules"] = 1] = "NodeModules";
92660 States[States["Scope"] = 2] = "Scope";
92661 States[States["PackageContent"] = 3] = "PackageContent";
92662 })(States || (States = {}));
92663 var partStart = 0;
92664 var partEnd = 0;
92665 var state = 0 /* BeforeNodeModules */;
92666 while (partEnd >= 0) {
92667 partStart = partEnd;
92668 partEnd = fullPath.indexOf("/", partStart + 1);
92669 switch (state) {
92670 case 0 /* BeforeNodeModules */:
92671 if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
92672 topLevelNodeModulesIndex = partStart;
92673 topLevelPackageNameIndex = partEnd;
92674 state = 1 /* NodeModules */;
92675 }
92676 break;
92677 case 1 /* NodeModules */:
92678 case 2 /* Scope */:
92679 if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
92680 state = 2 /* Scope */;
92681 }
92682 else {
92683 packageRootIndex = partEnd;
92684 state = 3 /* PackageContent */;
92685 }
92686 break;
92687 case 3 /* PackageContent */:
92688 if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
92689 state = 1 /* NodeModules */;
92690 }
92691 else {
92692 state = 3 /* PackageContent */;
92693 }
92694 break;
92695 }
92696 }
92697 fileNameIndex = partStart;
92698 return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
92699 }
92700 function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
92701 return ts.firstDefined(rootDirs, function (rootDir) {
92702 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
92703 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
92704 });
92705 }
92706 function removeExtensionAndIndexPostFix(fileName, ending, options) {
92707 if (ts.fileExtensionIs(fileName, ".json" /* Json */))
92708 return fileName;
92709 var noExtension = ts.removeFileExtension(fileName);
92710 switch (ending) {
92711 case 0 /* Minimal */:
92712 return ts.removeSuffix(noExtension, "/index");
92713 case 1 /* Index */:
92714 return noExtension;
92715 case 2 /* JsExtension */:
92716 return noExtension + getJSExtensionForFile(fileName, options);
92717 default:
92718 return ts.Debug.assertNever(ending);
92719 }
92720 }
92721 function getJSExtensionForFile(fileName, options) {
92722 var ext = ts.extensionFromPath(fileName);
92723 switch (ext) {
92724 case ".ts" /* Ts */:
92725 case ".d.ts" /* Dts */:
92726 return ".js" /* Js */;
92727 case ".tsx" /* Tsx */:
92728 return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
92729 case ".js" /* Js */:
92730 case ".jsx" /* Jsx */:
92731 case ".json" /* Json */:
92732 return ext;
92733 case ".tsbuildinfo" /* TsBuildInfo */:
92734 return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
92735 default:
92736 return ts.Debug.assertNever(ext);
92737 }
92738 }
92739 function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
92740 var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
92741 return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
92742 }
92743 function isPathRelativeToParent(path) {
92744 return ts.startsWith(path, "..");
92745 }
92746 })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
92747})(ts || (ts = {}));
92748/*@internal*/
92749var ts;
92750(function (ts) {
92751 var sysFormatDiagnosticsHost = ts.sys ? {
92752 getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
92753 getNewLine: function () { return ts.sys.newLine; },
92754 getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
92755 } : undefined; // TODO: GH#18217
92756 /**
92757 * Create a function that reports error by writing to the system and handles the formating of the diagnostic
92758 */
92759 function createDiagnosticReporter(system, pretty) {
92760 var host = system === ts.sys ? sysFormatDiagnosticsHost : {
92761 getCurrentDirectory: function () { return system.getCurrentDirectory(); },
92762 getNewLine: function () { return system.newLine; },
92763 getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
92764 };
92765 if (!pretty) {
92766 return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
92767 }
92768 var diagnostics = new Array(1);
92769 return function (diagnostic) {
92770 diagnostics[0] = diagnostic;
92771 system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
92772 diagnostics[0] = undefined; // TODO: GH#18217
92773 };
92774 }
92775 ts.createDiagnosticReporter = createDiagnosticReporter;
92776 /**
92777 * @returns Whether the screen was cleared.
92778 */
92779 function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
92780 if (system.clearScreen &&
92781 !options.preserveWatchOutput &&
92782 !options.extendedDiagnostics &&
92783 !options.diagnostics &&
92784 ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
92785 system.clearScreen();
92786 return true;
92787 }
92788 return false;
92789 }
92790 ts.screenStartingMessageCodes = [
92791 ts.Diagnostics.Starting_compilation_in_watch_mode.code,
92792 ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
92793 ];
92794 function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
92795 return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
92796 ? newLine + newLine
92797 : newLine;
92798 }
92799 /**
92800 * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
92801 */
92802 function createWatchStatusReporter(system, pretty) {
92803 return pretty ?
92804 function (diagnostic, newLine, options) {
92805 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
92806 var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] ";
92807 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
92808 system.write(output);
92809 } :
92810 function (diagnostic, newLine, options) {
92811 var output = "";
92812 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
92813 output += newLine;
92814 }
92815 output += new Date().toLocaleTimeString() + " - ";
92816 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
92817 system.write(output);
92818 };
92819 }
92820 ts.createWatchStatusReporter = createWatchStatusReporter;
92821 /** Parses config file using System interface */
92822 function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) {
92823 var host = system;
92824 host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); };
92825 var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
92826 host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
92827 return result;
92828 }
92829 ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
92830 function getErrorCountForSummary(diagnostics) {
92831 return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
92832 }
92833 ts.getErrorCountForSummary = getErrorCountForSummary;
92834 function getWatchErrorSummaryDiagnosticMessage(errorCount) {
92835 return errorCount === 1 ?
92836 ts.Diagnostics.Found_1_error_Watching_for_file_changes :
92837 ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
92838 }
92839 ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
92840 function getErrorSummaryText(errorCount, newLine) {
92841 if (errorCount === 0)
92842 return "";
92843 var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
92844 return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
92845 }
92846 ts.getErrorSummaryText = getErrorSummaryText;
92847 /**
92848 * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
92849 */
92850 function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) {
92851 // First get and report any syntactic errors.
92852 var diagnostics = program.getConfigFileParsingDiagnostics().slice();
92853 var configFileParsingDiagnosticsLength = diagnostics.length;
92854 ts.addRange(diagnostics, program.getSyntacticDiagnostics());
92855 // If we didn't have any syntactic errors, then also try getting the global and
92856 // semantic errors.
92857 if (diagnostics.length === configFileParsingDiagnosticsLength) {
92858 ts.addRange(diagnostics, program.getOptionsDiagnostics());
92859 ts.addRange(diagnostics, program.getGlobalDiagnostics());
92860 if (diagnostics.length === configFileParsingDiagnosticsLength) {
92861 ts.addRange(diagnostics, program.getSemanticDiagnostics());
92862 }
92863 }
92864 // Emit and report any errors we ran into.
92865 var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics;
92866 ts.addRange(diagnostics, emitDiagnostics);
92867 ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic);
92868 if (writeFileName) {
92869 var currentDir_1 = program.getCurrentDirectory();
92870 ts.forEach(emittedFiles, function (file) {
92871 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
92872 writeFileName("TSFILE: " + filepath);
92873 });
92874 if (program.getCompilerOptions().listFiles) {
92875 ts.forEach(program.getSourceFiles(), function (file) {
92876 writeFileName(file.fileName);
92877 });
92878 }
92879 }
92880 if (reportSummary) {
92881 reportSummary(getErrorCountForSummary(diagnostics));
92882 }
92883 if (emitSkipped && diagnostics.length > 0) {
92884 // If the emitter didn't emit anything, then pass that value along.
92885 return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
92886 }
92887 else if (diagnostics.length > 0) {
92888 // The emitter emitted something, inform the caller if that happened in the presence
92889 // of diagnostics or not.
92890 return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
92891 }
92892 return ts.ExitStatus.Success;
92893 }
92894 ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
92895 var noopFileWatcher = { close: ts.noop };
92896 function createWatchHost(system, reportWatchStatus) {
92897 if (system === void 0) { system = ts.sys; }
92898 var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
92899 return {
92900 onWatchStatusChange: onWatchStatusChange,
92901 watchFile: ts.maybeBind(system, system.watchFile) || (function () { return noopFileWatcher; }),
92902 watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return noopFileWatcher; }),
92903 setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
92904 clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
92905 };
92906 }
92907 ts.createWatchHost = createWatchHost;
92908 var WatchType;
92909 (function (WatchType) {
92910 WatchType["ConfigFile"] = "Config file";
92911 WatchType["SourceFile"] = "Source file";
92912 WatchType["MissingFile"] = "Missing file";
92913 WatchType["WildcardDirectory"] = "Wild card directory";
92914 WatchType["FailedLookupLocations"] = "Failed Lookup Locations";
92915 WatchType["TypeRoots"] = "Type roots";
92916 })(WatchType = ts.WatchType || (ts.WatchType = {}));
92917 function createWatchFactory(host, options) {
92918 var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
92919 var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
92920 var result = ts.getWatchFactory(watchLogLevel, writeLog);
92921 result.writeLog = writeLog;
92922 return result;
92923 }
92924 ts.createWatchFactory = createWatchFactory;
92925 function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
92926 if (directoryStructureHost === void 0) { directoryStructureHost = host; }
92927 var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
92928 var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
92929 return {
92930 getSourceFile: function (fileName, languageVersion, onError) {
92931 var text;
92932 try {
92933 ts.performance.mark("beforeIORead");
92934 text = host.readFile(fileName, getCompilerOptions().charset);
92935 ts.performance.mark("afterIORead");
92936 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
92937 }
92938 catch (e) {
92939 if (onError) {
92940 onError(e.message);
92941 }
92942 text = "";
92943 }
92944 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
92945 },
92946 getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
92947 getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
92948 writeFile: writeFile,
92949 getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
92950 useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
92951 getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
92952 getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
92953 fileExists: function (f) { return host.fileExists(f); },
92954 readFile: function (f) { return host.readFile(f); },
92955 trace: ts.maybeBind(host, host.trace),
92956 directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
92957 getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
92958 realpath: ts.maybeBind(host, host.realpath),
92959 getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
92960 createHash: ts.maybeBind(host, host.createHash),
92961 readDirectory: ts.maybeBind(host, host.readDirectory),
92962 };
92963 function ensureDirectoriesExist(directoryPath) {
92964 if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) {
92965 var parentDirectory = ts.getDirectoryPath(directoryPath);
92966 ensureDirectoriesExist(parentDirectory);
92967 if (host.createDirectory)
92968 host.createDirectory(directoryPath);
92969 }
92970 }
92971 function writeFile(fileName, text, writeByteOrderMark, onError) {
92972 try {
92973 ts.performance.mark("beforeIOWrite");
92974 ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName)));
92975 host.writeFile(fileName, text, writeByteOrderMark);
92976 ts.performance.mark("afterIOWrite");
92977 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
92978 }
92979 catch (e) {
92980 if (onError) {
92981 onError(e.message);
92982 }
92983 }
92984 }
92985 }
92986 ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
92987 function setGetSourceFileAsHashVersioned(compilerHost, host) {
92988 var originalGetSourceFile = compilerHost.getSourceFile;
92989 var computeHash = host.createHash || ts.generateDjb2Hash;
92990 compilerHost.getSourceFile = function () {
92991 var args = [];
92992 for (var _i = 0; _i < arguments.length; _i++) {
92993 args[_i] = arguments[_i];
92994 }
92995 var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
92996 if (result) {
92997 result.version = computeHash.call(host, result.text);
92998 }
92999 return result;
93000 };
93001 }
93002 ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
93003 /**
93004 * Creates the watch compiler host that can be extended with config file or root file names and options host
93005 */
93006 function createProgramHost(system, createProgram) {
93007 var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
93008 var host = system;
93009 host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!)
93010 return {
93011 useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
93012 getNewLine: function () { return system.newLine; },
93013 getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
93014 getDefaultLibLocation: getDefaultLibLocation,
93015 getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
93016 fileExists: function (path) { return system.fileExists(path); },
93017 readFile: function (path, encoding) { return system.readFile(path, encoding); },
93018 directoryExists: function (path) { return system.directoryExists(path); },
93019 getDirectories: function (path) { return system.getDirectories(path); },
93020 readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
93021 realpath: ts.maybeBind(system, system.realpath),
93022 getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
93023 trace: function (s) { return system.write(s + system.newLine); },
93024 createDirectory: function (path) { return system.createDirectory(path); },
93025 writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
93026 onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
93027 createHash: ts.maybeBind(system, system.createHash),
93028 createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
93029 };
93030 }
93031 ts.createProgramHost = createProgramHost;
93032 /**
93033 * Creates the watch compiler host that can be extended with config file or root file names and options host
93034 */
93035 function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
93036 if (system === void 0) { system = ts.sys; }
93037 var writeFileName = function (s) { return system.write(s + system.newLine); };
93038 var result = createProgramHost(system, createProgram);
93039 ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
93040 result.afterProgramCreate = function (builderProgram) {
93041 var compilerOptions = builderProgram.getCompilerOptions();
93042 var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
93043 emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); });
93044 };
93045 return result;
93046 }
93047 /**
93048 * Report error and exit
93049 */
93050 function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
93051 reportDiagnostic(diagnostic);
93052 system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
93053 }
93054 /**
93055 * Creates the watch compiler host from system for config file in watch mode
93056 */
93057 function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) {
93058 var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
93059 var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
93060 host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
93061 host.configFileName = configFileName;
93062 host.optionsToExtend = optionsToExtend;
93063 return host;
93064 }
93065 ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
93066 /**
93067 * Creates the watch compiler host from system for compiling root files and options in watch mode
93068 */
93069 function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
93070 var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
93071 host.rootFiles = rootFiles;
93072 host.options = options;
93073 host.projectReferences = projectReferences;
93074 return host;
93075 }
93076 ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
93077 function readBuilderProgram(compilerOptions, readFile) {
93078 if (compilerOptions.out || compilerOptions.outFile)
93079 return undefined;
93080 var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions);
93081 if (!buildInfoPath)
93082 return undefined;
93083 var content = readFile(buildInfoPath);
93084 if (!content)
93085 return undefined;
93086 var buildInfo = ts.getBuildInfo(content);
93087 if (buildInfo.version !== ts.version)
93088 return undefined;
93089 if (!buildInfo.program)
93090 return undefined;
93091 return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
93092 }
93093 ts.readBuilderProgram = readBuilderProgram;
93094 function createIncrementalCompilerHost(options, system) {
93095 if (system === void 0) { system = ts.sys; }
93096 var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
93097 host.createHash = ts.maybeBind(system, system.createHash);
93098 setGetSourceFileAsHashVersioned(host, system);
93099 ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
93100 return host;
93101 }
93102 ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
93103 function createIncrementalProgram(_a) {
93104 var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
93105 host = host || createIncrementalCompilerHost(options);
93106 createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
93107 var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); });
93108 return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
93109 }
93110 function performIncrementalCompilation(input) {
93111 var system = input.system || ts.sys;
93112 var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system));
93113 var builderProgram = createIncrementalProgram(input);
93114 var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
93115 if (input.afterProgramEmitAndDiagnostics)
93116 input.afterProgramEmitAndDiagnostics(builderProgram);
93117 return exitStatus;
93118 }
93119 ts.performIncrementalCompilation = performIncrementalCompilation;
93120})(ts || (ts = {}));
93121(function (ts) {
93122 function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
93123 if (ts.isArray(rootFilesOrConfigFileName)) {
93124 return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217
93125 }
93126 else {
93127 return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus);
93128 }
93129 }
93130 ts.createWatchCompilerHost = createWatchCompilerHost;
93131 function createWatchProgram(host) {
93132 var builderProgram;
93133 var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
93134 var missingFilesMap; // Map of file watchers for the missing files
93135 var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
93136 var timerToUpdateProgram; // timer callback to recompile the program
93137 var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info
93138 var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files
93139 var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
93140 var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed
93141 var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
93142 var currentDirectory = host.getCurrentDirectory();
93143 var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram;
93144 var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences;
93145 var configFileSpecs;
93146 var configFileParsingDiagnostics;
93147 var canConfigFileJsonReportNoInputFiles = false;
93148 var hasChangedConfigFileParsingErrors = false;
93149 var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
93150 if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) {
93151 host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost);
93152 }
93153 var directoryStructureHost = cachedDirectoryStructureHost || host;
93154 var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
93155 // From tsc we want to get already parsed result and hence check for rootFileNames
93156 var newLine = updateNewLine();
93157 if (configFileName && host.configFileParsingResult) {
93158 setConfigFileParsingResult(host.configFileParsingResult);
93159 newLine = updateNewLine();
93160 }
93161 reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
93162 if (configFileName && !host.configFileParsingResult) {
93163 newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
93164 ts.Debug.assert(!rootFileNames);
93165 parseConfigFile();
93166 newLine = updateNewLine();
93167 }
93168 var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
93169 var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
93170 writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
93171 var configFileWatcher;
93172 if (configFileName) {
93173 configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
93174 }
93175 var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
93176 ts.setGetSourceFileAsHashVersioned(compilerHost, host);
93177 // Members for CompilerHost
93178 var getNewSourceFile = compilerHost.getSourceFile;
93179 compilerHost.getSourceFile = function (fileName) {
93180 var args = [];
93181 for (var _i = 1; _i < arguments.length; _i++) {
93182 args[_i - 1] = arguments[_i];
93183 }
93184 return getVersionedSourceFileByPath.apply(void 0, [fileName, toPath(fileName)].concat(args));
93185 };
93186 compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
93187 compilerHost.getNewLine = function () { return newLine; };
93188 compilerHost.fileExists = fileExists;
93189 compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
93190 // Members for ResolutionCacheHost
93191 compilerHost.toPath = toPath;
93192 compilerHost.getCompilationSettings = function () { return compilerOptions; };
93193 compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations" /* FailedLookupLocations */); };
93194 compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots" /* TypeRoots */); };
93195 compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
93196 compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
93197 compilerHost.onChangedAutomaticTypeDirectiveNames = function () {
93198 hasChangedAutomaticTypeDirectiveNames = true;
93199 scheduleProgramUpdate();
93200 };
93201 compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation;
93202 compilerHost.getCurrentProgram = getCurrentProgram;
93203 compilerHost.writeLog = writeLog;
93204 // Cache for the module resolution
93205 var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
93206 ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
93207 currentDirectory,
93208 /*logChangesWhenResolvingModule*/ false);
93209 // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
93210 compilerHost.resolveModuleNames = host.resolveModuleNames ?
93211 (function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); }) :
93212 (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
93213 compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
93214 (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) :
93215 (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
93216 var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
93217 builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); });
93218 synchronizeProgram();
93219 // Update the wild card directory watch
93220 watchConfigFileWildCardDirectories();
93221 return configFileName ?
93222 { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } :
93223 { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close };
93224 function close() {
93225 resolutionCache.clear();
93226 ts.clearMap(sourceFilesCache, function (value) {
93227 if (value && value.fileWatcher) {
93228 value.fileWatcher.close();
93229 value.fileWatcher = undefined;
93230 }
93231 });
93232 if (configFileWatcher) {
93233 configFileWatcher.close();
93234 configFileWatcher = undefined;
93235 }
93236 if (watchedWildcardDirectories) {
93237 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
93238 watchedWildcardDirectories = undefined;
93239 }
93240 if (missingFilesMap) {
93241 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
93242 missingFilesMap = undefined;
93243 }
93244 }
93245 function getCurrentBuilderProgram() {
93246 return builderProgram;
93247 }
93248 function getCurrentProgram() {
93249 return builderProgram && builderProgram.getProgramOrUndefined();
93250 }
93251 function synchronizeProgram() {
93252 writeLog("Synchronizing program");
93253 var program = getCurrentBuilderProgram();
93254 if (hasChangedCompilerOptions) {
93255 newLine = updateNewLine();
93256 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
93257 resolutionCache.clear();
93258 }
93259 }
93260 // All resolutions are invalid if user provided resolutions
93261 var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
93262 if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
93263 if (hasChangedConfigFileParsingErrors) {
93264 builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
93265 hasChangedConfigFileParsingErrors = false;
93266 }
93267 }
93268 else {
93269 createNewProgram(hasInvalidatedResolution);
93270 }
93271 if (host.afterProgramCreate) {
93272 host.afterProgramCreate(builderProgram);
93273 }
93274 return builderProgram;
93275 }
93276 function createNewProgram(hasInvalidatedResolution) {
93277 // Compile the program
93278 writeLog("CreatingProgramWith::");
93279 writeLog(" roots: " + JSON.stringify(rootFileNames));
93280 writeLog(" options: " + JSON.stringify(compilerOptions));
93281 var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
93282 hasChangedCompilerOptions = false;
93283 hasChangedConfigFileParsingErrors = false;
93284 resolutionCache.startCachingPerDirectoryResolution();
93285 compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
93286 compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
93287 builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
93288 resolutionCache.finishCachingPerDirectoryResolution();
93289 // Update watches
93290 ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath);
93291 if (needsUpdateInTypeRootWatch) {
93292 resolutionCache.updateTypeRootsWatch();
93293 }
93294 if (missingFilePathsRequestedForRelease) {
93295 // These are the paths that program creater told us as not in use any more but were missing on the disk.
93296 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
93297 // if there is already watcher for it (for missing files)
93298 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
93299 // so that at later time we have correct result of their presence
93300 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
93301 var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
93302 if (!missingFilesMap.has(missingFilePath)) {
93303 sourceFilesCache.delete(missingFilePath);
93304 }
93305 }
93306 missingFilePathsRequestedForRelease = undefined;
93307 }
93308 }
93309 function updateRootFileNames(files) {
93310 ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
93311 rootFileNames = files;
93312 scheduleProgramUpdate();
93313 }
93314 function updateNewLine() {
93315 return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
93316 }
93317 function toPath(fileName) {
93318 return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
93319 }
93320 function isFileMissingOnHost(hostSourceFile) {
93321 return typeof hostSourceFile === "boolean";
93322 }
93323 function isFilePresenceUnknownOnHost(hostSourceFile) {
93324 return typeof hostSourceFile.version === "boolean";
93325 }
93326 function fileExists(fileName) {
93327 var path = toPath(fileName);
93328 // If file is missing on host from cache, we can definitely say file doesnt exist
93329 // otherwise we need to ensure from the disk
93330 if (isFileMissingOnHost(sourceFilesCache.get(path))) {
93331 return true;
93332 }
93333 return directoryStructureHost.fileExists(fileName);
93334 }
93335 function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
93336 var hostSourceFile = sourceFilesCache.get(path);
93337 // No source file on the host
93338 if (isFileMissingOnHost(hostSourceFile)) {
93339 return undefined;
93340 }
93341 // Create new source file if requested or the versions dont match
93342 if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
93343 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
93344 if (hostSourceFile) {
93345 if (sourceFile) {
93346 // Set the source file and create file watcher now that file was present on the disk
93347 hostSourceFile.sourceFile = sourceFile;
93348 hostSourceFile.version = sourceFile.version;
93349 if (!hostSourceFile.fileWatcher) {
93350 hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
93351 }
93352 }
93353 else {
93354 // There is no source file on host any more, close the watch, missing file paths will track it
93355 if (hostSourceFile.fileWatcher) {
93356 hostSourceFile.fileWatcher.close();
93357 }
93358 sourceFilesCache.set(path, false);
93359 }
93360 }
93361 else {
93362 if (sourceFile) {
93363 var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
93364 sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
93365 }
93366 else {
93367 sourceFilesCache.set(path, false);
93368 }
93369 }
93370 return sourceFile;
93371 }
93372 return hostSourceFile.sourceFile;
93373 }
93374 function nextSourceFileVersion(path) {
93375 var hostSourceFile = sourceFilesCache.get(path);
93376 if (hostSourceFile !== undefined) {
93377 if (isFileMissingOnHost(hostSourceFile)) {
93378 // The next version, lets set it as presence unknown file
93379 sourceFilesCache.set(path, { version: false });
93380 }
93381 else {
93382 hostSourceFile.version = false;
93383 }
93384 }
93385 }
93386 function getSourceVersion(path) {
93387 var hostSourceFile = sourceFilesCache.get(path);
93388 return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
93389 }
93390 function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
93391 var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
93392 // If this is the source file thats in the cache and new program doesnt need it,
93393 // remove the cached entry.
93394 // Note we arent deleting entry if file became missing in new program or
93395 // there was version update and new source file was created.
93396 if (hostSourceFileInfo !== undefined) {
93397 // record the missing file paths so they can be removed later if watchers arent tracking them
93398 if (isFileMissingOnHost(hostSourceFileInfo)) {
93399 (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
93400 }
93401 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
93402 if (hostSourceFileInfo.fileWatcher) {
93403 hostSourceFileInfo.fileWatcher.close();
93404 }
93405 sourceFilesCache.delete(oldSourceFile.resolvedPath);
93406 if (!hasSourceFileByPath) {
93407 resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
93408 }
93409 }
93410 }
93411 }
93412 function reportWatchDiagnostic(message) {
93413 if (host.onWatchStatusChange) {
93414 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
93415 }
93416 }
93417 // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
93418 // operations (such as saving all modified files in an editor) a chance to complete before we kick
93419 // off a new compilation.
93420 function scheduleProgramUpdate() {
93421 if (!host.setTimeout || !host.clearTimeout) {
93422 return;
93423 }
93424 if (timerToUpdateProgram) {
93425 host.clearTimeout(timerToUpdateProgram);
93426 }
93427 writeLog("Scheduling update");
93428 timerToUpdateProgram = host.setTimeout(updateProgram, 250);
93429 }
93430 function scheduleProgramReload() {
93431 ts.Debug.assert(!!configFileName);
93432 reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
93433 scheduleProgramUpdate();
93434 }
93435 function updateProgram() {
93436 timerToUpdateProgram = undefined;
93437 reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
93438 switch (reloadLevel) {
93439 case ts.ConfigFileProgramReloadLevel.Partial:
93440 return reloadFileNamesFromConfigFile();
93441 case ts.ConfigFileProgramReloadLevel.Full:
93442 return reloadConfigFile();
93443 default:
93444 synchronizeProgram();
93445 return;
93446 }
93447 }
93448 function reloadFileNamesFromConfigFile() {
93449 writeLog("Reloading new file names and options");
93450 var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost);
93451 if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
93452 hasChangedConfigFileParsingErrors = true;
93453 }
93454 rootFileNames = result.fileNames;
93455 // Update the program
93456 synchronizeProgram();
93457 }
93458 function reloadConfigFile() {
93459 writeLog("Reloading config file: " + configFileName);
93460 reloadLevel = ts.ConfigFileProgramReloadLevel.None;
93461 if (cachedDirectoryStructureHost) {
93462 cachedDirectoryStructureHost.clearCache();
93463 }
93464 parseConfigFile();
93465 hasChangedCompilerOptions = true;
93466 synchronizeProgram();
93467 // Update the wild card directory watch
93468 watchConfigFileWildCardDirectories();
93469 }
93470 function parseConfigFile() {
93471 setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217
93472 }
93473 function setConfigFileParsingResult(configFileParseResult) {
93474 rootFileNames = configFileParseResult.fileNames;
93475 compilerOptions = configFileParseResult.options;
93476 configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
93477 projectReferences = configFileParseResult.projectReferences;
93478 configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
93479 canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw);
93480 hasChangedConfigFileParsingErrors = true;
93481 }
93482 function onSourceFileChange(fileName, eventKind, path) {
93483 updateCachedSystemWithFile(fileName, path, eventKind);
93484 // Update the source file cache
93485 if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
93486 resolutionCache.invalidateResolutionOfFile(path);
93487 }
93488 resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
93489 nextSourceFileVersion(path);
93490 // Update the program
93491 scheduleProgramUpdate();
93492 }
93493 function updateCachedSystemWithFile(fileName, path, eventKind) {
93494 if (cachedDirectoryStructureHost) {
93495 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
93496 }
93497 }
93498 function watchMissingFilePath(missingFilePath) {
93499 return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file" /* MissingFile */);
93500 }
93501 function onMissingFileChange(fileName, eventKind, missingFilePath) {
93502 updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
93503 if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
93504 missingFilesMap.get(missingFilePath).close();
93505 missingFilesMap.delete(missingFilePath);
93506 // Delete the entry in the source files cache so that new source file is created
93507 nextSourceFileVersion(missingFilePath);
93508 // When a missing file is created, we should update the graph.
93509 scheduleProgramUpdate();
93510 }
93511 }
93512 function watchConfigFileWildCardDirectories() {
93513 if (configFileSpecs) {
93514 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory);
93515 }
93516 else if (watchedWildcardDirectories) {
93517 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
93518 }
93519 }
93520 function watchWildcardDirectory(directory, flags) {
93521 return watchDirectory(host, directory, function (fileOrDirectory) {
93522 ts.Debug.assert(!!configFileName);
93523 var fileOrDirectoryPath = toPath(fileOrDirectory);
93524 // Since the file existance changed, update the sourceFiles cache
93525 if (cachedDirectoryStructureHost) {
93526 cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
93527 }
93528 nextSourceFileVersion(fileOrDirectoryPath);
93529 if (ts.isPathIgnored(fileOrDirectoryPath))
93530 return;
93531 // If the the added or created file or directory is not supported file name, ignore the file
93532 // But when watched directory is added/removed, we need to reload the file list
93533 if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
93534 writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
93535 return;
93536 }
93537 // Reload is pending, do the reload
93538 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
93539 reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
93540 // Schedule Update the program
93541 scheduleProgramUpdate();
93542 }
93543 }, flags, "Wild card directory" /* WildcardDirectory */);
93544 }
93545 }
93546 ts.createWatchProgram = createWatchProgram;
93547})(ts || (ts = {}));
93548// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch
93549/*@internal*/
93550var ts;
93551(function (ts) {
93552 var minimumDate = new Date(-8640000000000000);
93553 var maximumDate = new Date(8640000000000000);
93554 var BuildResultFlags;
93555 (function (BuildResultFlags) {
93556 BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
93557 /**
93558 * No errors of any kind occurred during build
93559 */
93560 BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
93561 /**
93562 * None of the .d.ts files emitted by this build were
93563 * different from the existing files on disk
93564 */
93565 BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
93566 BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
93567 BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
93568 BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
93569 BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
93570 BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
93571 BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
93572 })(BuildResultFlags || (BuildResultFlags = {}));
93573 var UpToDateStatusType;
93574 (function (UpToDateStatusType) {
93575 UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
93576 UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
93577 /**
93578 * The project appears out of date because its upstream inputs are newer than its outputs,
93579 * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
93580 * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
93581 */
93582 UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
93583 /**
93584 * The project appears out of date because its upstream inputs are newer than its outputs,
93585 * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
93586 * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
93587 */
93588 UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
93589 UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
93590 UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
93591 UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
93592 UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
93593 UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
93594 UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
93595 UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
93596 /**
93597 * Projects with no outputs (i.e. "solution" files)
93598 */
93599 UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
93600 })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
93601 function createFileMap(toPath) {
93602 // tslint:disable-next-line:no-null-keyword
93603 var lookup = ts.createMap();
93604 return {
93605 setValue: setValue,
93606 getValue: getValue,
93607 removeKey: removeKey,
93608 forEach: forEach,
93609 hasKey: hasKey,
93610 getSize: getSize,
93611 clear: clear
93612 };
93613 function forEach(action) {
93614 lookup.forEach(action);
93615 }
93616 function hasKey(fileName) {
93617 return lookup.has(toPath(fileName));
93618 }
93619 function removeKey(fileName) {
93620 lookup.delete(toPath(fileName));
93621 }
93622 function setValue(fileName, value) {
93623 lookup.set(toPath(fileName), value);
93624 }
93625 function getValue(fileName) {
93626 return lookup.get(toPath(fileName));
93627 }
93628 function getSize() {
93629 return lookup.size;
93630 }
93631 function clear() {
93632 lookup.clear();
93633 }
93634 }
93635 function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
93636 var existingValue = configFileMap.getValue(resolved);
93637 var newValue;
93638 if (!existingValue) {
93639 newValue = createT();
93640 configFileMap.setValue(resolved, newValue);
93641 }
93642 return existingValue || newValue;
93643 }
93644 function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
93645 return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
93646 }
93647 function newer(date1, date2) {
93648 return date2 > date1 ? date2 : date1;
93649 }
93650 function isDeclarationFile(fileName) {
93651 return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
93652 }
93653 /**
93654 * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
93655 */
93656 function createBuilderStatusReporter(system, pretty) {
93657 return function (diagnostic) {
93658 var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - ";
93659 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
93660 system.write(output);
93661 };
93662 }
93663 ts.createBuilderStatusReporter = createBuilderStatusReporter;
93664 function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
93665 var host = ts.createProgramHost(system, createProgram);
93666 host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
93667 host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
93668 host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
93669 host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
93670 host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
93671 return host;
93672 }
93673 function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
93674 if (system === void 0) { system = ts.sys; }
93675 var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
93676 host.reportErrorSummary = reportErrorSummary;
93677 return host;
93678 }
93679 ts.createSolutionBuilderHost = createSolutionBuilderHost;
93680 function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
93681 if (system === void 0) { system = ts.sys; }
93682 var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
93683 var watchHost = ts.createWatchHost(system, reportWatchStatus);
93684 ts.copyProperties(host, watchHost);
93685 return host;
93686 }
93687 ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
93688 function getCompilerOptionsOfBuildOptions(buildOptions) {
93689 var result = {};
93690 ts.commonOptionsWithBuild.forEach(function (option) {
93691 result[option.name] = buildOptions[option.name];
93692 });
93693 return result;
93694 }
93695 function createSolutionBuilder(host, rootNames, defaultOptions) {
93696 var hostWithWatch = host;
93697 var currentDirectory = host.getCurrentDirectory();
93698 var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
93699 var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host);
93700 // State of the solution
93701 var options = defaultOptions;
93702 var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
93703 var configFileCache = createFileMap(toPath);
93704 /** Map from output file name to its pre-build timestamp */
93705 var unchangedOutputs = createFileMap(toPath);
93706 /** Map from config file name to up-to-date status */
93707 var projectStatus = createFileMap(toPath);
93708 var missingRoots = ts.createMap();
93709 var globalDependencyGraph;
93710 var writeFileName = function (s) { return host.trace && host.trace(s); };
93711 var readFileWithCache = function (f) { return host.readFile(f); };
93712 var projectCompilerOptions = baseCompilerOptions;
93713 var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
93714 ts.setGetSourceFileAsHashVersioned(compilerHost, host);
93715 var buildInfoChecked = createFileMap(toPath);
93716 // Watch state
93717 var builderPrograms = createFileMap(toPath);
93718 var diagnostics = createFileMap(toPath);
93719 var projectPendingBuild = createFileMap(toPath);
93720 var projectErrorsReported = createFileMap(toPath);
93721 var invalidatedProjectQueue = [];
93722 var nextProjectToBuild = 0;
93723 var timerToBuildInvalidatedProject;
93724 var reportFileChangeDetected = false;
93725 var _a = ts.createWatchFactory(host, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
93726 // Watches for the solution
93727 var allWatchedWildcardDirectories = createFileMap(toPath);
93728 var allWatchedInputFiles = createFileMap(toPath);
93729 var allWatchedConfigFiles = createFileMap(toPath);
93730 return {
93731 buildAllProjects: buildAllProjects,
93732 getUpToDateStatusOfFile: getUpToDateStatusOfFile,
93733 cleanAllProjects: cleanAllProjects,
93734 resetBuildContext: resetBuildContext,
93735 getBuildGraph: getBuildGraph,
93736 invalidateProject: invalidateProject,
93737 buildInvalidatedProject: buildInvalidatedProject,
93738 resolveProjectName: resolveProjectName,
93739 startWatching: startWatching
93740 };
93741 function toPath(fileName) {
93742 return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
93743 }
93744 function resetBuildContext(opts) {
93745 if (opts === void 0) { opts = defaultOptions; }
93746 options = opts;
93747 baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
93748 configFileCache.clear();
93749 unchangedOutputs.clear();
93750 projectStatus.clear();
93751 missingRoots.clear();
93752 globalDependencyGraph = undefined;
93753 buildInfoChecked.clear();
93754 diagnostics.clear();
93755 projectPendingBuild.clear();
93756 projectErrorsReported.clear();
93757 invalidatedProjectQueue.length = 0;
93758 nextProjectToBuild = 0;
93759 if (timerToBuildInvalidatedProject) {
93760 clearTimeout(timerToBuildInvalidatedProject);
93761 timerToBuildInvalidatedProject = undefined;
93762 }
93763 reportFileChangeDetected = false;
93764 ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); });
93765 ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
93766 ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
93767 builderPrograms.clear();
93768 }
93769 function isParsedCommandLine(entry) {
93770 return !!entry.options;
93771 }
93772 function parseConfigFile(configFilePath) {
93773 var value = configFileCache.getValue(configFilePath);
93774 if (value) {
93775 return isParsedCommandLine(value) ? value : undefined;
93776 }
93777 var diagnostic;
93778 parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
93779 var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost);
93780 parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
93781 configFileCache.setValue(configFilePath, parsed || diagnostic);
93782 return parsed;
93783 }
93784 function reportStatus(message) {
93785 var args = [];
93786 for (var _i = 1; _i < arguments.length; _i++) {
93787 args[_i - 1] = arguments[_i];
93788 }
93789 host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)));
93790 }
93791 function reportWatchStatus(message) {
93792 var args = [];
93793 for (var _i = 1; _i < arguments.length; _i++) {
93794 args[_i - 1] = arguments[_i];
93795 }
93796 if (hostWithWatch.onWatchStatusChange) {
93797 hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions);
93798 }
93799 }
93800 function startWatching() {
93801 var graph = getGlobalDependencyGraph();
93802 for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
93803 var resolved = _a[_i];
93804 // Watch this file
93805 watchConfigFile(resolved);
93806 var cfg = parseConfigFile(resolved);
93807 if (cfg) {
93808 // Update watchers for wildcard directories
93809 watchWildCardDirectories(resolved, cfg);
93810 // Watch input files
93811 watchInputFiles(resolved, cfg);
93812 }
93813 }
93814 }
93815 function watchConfigFile(resolved) {
93816 if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) {
93817 allWatchedConfigFiles.setValue(resolved, watchFile(hostWithWatch, resolved, function () {
93818 invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full);
93819 }, ts.PollingInterval.High, "Config file" /* ConfigFile */, resolved));
93820 }
93821 }
93822 function watchWildCardDirectories(resolved, parsed) {
93823 if (!options.watch)
93824 return;
93825 ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) {
93826 return watchDirectory(hostWithWatch, dir, function (fileOrDirectory) {
93827 var fileOrDirectoryPath = toPath(fileOrDirectory);
93828 if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
93829 writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory);
93830 return;
93831 }
93832 if (isOutputFile(fileOrDirectory, parsed)) {
93833 writeLog(fileOrDirectory + " is output file");
93834 return;
93835 }
93836 invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial);
93837 }, flags, "Wild card directory" /* WildcardDirectory */, resolved);
93838 });
93839 }
93840 function watchInputFiles(resolved, parsed) {
93841 if (!options.watch)
93842 return;
93843 ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), {
93844 createNewValue: function (path, input) { return watchFilePath(hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, path, "Source file" /* SourceFile */, resolved); },
93845 onDeleteValue: ts.closeFileWatcher,
93846 });
93847 }
93848 function isOutputFile(fileName, configFile) {
93849 if (configFile.options.noEmit)
93850 return false;
93851 // ts or tsx files are not output
93852 if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) &&
93853 (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) {
93854 return false;
93855 }
93856 // If options have --outFile or --out, check if its that
93857 var out = configFile.options.outFile || configFile.options.out;
93858 if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) {
93859 return true;
93860 }
93861 // If declarationDir is specified, return if its a file in that directory
93862 if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) {
93863 return true;
93864 }
93865 // If --outDir, check if file is in that directory
93866 if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) {
93867 return true;
93868 }
93869 return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); });
93870 }
93871 function isSameFile(file1, file2) {
93872 return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
93873 }
93874 function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) {
93875 reportFileChangeDetected = true;
93876 invalidateResolvedProject(resolved, reloadLevel);
93877 scheduleBuildInvalidatedProject();
93878 }
93879 function getUpToDateStatusOfFile(configFileName) {
93880 return getUpToDateStatus(parseConfigFile(configFileName));
93881 }
93882 function getBuildGraph(configFileNames) {
93883 return createDependencyGraph(resolveProjectNames(configFileNames));
93884 }
93885 function getGlobalDependencyGraph() {
93886 return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames));
93887 }
93888 function getUpToDateStatus(project) {
93889 if (project === undefined) {
93890 return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
93891 }
93892 var prior = projectStatus.getValue(project.options.configFilePath);
93893 if (prior !== undefined) {
93894 return prior;
93895 }
93896 var actual = getUpToDateStatusWorker(project);
93897 projectStatus.setValue(project.options.configFilePath, actual);
93898 return actual;
93899 }
93900 function getUpToDateStatusWorker(project) {
93901 var newestInputFileName = undefined;
93902 var newestInputFileTime = minimumDate;
93903 // Get timestamps of input files
93904 for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
93905 var inputFile = _a[_i];
93906 if (!host.fileExists(inputFile)) {
93907 return {
93908 type: UpToDateStatusType.Unbuildable,
93909 reason: inputFile + " does not exist"
93910 };
93911 }
93912 var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
93913 if (inputTime > newestInputFileTime) {
93914 newestInputFileName = inputFile;
93915 newestInputFileTime = inputTime;
93916 }
93917 }
93918 // Container if no files are specified in the project
93919 if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
93920 return {
93921 type: UpToDateStatusType.ContainerOnly
93922 };
93923 }
93924 // Collect the expected outputs of this project
93925 var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
93926 // Now see if all outputs are newer than the newest input
93927 var oldestOutputFileName = "(none)";
93928 var oldestOutputFileTime = maximumDate;
93929 var newestOutputFileName = "(none)";
93930 var newestOutputFileTime = minimumDate;
93931 var missingOutputFileName;
93932 var newestDeclarationFileContentChangedTime = minimumDate;
93933 var isOutOfDateWithInputs = false;
93934 for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
93935 var output = outputs_1[_b];
93936 // Output is missing; can stop checking
93937 // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
93938 if (!host.fileExists(output)) {
93939 missingOutputFileName = output;
93940 break;
93941 }
93942 var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
93943 if (outputTime < oldestOutputFileTime) {
93944 oldestOutputFileTime = outputTime;
93945 oldestOutputFileName = output;
93946 }
93947 // If an output is older than the newest input, we can stop checking
93948 // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
93949 if (outputTime < newestInputFileTime) {
93950 isOutOfDateWithInputs = true;
93951 break;
93952 }
93953 if (outputTime > newestOutputFileTime) {
93954 newestOutputFileTime = outputTime;
93955 newestOutputFileName = output;
93956 }
93957 // Keep track of when the most recent time a .d.ts file was changed.
93958 // In addition to file timestamps, we also keep track of when a .d.ts file
93959 // had its file touched but not had its contents changed - this allows us
93960 // to skip a downstream typecheck
93961 if (isDeclarationFile(output)) {
93962 var unchangedTime = unchangedOutputs.getValue(output);
93963 if (unchangedTime !== undefined) {
93964 newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime);
93965 }
93966 else {
93967 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
93968 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
93969 }
93970 }
93971 }
93972 var pseudoUpToDate = false;
93973 var usesPrepend = false;
93974 var upstreamChangedProject;
93975 if (project.projectReferences) {
93976 projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream });
93977 for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
93978 var ref = _d[_c];
93979 usesPrepend = usesPrepend || !!(ref.prepend);
93980 var resolvedRef = ts.resolveProjectReferencePath(ref);
93981 var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef));
93982 // Its a circular reference ignore the status of this project
93983 if (refStatus.type === UpToDateStatusType.ComputingUpstream) {
93984 continue;
93985 }
93986 // An upstream project is blocked
93987 if (refStatus.type === UpToDateStatusType.Unbuildable) {
93988 return {
93989 type: UpToDateStatusType.UpstreamBlocked,
93990 upstreamProjectName: ref.path
93991 };
93992 }
93993 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
93994 if (refStatus.type !== UpToDateStatusType.UpToDate) {
93995 return {
93996 type: UpToDateStatusType.UpstreamOutOfDate,
93997 upstreamProjectName: ref.path
93998 };
93999 }
94000 // Check oldest output file name only if there is no missing output file name
94001 if (!missingOutputFileName) {
94002 // If the upstream project's newest file is older than our oldest output, we
94003 // can't be out of date because of it
94004 if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
94005 continue;
94006 }
94007 // If the upstream project has only change .d.ts files, and we've built
94008 // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
94009 if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
94010 pseudoUpToDate = true;
94011 upstreamChangedProject = ref.path;
94012 continue;
94013 }
94014 // We have an output older than an upstream output - we are out of date
94015 ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
94016 return {
94017 type: UpToDateStatusType.OutOfDateWithUpstream,
94018 outOfDateOutputFileName: oldestOutputFileName,
94019 newerProjectName: ref.path
94020 };
94021 }
94022 }
94023 }
94024 if (missingOutputFileName !== undefined) {
94025 return {
94026 type: UpToDateStatusType.OutputMissing,
94027 missingOutputFileName: missingOutputFileName
94028 };
94029 }
94030 if (isOutOfDateWithInputs) {
94031 return {
94032 type: UpToDateStatusType.OutOfDateWithSelf,
94033 outOfDateOutputFileName: oldestOutputFileName,
94034 newerInputFileName: newestInputFileName
94035 };
94036 }
94037 else {
94038 // Check tsconfig time
94039 var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
94040 if (configStatus)
94041 return configStatus;
94042 // Check extended config time
94043 var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); });
94044 if (extendedConfigStatus)
94045 return extendedConfigStatus;
94046 }
94047 if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
94048 buildInfoChecked.setValue(project.options.configFilePath, true);
94049 var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
94050 if (buildInfoPath) {
94051 var value = readFileWithCache(buildInfoPath);
94052 var buildInfo = value && ts.getBuildInfo(value);
94053 if (buildInfo && buildInfo.version !== ts.version) {
94054 return {
94055 type: UpToDateStatusType.TsVersionOutputOfDate,
94056 version: buildInfo.version
94057 };
94058 }
94059 }
94060 }
94061 if (usesPrepend && pseudoUpToDate) {
94062 return {
94063 type: UpToDateStatusType.OutOfDateWithPrepend,
94064 outOfDateOutputFileName: oldestOutputFileName,
94065 newerProjectName: upstreamChangedProject
94066 };
94067 }
94068 // Up to date
94069 return {
94070 type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate,
94071 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
94072 newestInputFileTime: newestInputFileTime,
94073 newestOutputFileTime: newestOutputFileTime,
94074 newestInputFileName: newestInputFileName,
94075 newestOutputFileName: newestOutputFileName,
94076 oldestOutputFileName: oldestOutputFileName
94077 };
94078 }
94079 function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) {
94080 // Check tsconfig time
94081 var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
94082 if (oldestOutputFileTime < tsconfigTime) {
94083 return {
94084 type: UpToDateStatusType.OutOfDateWithSelf,
94085 outOfDateOutputFileName: oldestOutputFileName,
94086 newerInputFileName: configFile
94087 };
94088 }
94089 }
94090 function invalidateProject(configFileName, reloadLevel) {
94091 invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel);
94092 }
94093 function invalidateResolvedProject(resolved, reloadLevel) {
94094 if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
94095 configFileCache.removeKey(resolved);
94096 globalDependencyGraph = undefined;
94097 }
94098 projectStatus.removeKey(resolved);
94099 diagnostics.removeKey(resolved);
94100 addProjToQueue(resolved, reloadLevel);
94101 }
94102 /**
94103 * return true if new addition
94104 */
94105 function addProjToQueue(proj, reloadLevel) {
94106 var value = projectPendingBuild.getValue(proj);
94107 if (value === undefined) {
94108 projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None);
94109 invalidatedProjectQueue.push(proj);
94110 }
94111 else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) {
94112 projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None);
94113 }
94114 }
94115 function getNextInvalidatedProject() {
94116 if (nextProjectToBuild < invalidatedProjectQueue.length) {
94117 var project = invalidatedProjectQueue[nextProjectToBuild];
94118 nextProjectToBuild++;
94119 var reloadLevel = projectPendingBuild.getValue(project);
94120 projectPendingBuild.removeKey(project);
94121 if (!projectPendingBuild.getSize()) {
94122 invalidatedProjectQueue.length = 0;
94123 nextProjectToBuild = 0;
94124 }
94125 return { project: project, reloadLevel: reloadLevel };
94126 }
94127 }
94128 function hasPendingInvalidatedProjects() {
94129 return !!projectPendingBuild.getSize();
94130 }
94131 function scheduleBuildInvalidatedProject() {
94132 if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
94133 return;
94134 }
94135 if (timerToBuildInvalidatedProject) {
94136 hostWithWatch.clearTimeout(timerToBuildInvalidatedProject);
94137 }
94138 timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250);
94139 }
94140 function buildInvalidatedProject() {
94141 timerToBuildInvalidatedProject = undefined;
94142 if (reportFileChangeDetected) {
94143 reportFileChangeDetected = false;
94144 projectErrorsReported.clear();
94145 reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
94146 }
94147 var buildProject = getNextInvalidatedProject();
94148 if (buildProject) {
94149 buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel);
94150 if (hasPendingInvalidatedProjects()) {
94151 if (options.watch && !timerToBuildInvalidatedProject) {
94152 scheduleBuildInvalidatedProject();
94153 }
94154 }
94155 else {
94156 reportErrorSummary();
94157 }
94158 }
94159 }
94160 function reportErrorSummary() {
94161 if (options.watch || host.reportErrorSummary) {
94162 // Report errors from the other projects
94163 getGlobalDependencyGraph().buildQueue.forEach(function (project) {
94164 if (!projectErrorsReported.hasKey(project)) {
94165 reportErrors(diagnostics.getValue(project) || ts.emptyArray);
94166 }
94167 });
94168 var totalErrors_1 = 0;
94169 diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += ts.getErrorCountForSummary(singleProjectErrors); });
94170 if (options.watch) {
94171 reportWatchStatus(ts.getWatchErrorSummaryDiagnosticMessage(totalErrors_1), totalErrors_1);
94172 }
94173 else {
94174 host.reportErrorSummary(totalErrors_1);
94175 }
94176 }
94177 }
94178 function buildSingleInvalidatedProject(resolved, reloadLevel) {
94179 var proj = parseConfigFile(resolved);
94180 if (!proj) {
94181 reportParseConfigFileDiagnostic(resolved);
94182 return;
94183 }
94184 if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
94185 watchConfigFile(resolved);
94186 watchWildCardDirectories(resolved, proj);
94187 watchInputFiles(resolved, proj);
94188 }
94189 else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
94190 // Update file names
94191 var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost);
94192 ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw));
94193 proj.fileNames = result.fileNames;
94194 watchInputFiles(resolved, proj);
94195 }
94196 var status = getUpToDateStatus(proj);
94197 verboseReportProjectStatus(resolved, status);
94198 if (status.type === UpToDateStatusType.UpstreamBlocked) {
94199 if (options.verbose)
94200 reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName);
94201 return;
94202 }
94203 if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes) {
94204 // Fake that files have been built by updating output file stamps
94205 updateOutputTimestamps(proj);
94206 return;
94207 }
94208 var buildResult = needsBuild(status, resolved) ?
94209 buildSingleProject(resolved) : // Actual build
94210 updateBundle(resolved); // Fake that files have been built by manipulating prepend and existing output
94211 if (buildResult & BuildResultFlags.AnyErrors)
94212 return;
94213 var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
94214 var referencingProjects = referencingProjectsMap.getValue(resolved);
94215 if (!referencingProjects)
94216 return;
94217 // Always use build order to queue projects
94218 for (var index = buildQueue.indexOf(resolved) + 1; index < buildQueue.length; index++) {
94219 var project = buildQueue[index];
94220 var prepend = referencingProjects.getValue(project);
94221 if (prepend !== undefined) {
94222 // If the project is referenced with prepend, always build downstream projects,
94223 // If declaration output is changed, build the project
94224 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
94225 var status_1 = projectStatus.getValue(project);
94226 if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
94227 if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
94228 projectStatus.setValue(project, {
94229 type: UpToDateStatusType.OutOfDateWithUpstream,
94230 outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
94231 newerProjectName: resolved
94232 });
94233 }
94234 }
94235 else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
94236 if (prepend) {
94237 projectStatus.setValue(project, {
94238 type: UpToDateStatusType.OutOfDateWithPrepend,
94239 outOfDateOutputFileName: status_1.oldestOutputFileName,
94240 newerProjectName: resolved
94241 });
94242 }
94243 else {
94244 status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
94245 }
94246 }
94247 addProjToQueue(project);
94248 }
94249 }
94250 }
94251 function createDependencyGraph(roots) {
94252 var temporaryMarks = createFileMap(toPath);
94253 var permanentMarks = createFileMap(toPath);
94254 var circularityReportStack = [];
94255 var buildOrder = [];
94256 var referencingProjectsMap = createFileMap(toPath);
94257 for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
94258 var root = roots_1[_i];
94259 visit(root);
94260 }
94261 return {
94262 buildQueue: buildOrder,
94263 referencingProjectsMap: referencingProjectsMap
94264 };
94265 function visit(projPath, inCircularContext) {
94266 // Already visited
94267 if (permanentMarks.hasKey(projPath))
94268 return;
94269 // Circular
94270 if (temporaryMarks.hasKey(projPath)) {
94271 if (!inCircularContext) {
94272 // TODO:: Do we report this as error?
94273 reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n"));
94274 }
94275 return;
94276 }
94277 temporaryMarks.setValue(projPath, true);
94278 circularityReportStack.push(projPath);
94279 var parsed = parseConfigFile(projPath);
94280 if (parsed && parsed.projectReferences) {
94281 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
94282 var ref = _a[_i];
94283 var resolvedRefPath = resolveProjectName(ref.path);
94284 visit(resolvedRefPath, inCircularContext || ref.circular);
94285 // Get projects referencing resolvedRefPath and add projPath to it
94286 var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); });
94287 referencingProjects.setValue(projPath, !!ref.prepend);
94288 }
94289 }
94290 circularityReportStack.pop();
94291 permanentMarks.setValue(projPath, true);
94292 buildOrder.push(projPath);
94293 }
94294 }
94295 function buildSingleProject(proj) {
94296 if (options.dry) {
94297 reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj);
94298 return BuildResultFlags.Success;
94299 }
94300 if (options.verbose)
94301 reportStatus(ts.Diagnostics.Building_project_0, proj);
94302 var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
94303 var configFile = parseConfigFile(proj);
94304 if (!configFile) {
94305 // Failed to read the config file
94306 resultFlags |= BuildResultFlags.ConfigFileErrors;
94307 reportParseConfigFileDiagnostic(proj);
94308 projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" });
94309 return resultFlags;
94310 }
94311 if (configFile.fileNames.length === 0) {
94312 reportAndStoreErrors(proj, configFile.errors);
94313 // Nothing to build - must be a solution file, basically
94314 return BuildResultFlags.None;
94315 }
94316 // TODO: handle resolve module name to cache result in project reference redirect
94317 projectCompilerOptions = configFile.options;
94318 var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
94319 // Don't emit anything in the presence of syntactic errors or options diagnostics
94320 var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
94321 if (syntaxDiagnostics.length) {
94322 return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
94323 }
94324 // Same as above but now for semantic diagnostics
94325 var semanticDiagnostics = program.getSemanticDiagnostics();
94326 if (semanticDiagnostics.length) {
94327 return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic");
94328 }
94329 // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
94330 program.backupState();
94331 var newestDeclarationFileContentChangedTime = minimumDate;
94332 var anyDtsChanged = false;
94333 var declDiagnostics;
94334 var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
94335 var outputFiles = [];
94336 ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); });
94337 // Don't emit .d.ts if there are decl file errors
94338 if (declDiagnostics) {
94339 program.restoreState();
94340 return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
94341 }
94342 // Actual Emit
94343 var emitterDiagnostics = ts.createDiagnosticCollection();
94344 var emittedOutputs = createFileMap(toPath);
94345 outputFiles.forEach(function (_a) {
94346 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
94347 var priorChangeTime;
94348 if (!anyDtsChanged && isDeclarationFile(name)) {
94349 // Check for unchanged .d.ts files
94350 if (host.fileExists(name) && readFileWithCache(name) === text) {
94351 priorChangeTime = host.getModifiedTime(name);
94352 }
94353 else {
94354 resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
94355 anyDtsChanged = true;
94356 }
94357 }
94358 emittedOutputs.setValue(name, true);
94359 ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
94360 if (priorChangeTime !== undefined) {
94361 newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
94362 unchangedOutputs.setValue(name, priorChangeTime);
94363 }
94364 });
94365 var emitDiagnostics = emitterDiagnostics.getDiagnostics();
94366 if (emitDiagnostics.length) {
94367 return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
94368 }
94369 // Update time stamps for rest of the outputs
94370 newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(configFile, newestDeclarationFileContentChangedTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
94371 var status = {
94372 type: UpToDateStatusType.UpToDate,
94373 newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime,
94374 oldestOutputFileName: outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(configFile, !host.useCaseSensitiveFileNames())
94375 };
94376 diagnostics.removeKey(proj);
94377 projectStatus.setValue(proj, status);
94378 afterProgramCreate(proj, program);
94379 projectCompilerOptions = baseCompilerOptions;
94380 return resultFlags;
94381 function buildErrors(diagnostics, errorFlags, errorType) {
94382 resultFlags |= errorFlags;
94383 reportAndStoreErrors(proj, diagnostics);
94384 projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
94385 afterProgramCreate(proj, program);
94386 projectCompilerOptions = baseCompilerOptions;
94387 return resultFlags;
94388 }
94389 }
94390 function afterProgramCreate(proj, program) {
94391 if (host.afterProgramEmitAndDiagnostics) {
94392 host.afterProgramEmitAndDiagnostics(program);
94393 }
94394 if (options.watch) {
94395 program.releaseProgram();
94396 builderPrograms.setValue(proj, program);
94397 }
94398 }
94399 function getOldProgram(proj, parsed) {
94400 if (options.force)
94401 return undefined;
94402 var value = builderPrograms.getValue(proj);
94403 if (value)
94404 return value;
94405 return ts.readBuilderProgram(parsed.options, readFileWithCache);
94406 }
94407 function updateBundle(proj) {
94408 if (options.dry) {
94409 reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
94410 return BuildResultFlags.Success;
94411 }
94412 if (options.verbose)
94413 reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
94414 // Update js, and source map
94415 var config = ts.Debug.assertDefined(parseConfigFile(proj));
94416 projectCompilerOptions = config.options;
94417 var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
94418 if (ts.isString(outputFiles)) {
94419 reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
94420 return buildSingleProject(proj);
94421 }
94422 // Actual Emit
94423 ts.Debug.assert(!!outputFiles.length);
94424 var emitterDiagnostics = ts.createDiagnosticCollection();
94425 var emittedOutputs = createFileMap(toPath);
94426 outputFiles.forEach(function (_a) {
94427 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
94428 emittedOutputs.setValue(name, true);
94429 ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
94430 });
94431 var emitDiagnostics = emitterDiagnostics.getDiagnostics();
94432 if (emitDiagnostics.length) {
94433 reportAndStoreErrors(proj, emitDiagnostics);
94434 projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
94435 projectCompilerOptions = baseCompilerOptions;
94436 return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
94437 }
94438 // Update timestamps for dts
94439 var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
94440 var status = {
94441 type: UpToDateStatusType.UpToDate,
94442 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
94443 oldestOutputFileName: outputFiles[0].name
94444 };
94445 diagnostics.removeKey(proj);
94446 projectStatus.setValue(proj, status);
94447 projectCompilerOptions = baseCompilerOptions;
94448 return BuildResultFlags.DeclarationOutputUnchanged;
94449 }
94450 function updateOutputTimestamps(proj) {
94451 if (options.dry) {
94452 return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
94453 }
94454 var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
94455 var status = {
94456 type: UpToDateStatusType.UpToDate,
94457 newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
94458 oldestOutputFileName: ts.getFirstProjectOutput(proj, !host.useCaseSensitiveFileNames())
94459 };
94460 projectStatus.setValue(proj.options.configFilePath, status);
94461 }
94462 function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
94463 var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
94464 if (!skipOutputs || outputs.length !== skipOutputs.getSize()) {
94465 if (options.verbose) {
94466 reportStatus(verboseMessage, proj.options.configFilePath);
94467 }
94468 var now = host.now ? host.now() : new Date();
94469 for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
94470 var file = outputs_2[_i];
94471 if (skipOutputs && skipOutputs.hasKey(file)) {
94472 continue;
94473 }
94474 if (isDeclarationFile(file)) {
94475 priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
94476 }
94477 host.setModifiedTime(file, now);
94478 if (proj.options.listEmittedFiles) {
94479 writeFileName("TSFILE: " + file);
94480 }
94481 }
94482 }
94483 return priorNewestUpdateTime;
94484 }
94485 function getFilesToClean() {
94486 // Get the same graph for cleaning we'd use for building
94487 var graph = getGlobalDependencyGraph();
94488 var filesToDelete = [];
94489 for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
94490 var proj = _a[_i];
94491 var parsed = parseConfigFile(proj);
94492 if (parsed === undefined) {
94493 // File has gone missing; fine to ignore here
94494 reportParseConfigFileDiagnostic(proj);
94495 continue;
94496 }
94497 var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
94498 for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
94499 var output = outputs_3[_b];
94500 if (host.fileExists(output)) {
94501 filesToDelete.push(output);
94502 }
94503 }
94504 }
94505 return filesToDelete;
94506 }
94507 function cleanAllProjects() {
94508 var filesToDelete = getFilesToClean();
94509 if (options.dry) {
94510 reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
94511 return ts.ExitStatus.Success;
94512 }
94513 for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) {
94514 var output = filesToDelete_1[_i];
94515 host.deleteFile(output);
94516 }
94517 return ts.ExitStatus.Success;
94518 }
94519 function resolveProjectName(name) {
94520 return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name));
94521 }
94522 function resolveProjectNames(configFileNames) {
94523 return configFileNames.map(resolveProjectName);
94524 }
94525 function buildAllProjects() {
94526 if (options.watch) {
94527 reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode);
94528 }
94529 // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api
94530 // Override readFile for json files and output .d.ts to cache the text
94531 var savedReadFileWithCache = readFileWithCache;
94532 var savedGetSourceFile = compilerHost.getSourceFile;
94533 var _a = ts.changeCompilerHostLikeToUseCache(host, toPath, function () {
94534 var args = [];
94535 for (var _i = 0; _i < arguments.length; _i++) {
94536 args[_i] = arguments[_i];
94537 }
94538 return savedGetSourceFile.call.apply(savedGetSourceFile, [compilerHost].concat(args));
94539 }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, newReadFileWithCache = _a.readFileWithCache;
94540 readFileWithCache = newReadFileWithCache;
94541 compilerHost.getSourceFile = getSourceFileWithCache;
94542 var graph = getGlobalDependencyGraph();
94543 reportBuildQueue(graph);
94544 var anyFailed = false;
94545 for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) {
94546 var next = _b[_i];
94547 var proj = parseConfigFile(next);
94548 if (proj === undefined) {
94549 reportParseConfigFileDiagnostic(next);
94550 anyFailed = true;
94551 break;
94552 }
94553 // report errors early when using continue or break statements
94554 var errors = proj.errors;
94555 var status = getUpToDateStatus(proj);
94556 verboseReportProjectStatus(next, status);
94557 var projName = proj.options.configFilePath;
94558 if (status.type === UpToDateStatusType.UpToDate && !options.force) {
94559 reportAndStoreErrors(next, errors);
94560 // Up to date, skip
94561 if (defaultOptions.dry) {
94562 // In a dry build, inform the user of this fact
94563 reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName);
94564 }
94565 continue;
94566 }
94567 if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) {
94568 reportAndStoreErrors(next, errors);
94569 // Fake build
94570 updateOutputTimestamps(proj);
94571 continue;
94572 }
94573 if (status.type === UpToDateStatusType.UpstreamBlocked) {
94574 reportAndStoreErrors(next, errors);
94575 if (options.verbose)
94576 reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName);
94577 continue;
94578 }
94579 if (status.type === UpToDateStatusType.ContainerOnly) {
94580 reportAndStoreErrors(next, errors);
94581 // Do nothing
94582 continue;
94583 }
94584 var buildResult = needsBuild(status, next) ?
94585 buildSingleProject(next) : // Actual build
94586 updateBundle(next); // Fake that files have been built by manipulating prepend and existing output
94587 anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
94588 }
94589 reportErrorSummary();
94590 host.readFile = originalReadFile;
94591 host.fileExists = originalFileExists;
94592 host.directoryExists = originalDirectoryExists;
94593 host.createDirectory = originalCreateDirectory;
94594 host.writeFile = originalWriteFile;
94595 compilerHost.getSourceFile = savedGetSourceFile;
94596 readFileWithCache = savedReadFileWithCache;
94597 return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
94598 }
94599 function needsBuild(status, configFile) {
94600 if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force)
94601 return true;
94602 var config = parseConfigFile(configFile);
94603 return !config ||
94604 config.fileNames.length === 0 ||
94605 !!config.errors.length ||
94606 !ts.isIncrementalCompilation(config.options);
94607 }
94608 function reportParseConfigFileDiagnostic(proj) {
94609 reportAndStoreErrors(proj, [configFileCache.getValue(proj)]);
94610 }
94611 function reportAndStoreErrors(proj, errors) {
94612 reportErrors(errors);
94613 projectErrorsReported.setValue(proj, true);
94614 diagnostics.setValue(proj, errors);
94615 }
94616 function reportErrors(errors) {
94617 errors.forEach(function (err) { return host.reportDiagnostic(err); });
94618 }
94619 /**
94620 * Report the build ordering inferred from the current project graph if we're in verbose mode
94621 */
94622 function reportBuildQueue(graph) {
94623 if (options.verbose) {
94624 reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join(""));
94625 }
94626 }
94627 function relName(path) {
94628 return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); });
94629 }
94630 /**
94631 * Report the up-to-date status of a project if we're in verbose mode
94632 */
94633 function verboseReportProjectStatus(configFileName, status) {
94634 if (!options.verbose)
94635 return;
94636 return formatUpToDateStatus(configFileName, status, relName, reportStatus);
94637 }
94638 }
94639 ts.createSolutionBuilder = createSolutionBuilder;
94640 function resolveConfigFileProjectName(project) {
94641 if (ts.fileExtensionIs(project, ".json" /* Json */)) {
94642 return project;
94643 }
94644 return ts.combinePaths(project, "tsconfig.json");
94645 }
94646 ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
94647 function formatUpToDateStatus(configFileName, status, relName, formatMessage) {
94648 switch (status.type) {
94649 case UpToDateStatusType.OutOfDateWithSelf:
94650 return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName));
94651 case UpToDateStatusType.OutOfDateWithUpstream:
94652 return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName));
94653 case UpToDateStatusType.OutputMissing:
94654 return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName));
94655 case UpToDateStatusType.UpToDate:
94656 if (status.newestInputFileTime !== undefined) {
94657 return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || ""));
94658 }
94659 // Don't report anything for "up to date because it was already built" -- too verbose
94660 break;
94661 case UpToDateStatusType.OutOfDateWithPrepend:
94662 return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
94663 case UpToDateStatusType.UpToDateWithUpstreamTypes:
94664 return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName));
94665 case UpToDateStatusType.UpstreamOutOfDate:
94666 return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName));
94667 case UpToDateStatusType.UpstreamBlocked:
94668 return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName));
94669 case UpToDateStatusType.Unbuildable:
94670 return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason);
94671 case UpToDateStatusType.TsVersionOutputOfDate:
94672 return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
94673 case UpToDateStatusType.ContainerOnly:
94674 // Don't report status on "solution" projects
94675 case UpToDateStatusType.ComputingUpstream:
94676 // Should never leak from getUptoDateStatusWorker
94677 break;
94678 default:
94679 ts.assertType(status);
94680 }
94681 }
94682 ts.formatUpToDateStatus = formatUpToDateStatus;
94683})(ts || (ts = {}));
94684/* @internal */
94685var ts;
94686(function (ts) {
94687 var ValueKind;
94688 (function (ValueKind) {
94689 ValueKind[ValueKind["Const"] = 0] = "Const";
94690 ValueKind[ValueKind["Array"] = 1] = "Array";
94691 ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass";
94692 ValueKind[ValueKind["Object"] = 3] = "Object";
94693 })(ValueKind = ts.ValueKind || (ts.ValueKind = {}));
94694 function inspectModule(fileNameToRequire) {
94695 return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire));
94696 }
94697 ts.inspectModule = inspectModule;
94698 function inspectValue(name, value) {
94699 return getValueInfo(name, value, getRecurser());
94700 }
94701 ts.inspectValue = inspectValue;
94702 function getRecurser() {
94703 var seen = [];
94704 var nameStack = [];
94705 return function (obj, name, cbOk, cbFail) {
94706 if (seen.indexOf(obj) !== -1 || nameStack.length > 4) {
94707 return cbFail(seen.indexOf(obj) !== -1, nameStack);
94708 }
94709 seen.push(obj);
94710 nameStack.push(name);
94711 var res = cbOk();
94712 nameStack.pop();
94713 seen.pop();
94714 return res;
94715 };
94716 }
94717 function getValueInfo(name, value, recurser) {
94718 return recurser(value, name, function () {
94719 if (typeof value === "function")
94720 return getFunctionOrClassInfo(value, name, recurser);
94721 if (typeof value === "object") {
94722 var builtin = getBuiltinType(name, value, recurser);
94723 if (builtin !== undefined)
94724 return builtin;
94725 var entries = getEntriesOfObject(value);
94726 var hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype;
94727 var members = ts.flatMap(entries, function (_a) {
94728 var key = _a.key, value = _a.value;
94729 return getValueInfo(key, value, recurser);
94730 });
94731 return { kind: 3 /* Object */, name: name, hasNontrivialPrototype: hasNontrivialPrototype, members: members };
94732 }
94733 return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value };
94734 }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); });
94735 }
94736 function getFunctionOrClassInfo(fn, name, recurser) {
94737 var prototypeMembers = getPrototypeMembers(fn, recurser);
94738 var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) {
94739 var key = _a.key, value = _a.value;
94740 return getValueInfo(key, value, recurser);
94741 });
94742 var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString);
94743 var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString;
94744 return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers };
94745 }
94746 var builtins = ts.memoize(function () {
94747 var map = ts.createMap();
94748 for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) {
94749 var _b = _a[_i], key = _b.key, value = _b.value;
94750 if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) {
94751 map.set(key, value);
94752 }
94753 }
94754 return map;
94755 });
94756 function getBuiltinType(name, value, recurser) {
94757 return ts.isArray(value)
94758 ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) }
94759 : ts.forEachEntry(builtins(), function (builtin, builtinName) {
94760 return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined;
94761 });
94762 }
94763 function getPrototypeMembers(fn, recurser) {
94764 var prototype = fn.prototype;
94765 // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary)
94766 return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) {
94767 var key = _a.key, value = _a.value;
94768 return key === "constructor" ? undefined : getValueInfo(key, value, recurser);
94769 });
94770 }
94771 var ignoredProperties = ["arguments", "caller", "constructor", "eval", "super_"];
94772 var reservedFunctionProperties = Object.getOwnPropertyNames(ts.noop);
94773 function getEntriesOfObject(obj) {
94774 var seen = ts.createMap();
94775 var entries = [];
94776 var chain = obj;
94777 while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) {
94778 for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) {
94779 var key = _a[_i];
94780 if (!isJsPrivate(key) &&
94781 ignoredProperties.indexOf(key) === -1 &&
94782 (typeof obj !== "function" || reservedFunctionProperties.indexOf(key) === -1) &&
94783 // Don't add property from a higher prototype if it already exists in a lower one
94784 ts.addToSeen(seen, key)) {
94785 var value = safeGetPropertyOfObject(chain, key);
94786 // Don't repeat "toString" that matches signature from Object.prototype
94787 if (!(key === "toString" && typeof value === "function" && value.length === 0)) {
94788 entries.push({ key: key, value: value });
94789 }
94790 }
94791 }
94792 chain = Object.getPrototypeOf(chain);
94793 }
94794 return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); });
94795 }
94796 function getFunctionLength(fn) {
94797 return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0;
94798 }
94799 function safeGetPropertyOfObject(obj, key) {
94800 var desc = Object.getOwnPropertyDescriptor(obj, key);
94801 return desc && desc.value;
94802 }
94803 function isNullOrUndefined(value) {
94804 return value == null; // tslint:disable-line
94805 }
94806 function anyValue(name, comment) {
94807 return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment };
94808 }
94809 function isJsPrivate(name) {
94810 return ts.startsWith(name, "_");
94811 }
94812 ts.isJsPrivate = isJsPrivate;
94813 function tryRequire(fileNameToRequire) {
94814 try {
94815 return require(fileNameToRequire);
94816 }
94817 catch (_a) {
94818 return undefined;
94819 }
94820 }
94821})(ts || (ts = {}));
94822/* @internal */
94823var ts;
94824(function (ts) {
94825 var server;
94826 (function (server) {
94827 // tslint:disable variable-name
94828 server.ActionSet = "action::set";
94829 server.ActionInvalidate = "action::invalidate";
94830 server.ActionPackageInstalled = "action::packageInstalled";
94831 server.ActionValueInspected = "action::valueInspected";
94832 server.EventTypesRegistry = "event::typesRegistry";
94833 server.EventBeginInstallTypes = "event::beginInstallTypes";
94834 server.EventEndInstallTypes = "event::endInstallTypes";
94835 server.EventInitializationFailed = "event::initializationFailed";
94836 var Arguments;
94837 (function (Arguments) {
94838 Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
94839 Arguments.LogFile = "--logFile";
94840 Arguments.EnableTelemetry = "--enableTelemetry";
94841 Arguments.TypingSafeListLocation = "--typingSafeListLocation";
94842 Arguments.TypesMapLocation = "--typesMapLocation";
94843 /**
94844 * This argument specifies the location of the NPM executable.
94845 * typingsInstaller will run the command with `${npmLocation} install ...`.
94846 */
94847 Arguments.NpmLocation = "--npmLocation";
94848 /**
94849 * Flag indicating that the typings installer should try to validate the default npm location.
94850 * If the default npm is not found when this flag is enabled, fallback to `npm install`
94851 */
94852 Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
94853 })(Arguments = server.Arguments || (server.Arguments = {}));
94854 function hasArgument(argumentName) {
94855 return ts.sys.args.indexOf(argumentName) >= 0;
94856 }
94857 server.hasArgument = hasArgument;
94858 function findArgument(argumentName) {
94859 var index = ts.sys.args.indexOf(argumentName);
94860 return index >= 0 && index < ts.sys.args.length - 1
94861 ? ts.sys.args[index + 1]
94862 : undefined;
94863 }
94864 server.findArgument = findArgument;
94865 function nowString() {
94866 // E.g. "12:34:56.789"
94867 var d = new Date();
94868 return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
94869 }
94870 server.nowString = nowString;
94871 })(server = ts.server || (ts.server = {}));
94872})(ts || (ts = {}));
94873/* @internal */
94874var ts;
94875(function (ts) {
94876 var JsTyping;
94877 (function (JsTyping) {
94878 function isTypingUpToDate(cachedTyping, availableTypingVersions) {
94879 var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
94880 return availableVersion.compareTo(cachedTyping.version) <= 0;
94881 }
94882 JsTyping.isTypingUpToDate = isTypingUpToDate;
94883 JsTyping.nodeCoreModuleList = [
94884 "assert",
94885 "async_hooks",
94886 "buffer",
94887 "child_process",
94888 "cluster",
94889 "console",
94890 "constants",
94891 "crypto",
94892 "dgram",
94893 "dns",
94894 "domain",
94895 "events",
94896 "fs",
94897 "http",
94898 "https",
94899 "http2",
94900 "inspector",
94901 "net",
94902 "os",
94903 "path",
94904 "perf_hooks",
94905 "process",
94906 "punycode",
94907 "querystring",
94908 "readline",
94909 "repl",
94910 "stream",
94911 "string_decoder",
94912 "timers",
94913 "tls",
94914 "tty",
94915 "url",
94916 "util",
94917 "v8",
94918 "vm",
94919 "zlib"
94920 ];
94921 JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
94922 function loadSafeList(host, safeListPath) {
94923 var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
94924 return ts.createMapFromTemplate(result.config);
94925 }
94926 JsTyping.loadSafeList = loadSafeList;
94927 function loadTypesMap(host, typesMapPath) {
94928 var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
94929 if (result.config) {
94930 return ts.createMapFromTemplate(result.config.simpleMap);
94931 }
94932 return undefined;
94933 }
94934 JsTyping.loadTypesMap = loadTypesMap;
94935 /**
94936 * @param host is the object providing I/O related operations.
94937 * @param fileNames are the file names that belong to the same project
94938 * @param projectRootPath is the path to the project root directory
94939 * @param safeListPath is the path used to retrieve the safe list
94940 * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
94941 * @param typeAcquisition is used to customize the typing acquisition process
94942 * @param compilerOptions are used as a source for typing inference
94943 */
94944 function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
94945 if (!typeAcquisition || !typeAcquisition.enable) {
94946 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
94947 }
94948 // A typing name to typing file path mapping
94949 var inferredTypings = ts.createMap();
94950 // Only infer typings for .js and .jsx files
94951 fileNames = ts.mapDefined(fileNames, function (fileName) {
94952 var path = ts.normalizePath(fileName);
94953 if (ts.hasJSFileExtension(path)) {
94954 return path;
94955 }
94956 });
94957 var filesToWatch = [];
94958 if (typeAcquisition.include)
94959 addInferredTypings(typeAcquisition.include, "Explicitly included types");
94960 var exclude = typeAcquisition.exclude || [];
94961 // Directories to search for package.json, bower.json and other typing information
94962 var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath);
94963 possibleSearchDirs.set(projectRootPath, true);
94964 possibleSearchDirs.forEach(function (_true, searchDir) {
94965 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
94966 getTypingNamesFromJson(packageJsonPath, filesToWatch);
94967 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
94968 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
94969 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
94970 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
94971 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
94972 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
94973 });
94974 getTypingNamesFromSourceFileNames(fileNames);
94975 // add typings for unresolved imports
94976 if (unresolvedImports) {
94977 var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
94978 addInferredTypings(module_1, "Inferred typings from unresolved imports");
94979 }
94980 // Add the cached typing locations for inferred typings that are already installed
94981 packageNameToTypingLocation.forEach(function (typing, name) {
94982 var registryEntry = typesRegistry.get(name);
94983 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
94984 inferredTypings.set(name, typing.typingLocation);
94985 }
94986 });
94987 // Remove typings that the user has added to the exclude list
94988 for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
94989 var excludeTypingName = exclude_1[_i];
94990 var didDelete = inferredTypings.delete(excludeTypingName);
94991 if (didDelete && log)
94992 log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
94993 }
94994 var newTypingNames = [];
94995 var cachedTypingPaths = [];
94996 inferredTypings.forEach(function (inferred, typing) {
94997 if (inferred !== undefined) {
94998 cachedTypingPaths.push(inferred);
94999 }
95000 else {
95001 newTypingNames.push(typing);
95002 }
95003 });
95004 var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
95005 if (log)
95006 log("Result: " + JSON.stringify(result));
95007 return result;
95008 function addInferredTyping(typingName) {
95009 if (!inferredTypings.has(typingName)) {
95010 inferredTypings.set(typingName, undefined); // TODO: GH#18217
95011 }
95012 }
95013 function addInferredTypings(typingNames, message) {
95014 if (log)
95015 log(message + ": " + JSON.stringify(typingNames));
95016 ts.forEach(typingNames, addInferredTyping);
95017 }
95018 /**
95019 * Get the typing info from common package manager json files like package.json or bower.json
95020 */
95021 function getTypingNamesFromJson(jsonPath, filesToWatch) {
95022 if (!host.fileExists(jsonPath)) {
95023 return;
95024 }
95025 filesToWatch.push(jsonPath);
95026 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
95027 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
95028 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
95029 }
95030 /**
95031 * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
95032 * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
95033 * to the 'angular-route' typing name.
95034 * @param fileNames are the names for source files in the project
95035 */
95036 function getTypingNamesFromSourceFileNames(fileNames) {
95037 var fromFileNames = ts.mapDefined(fileNames, function (j) {
95038 if (!ts.hasJSFileExtension(j))
95039 return undefined;
95040 var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
95041 var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
95042 return safeList.get(cleanedTypingName);
95043 });
95044 if (fromFileNames.length) {
95045 addInferredTypings(fromFileNames, "Inferred typings from file names");
95046 }
95047 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
95048 if (hasJsxFile) {
95049 if (log)
95050 log("Inferred 'react' typings due to presence of '.jsx' extension");
95051 addInferredTyping("react");
95052 }
95053 }
95054 /**
95055 * Infer typing names from packages folder (ex: node_module, bower_components)
95056 * @param packagesFolderPath is the path to the packages folder
95057 */
95058 function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
95059 filesToWatch.push(packagesFolderPath);
95060 // Todo: add support for ModuleResolutionHost too
95061 if (!host.directoryExists(packagesFolderPath)) {
95062 return;
95063 }
95064 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
95065 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
95066 if (log)
95067 log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
95068 var packageNames = [];
95069 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
95070 var fileName = fileNames_1[_i];
95071 var normalizedFileName = ts.normalizePath(fileName);
95072 var baseFileName = ts.getBaseFileName(normalizedFileName);
95073 if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
95074 continue;
95075 }
95076 var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
95077 var packageJson = result_1.config;
95078 // npm 3's package.json contains a "_requiredBy" field
95079 // we should include all the top level module names for npm 2, and only module names whose
95080 // "_requiredBy" field starts with "#" or equals "/" for npm 3.
95081 if (baseFileName === "package.json" && packageJson._requiredBy &&
95082 ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
95083 continue;
95084 }
95085 // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
95086 // to download d.ts files from DefinitelyTyped
95087 if (!packageJson.name) {
95088 continue;
95089 }
95090 var ownTypes = packageJson.types || packageJson.typings;
95091 if (ownTypes) {
95092 var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
95093 if (log)
95094 log(" Package '" + packageJson.name + "' provides its own types.");
95095 inferredTypings.set(packageJson.name, absolutePath);
95096 }
95097 else {
95098 packageNames.push(packageJson.name);
95099 }
95100 }
95101 addInferredTypings(packageNames, " Found package names");
95102 }
95103 }
95104 JsTyping.discoverTypings = discoverTypings;
95105 var PackageNameValidationResult;
95106 (function (PackageNameValidationResult) {
95107 PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok";
95108 PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported";
95109 PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName";
95110 PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong";
95111 PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot";
95112 PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore";
95113 PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters";
95114 })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {}));
95115 var maxPackageNameLength = 214;
95116 /**
95117 * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
95118 */
95119 function validatePackageName(packageName) {
95120 if (!packageName) {
95121 return 2 /* EmptyName */;
95122 }
95123 if (packageName.length > maxPackageNameLength) {
95124 return 3 /* NameTooLong */;
95125 }
95126 if (packageName.charCodeAt(0) === 46 /* dot */) {
95127 return 4 /* NameStartsWithDot */;
95128 }
95129 if (packageName.charCodeAt(0) === 95 /* _ */) {
95130 return 5 /* NameStartsWithUnderscore */;
95131 }
95132 // check if name is scope package like: starts with @ and has one '/' in the middle
95133 // scoped packages are not currently supported
95134 // TODO: when support will be added we'll need to split and check both scope and package name
95135 if (/^@[^/]+\/[^/]+$/.test(packageName)) {
95136 return 1 /* ScopedPackagesNotSupported */;
95137 }
95138 if (encodeURIComponent(packageName) !== packageName) {
95139 return 6 /* NameContainsNonURISafeCharacters */;
95140 }
95141 return 0 /* Ok */;
95142 }
95143 JsTyping.validatePackageName = validatePackageName;
95144 function renderPackageNameValidationFailure(result, typing) {
95145 switch (result) {
95146 case 2 /* EmptyName */:
95147 return "Package name '" + typing + "' cannot be empty";
95148 case 3 /* NameTooLong */:
95149 return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters";
95150 case 4 /* NameStartsWithDot */:
95151 return "Package name '" + typing + "' cannot start with '.'";
95152 case 5 /* NameStartsWithUnderscore */:
95153 return "Package name '" + typing + "' cannot start with '_'";
95154 case 1 /* ScopedPackagesNotSupported */:
95155 return "Package '" + typing + "' is scoped and currently is not supported";
95156 case 6 /* NameContainsNonURISafeCharacters */:
95157 return "Package name '" + typing + "' contains non URI safe characters";
95158 case 0 /* Ok */:
95159 return ts.Debug.fail(); // Shouldn't have called this.
95160 default:
95161 throw ts.Debug.assertNever(result);
95162 }
95163 }
95164 JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
95165 })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
95166})(ts || (ts = {}));
95167var ts;
95168(function (ts) {
95169 var server;
95170 (function (server) {
95171 var typingsInstaller;
95172 (function (typingsInstaller) {
95173 var nullLog = {
95174 isEnabled: function () { return false; },
95175 writeLine: ts.noop
95176 };
95177 function typingToFileName(cachePath, packageName, installTypingHost, log) {
95178 try {
95179 var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
95180 return result.resolvedModule && result.resolvedModule.resolvedFileName;
95181 }
95182 catch (e) {
95183 if (log.isEnabled()) {
95184 log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message);
95185 }
95186 return undefined;
95187 }
95188 }
95189 /*@internal*/
95190 function installNpmPackages(npmPath, tsVersion, packageNames, install) {
95191 var hasError = false;
95192 for (var remaining = packageNames.length; remaining > 0;) {
95193 var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
95194 remaining = result.remaining;
95195 hasError = install(result.command) || hasError;
95196 }
95197 return hasError;
95198 }
95199 typingsInstaller.installNpmPackages = installNpmPackages;
95200 /*@internal*/
95201 function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
95202 var sliceStart = packageNames.length - remaining;
95203 var command, toSlice = remaining;
95204 while (true) {
95205 command = npmPath + " install --ignore-scripts " + (toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ") + " --save-dev --user-agent=\"typesInstaller/" + tsVersion + "\"";
95206 if (command.length < 8000) {
95207 break;
95208 }
95209 toSlice = toSlice - Math.floor(toSlice / 2);
95210 }
95211 return { command: command, remaining: remaining - toSlice };
95212 }
95213 typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation;
95214 function endsWith(str, suffix, caseSensitive) {
95215 var expectedPos = str.length - suffix.length;
95216 return expectedPos >= 0 &&
95217 (str.indexOf(suffix, expectedPos) === expectedPos ||
95218 (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */));
95219 }
95220 function isPackageOrBowerJson(fileName, caseSensitive) {
95221 return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive);
95222 }
95223 function sameFiles(a, b, caseSensitive) {
95224 return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */);
95225 }
95226 var ProjectWatcherType;
95227 (function (ProjectWatcherType) {
95228 ProjectWatcherType["FileWatcher"] = "FileWatcher";
95229 ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher";
95230 })(ProjectWatcherType || (ProjectWatcherType = {}));
95231 var TypingsInstaller = /** @class */ (function () {
95232 function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) {
95233 if (log === void 0) { log = nullLog; }
95234 this.installTypingHost = installTypingHost;
95235 this.globalCachePath = globalCachePath;
95236 this.safeListPath = safeListPath;
95237 this.typesMapLocation = typesMapLocation;
95238 this.throttleLimit = throttleLimit;
95239 this.log = log;
95240 this.packageNameToTypingLocation = ts.createMap();
95241 this.missingTypingsSet = ts.createMap();
95242 this.knownCachesSet = ts.createMap();
95243 this.projectWatchers = ts.createMap();
95244 this.pendingRunRequests = [];
95245 this.installRunCount = 1;
95246 this.inFlightRequestCount = 0;
95247 this.latestDistTag = "latest";
95248 this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames);
95249 this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json");
95250 if (this.log.isEnabled()) {
95251 this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation);
95252 }
95253 this.processCacheLocation(this.globalCachePath);
95254 }
95255 TypingsInstaller.prototype.closeProject = function (req) {
95256 this.closeWatchers(req.projectName);
95257 };
95258 TypingsInstaller.prototype.closeWatchers = function (projectName) {
95259 if (this.log.isEnabled()) {
95260 this.log.writeLine("Closing file watchers for project '" + projectName + "'");
95261 }
95262 var watchers = this.projectWatchers.get(projectName);
95263 if (!watchers) {
95264 if (this.log.isEnabled()) {
95265 this.log.writeLine("No watchers are registered for project '" + projectName + "'");
95266 }
95267 return;
95268 }
95269 ts.clearMap(watchers, ts.closeFileWatcher);
95270 this.projectWatchers.delete(projectName);
95271 if (this.log.isEnabled()) {
95272 this.log.writeLine("Closing file watchers for project '" + projectName + "' - done.");
95273 }
95274 };
95275 TypingsInstaller.prototype.install = function (req) {
95276 var _this = this;
95277 if (this.log.isEnabled()) {
95278 this.log.writeLine("Got install request " + JSON.stringify(req));
95279 }
95280 // load existing typing information from the cache
95281 if (req.cachePath) {
95282 if (this.log.isEnabled()) {
95283 this.log.writeLine("Request specifies cache path '" + req.cachePath + "', loading cached information...");
95284 }
95285 this.processCacheLocation(req.cachePath);
95286 }
95287 if (this.safeList === undefined) {
95288 this.initializeSafeList();
95289 }
95290 var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, this.log.isEnabled() ? (function (s) { return _this.log.writeLine(s); }) : undefined, req.fileNames, req.projectRootPath, this.safeList, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports, this.typesRegistry);
95291 if (this.log.isEnabled()) {
95292 this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult));
95293 }
95294 // start watching files
95295 this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath);
95296 // install typings
95297 if (discoverTypingsResult.newTypingNames.length) {
95298 this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
95299 }
95300 else {
95301 this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
95302 if (this.log.isEnabled()) {
95303 this.log.writeLine("No new typings were requested as a result of typings discovery");
95304 }
95305 }
95306 };
95307 TypingsInstaller.prototype.initializeSafeList = function () {
95308 // Prefer the safe list from the types map if it exists
95309 if (this.typesMapLocation) {
95310 var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
95311 if (safeListFromMap) {
95312 this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'");
95313 this.safeList = safeListFromMap;
95314 return;
95315 }
95316 this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'");
95317 }
95318 this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
95319 };
95320 TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) {
95321 if (this.log.isEnabled()) {
95322 this.log.writeLine("Processing cache location '" + cacheLocation + "'");
95323 }
95324 if (this.knownCachesSet.has(cacheLocation)) {
95325 if (this.log.isEnabled()) {
95326 this.log.writeLine("Cache location was already processed...");
95327 }
95328 return;
95329 }
95330 var packageJson = ts.combinePaths(cacheLocation, "package.json");
95331 var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json");
95332 if (this.log.isEnabled()) {
95333 this.log.writeLine("Trying to find '" + packageJson + "'...");
95334 }
95335 if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
95336 var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217
95337 var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217
95338 if (this.log.isEnabled()) {
95339 this.log.writeLine("Loaded content of '" + packageJson + "': " + JSON.stringify(npmConfig));
95340 this.log.writeLine("Loaded content of '" + packageLockJson + "'");
95341 }
95342 if (npmConfig.devDependencies && npmLock.dependencies) {
95343 for (var key in npmConfig.devDependencies) {
95344 if (!ts.hasProperty(npmLock.dependencies, key)) {
95345 // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use
95346 continue;
95347 }
95348 // key is @types/<package name>
95349 var packageName = ts.getBaseFileName(key);
95350 if (!packageName) {
95351 continue;
95352 }
95353 var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
95354 if (!typingFile) {
95355 this.missingTypingsSet.set(packageName, true);
95356 continue;
95357 }
95358 var existingTypingFile = this.packageNameToTypingLocation.get(packageName);
95359 if (existingTypingFile) {
95360 if (existingTypingFile.typingLocation === typingFile) {
95361 continue;
95362 }
95363 if (this.log.isEnabled()) {
95364 this.log.writeLine("New typing for package " + packageName + " from '" + typingFile + "' conflicts with existing typing file '" + existingTypingFile + "'");
95365 }
95366 }
95367 if (this.log.isEnabled()) {
95368 this.log.writeLine("Adding entry into typings cache: '" + packageName + "' => '" + typingFile + "'");
95369 }
95370 var info = ts.getProperty(npmLock.dependencies, key);
95371 var version_1 = info && info.version;
95372 if (!version_1) {
95373 continue;
95374 }
95375 var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
95376 this.packageNameToTypingLocation.set(packageName, newTyping);
95377 }
95378 }
95379 }
95380 if (this.log.isEnabled()) {
95381 this.log.writeLine("Finished processing cache location '" + cacheLocation + "'");
95382 }
95383 this.knownCachesSet.set(cacheLocation, true);
95384 };
95385 TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
95386 var _this = this;
95387 return typingsToInstall.filter(function (typing) {
95388 if (_this.missingTypingsSet.get(typing)) {
95389 if (_this.log.isEnabled())
95390 _this.log.writeLine("'" + typing + "' is in missingTypingsSet - skipping...");
95391 return false;
95392 }
95393 var validationResult = ts.JsTyping.validatePackageName(typing);
95394 if (validationResult !== 0 /* Ok */) {
95395 // add typing name to missing set so we won't process it again
95396 _this.missingTypingsSet.set(typing, true);
95397 if (_this.log.isEnabled())
95398 _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing));
95399 return false;
95400 }
95401 if (!_this.typesRegistry.has(typing)) {
95402 if (_this.log.isEnabled())
95403 _this.log.writeLine("Entry for package '" + typing + "' does not exist in local types registry - skipping...");
95404 return false;
95405 }
95406 if (_this.packageNameToTypingLocation.get(typing) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typing), _this.typesRegistry.get(typing))) {
95407 if (_this.log.isEnabled())
95408 _this.log.writeLine("'" + typing + "' already has an up-to-date typing - skipping...");
95409 return false;
95410 }
95411 return true;
95412 });
95413 };
95414 TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) {
95415 var npmConfigPath = ts.combinePaths(directory, "package.json");
95416 if (this.log.isEnabled()) {
95417 this.log.writeLine("Npm config file: " + npmConfigPath);
95418 }
95419 if (!this.installTypingHost.fileExists(npmConfigPath)) {
95420 if (this.log.isEnabled()) {
95421 this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one...");
95422 }
95423 this.ensureDirectoryExists(directory, this.installTypingHost);
95424 this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
95425 }
95426 };
95427 TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
95428 var _this = this;
95429 if (this.log.isEnabled()) {
95430 this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
95431 }
95432 var filteredTypings = this.filterTypings(typingsToInstall);
95433 if (filteredTypings.length === 0) {
95434 if (this.log.isEnabled()) {
95435 this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings");
95436 }
95437 this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
95438 return;
95439 }
95440 this.ensurePackageDirectoryExists(cachePath);
95441 var requestId = this.installRunCount;
95442 this.installRunCount++;
95443 // send progress event
95444 this.sendResponse({
95445 kind: server.EventBeginInstallTypes,
95446 eventId: requestId,
95447 typingsInstallerVersion: ts.version,
95448 projectName: req.projectName
95449 });
95450 var scopedTypings = filteredTypings.map(typingsName);
95451 this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) {
95452 try {
95453 if (!ok) {
95454 if (_this.log.isEnabled()) {
95455 _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings));
95456 }
95457 for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) {
95458 var typing = filteredTypings_1[_i];
95459 _this.missingTypingsSet.set(typing, true);
95460 }
95461 return;
95462 }
95463 // TODO: watch project directory
95464 if (_this.log.isEnabled()) {
95465 _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings));
95466 }
95467 var installedTypingFiles = [];
95468 for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
95469 var packageName = filteredTypings_2[_a];
95470 var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
95471 if (!typingFile) {
95472 _this.missingTypingsSet.set(packageName, true);
95473 continue;
95474 }
95475 // packageName is guaranteed to exist in typesRegistry by filterTypings
95476 var distTags = _this.typesRegistry.get(packageName);
95477 var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
95478 var newTyping = { typingLocation: typingFile, version: newVersion };
95479 _this.packageNameToTypingLocation.set(packageName, newTyping);
95480 installedTypingFiles.push(typingFile);
95481 }
95482 if (_this.log.isEnabled()) {
95483 _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
95484 }
95485 _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
95486 }
95487 finally {
95488 var response = {
95489 kind: server.EventEndInstallTypes,
95490 eventId: requestId,
95491 projectName: req.projectName,
95492 packagesToInstall: scopedTypings,
95493 installSuccess: ok,
95494 typingsInstallerVersion: ts.version // tslint:disable-line no-unnecessary-qualifier (qualified explicitly to prevent occasional shadowing)
95495 };
95496 _this.sendResponse(response);
95497 }
95498 });
95499 };
95500 TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) {
95501 var directoryName = ts.getDirectoryPath(directory);
95502 if (!host.directoryExists(directoryName)) {
95503 this.ensureDirectoryExists(directoryName, host);
95504 }
95505 if (!host.directoryExists(directory)) {
95506 host.createDirectory(directory);
95507 }
95508 };
95509 TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath) {
95510 var _this = this;
95511 if (!files.length) {
95512 // shut down existing watchers
95513 this.closeWatchers(projectName);
95514 return;
95515 }
95516 var watchers = this.projectWatchers.get(projectName);
95517 var toRemove = ts.createMap();
95518 if (!watchers) {
95519 watchers = ts.createMap();
95520 this.projectWatchers.set(projectName, watchers);
95521 }
95522 else {
95523 ts.copyEntries(watchers, toRemove);
95524 }
95525 // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
95526 watchers.isInvoked = false;
95527 var isLoggingEnabled = this.log.isEnabled();
95528 var createProjectWatcher = function (path, projectWatcherType) {
95529 var canonicalPath = _this.toCanonicalFileName(path);
95530 toRemove.delete(canonicalPath);
95531 if (watchers.has(canonicalPath)) {
95532 return;
95533 }
95534 if (isLoggingEnabled) {
95535 _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path);
95536 }
95537 var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ?
95538 _this.installTypingHost.watchFile(path, function (f, eventKind) {
95539 if (isLoggingEnabled) {
95540 _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + path + ":: handler is already invoked '" + watchers.isInvoked + "'");
95541 }
95542 if (!watchers.isInvoked) {
95543 watchers.isInvoked = true;
95544 _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
95545 }
95546 }, /*pollingInterval*/ 2000) :
95547 _this.installTypingHost.watchDirectory(path, function (f) {
95548 if (isLoggingEnabled) {
95549 _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + path + " recursive :: handler is already invoked '" + watchers.isInvoked + "'");
95550 }
95551 if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) {
95552 return;
95553 }
95554 if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) &&
95555 !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) {
95556 watchers.isInvoked = true;
95557 _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
95558 }
95559 }, /*recursive*/ true);
95560 watchers.set(canonicalPath, isLoggingEnabled ? {
95561 close: function () {
95562 _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path);
95563 watcher.close();
95564 }
95565 } : watcher);
95566 };
95567 // Create watches from list of files
95568 for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
95569 var file = files_1[_i];
95570 if (file.endsWith("/package.json") || file.endsWith("/bower.json")) {
95571 // package.json or bower.json exists, watch the file to detect changes and update typings
95572 createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
95573 continue;
95574 }
95575 // path in projectRoot, watch project root
95576 if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
95577 var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1);
95578 if (subDirectory !== -1) {
95579 // Watch subDirectory
95580 createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
95581 }
95582 else {
95583 // Watch the directory itself
95584 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
95585 }
95586 continue;
95587 }
95588 // path in global cache, watch global cache
95589 if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
95590 createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */);
95591 continue;
95592 }
95593 // watch node_modules or bower_components
95594 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
95595 }
95596 // Remove unused watches
95597 toRemove.forEach(function (watch, path) {
95598 watch.close();
95599 watchers.delete(path);
95600 });
95601 };
95602 TypingsInstaller.prototype.createSetTypings = function (request, typings) {
95603 return {
95604 projectName: request.projectName,
95605 typeAcquisition: request.typeAcquisition,
95606 compilerOptions: request.compilerOptions,
95607 typings: typings,
95608 unresolvedImports: request.unresolvedImports,
95609 kind: server.ActionSet
95610 };
95611 };
95612 TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) {
95613 this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted });
95614 this.executeWithThrottling();
95615 };
95616 TypingsInstaller.prototype.executeWithThrottling = function () {
95617 var _this = this;
95618 var _loop_1 = function () {
95619 this_1.inFlightRequestCount++;
95620 var request = this_1.pendingRunRequests.pop();
95621 this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) {
95622 _this.inFlightRequestCount--;
95623 request.onRequestCompleted(ok);
95624 _this.executeWithThrottling();
95625 });
95626 };
95627 var this_1 = this;
95628 while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
95629 _loop_1();
95630 }
95631 };
95632 return TypingsInstaller;
95633 }());
95634 typingsInstaller.TypingsInstaller = TypingsInstaller;
95635 /* @internal */
95636 function typingsName(packageName) {
95637 return "@types/" + packageName + "@ts" + ts.versionMajorMinor;
95638 }
95639 typingsInstaller.typingsName = typingsName;
95640 })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
95641 })(server = ts.server || (ts.server = {}));
95642})(ts || (ts = {}));
95643var ts;
95644(function (ts) {
95645 var server;
95646 (function (server) {
95647 var typingsInstaller;
95648 (function (typingsInstaller) {
95649 var fs = require("fs");
95650 var path = require("path");
95651 var FileLog = (function () {
95652 function FileLog(logFile) {
95653 var _this = this;
95654 this.logFile = logFile;
95655 this.isEnabled = function () {
95656 return typeof _this.logFile === "string";
95657 };
95658 this.writeLine = function (text) {
95659 if (typeof _this.logFile !== "string")
95660 return;
95661 try {
95662 fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine);
95663 }
95664 catch (e) {
95665 _this.logFile = undefined;
95666 }
95667 };
95668 }
95669 return FileLog;
95670 }());
95671 function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
95672 if (path.basename(processName).indexOf("node") === 0) {
95673 var npmPath = path.join(path.dirname(process.argv[0]), "npm");
95674 if (!validateDefaultNpmLocation) {
95675 return npmPath;
95676 }
95677 if (host.fileExists(npmPath)) {
95678 return "\"" + npmPath + "\"";
95679 }
95680 }
95681 return "npm";
95682 }
95683 function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
95684 if (!host.fileExists(typesRegistryFilePath)) {
95685 if (log.isEnabled()) {
95686 log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist");
95687 }
95688 return ts.createMap();
95689 }
95690 try {
95691 var content = JSON.parse(host.readFile(typesRegistryFilePath));
95692 return ts.createMapFromTemplate(content.entries);
95693 }
95694 catch (e) {
95695 if (log.isEnabled()) {
95696 log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack);
95697 }
95698 return ts.createMap();
95699 }
95700 }
95701 var typesRegistryPackageName = "types-registry";
95702 function getTypesRegistryFileLocation(globalTypingsCacheLocation) {
95703 return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json");
95704 }
95705 var NodeTypingsInstaller = (function (_super) {
95706 __extends(NodeTypingsInstaller, _super);
95707 function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
95708 var _this = _super.call(this, ts.sys, globalTypingsCacheLocation, typingSafeListLocation ? ts.toPath(typingSafeListLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), typesMapLocation ? ts.toPath(typesMapLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typesMap.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this;
95709 _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
95710 if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
95711 _this.npmPath = "\"" + _this.npmPath + "\"";
95712 }
95713 if (_this.log.isEnabled()) {
95714 _this.log.writeLine("Process id: " + process.pid);
95715 _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)");
95716 _this.log.writeLine("validateDefaultNpmLocation: " + validateDefaultNpmLocation);
95717 }
95718 (_this.nodeExecSync = require("child_process").execSync);
95719 _this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
95720 try {
95721 if (_this.log.isEnabled()) {
95722 _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package...");
95723 }
95724 _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation });
95725 if (_this.log.isEnabled()) {
95726 _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package");
95727 }
95728 }
95729 catch (e) {
95730 if (_this.log.isEnabled()) {
95731 _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message);
95732 }
95733 _this.delayedInitializationError = {
95734 kind: "event::initializationFailed",
95735 message: e.message
95736 };
95737 }
95738 _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
95739 return _this;
95740 }
95741 NodeTypingsInstaller.prototype.listen = function () {
95742 var _this = this;
95743 process.on("message", function (req) {
95744 if (_this.delayedInitializationError) {
95745 _this.sendResponse(_this.delayedInitializationError);
95746 _this.delayedInitializationError = undefined;
95747 }
95748 switch (req.kind) {
95749 case "discover":
95750 _this.install(req);
95751 break;
95752 case "closeProject":
95753 _this.closeProject(req);
95754 break;
95755 case "typesRegistry": {
95756 var typesRegistry_1 = {};
95757 _this.typesRegistry.forEach(function (value, key) {
95758 typesRegistry_1[key] = value;
95759 });
95760 var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 };
95761 _this.sendResponse(response);
95762 break;
95763 }
95764 case "installPackage": {
95765 var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath;
95766 var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath;
95767 if (cwd) {
95768 _this.installWorker(-1, [packageName_1], cwd, function (success) {
95769 var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + ".";
95770 var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message };
95771 _this.sendResponse(response);
95772 });
95773 }
95774 else {
95775 var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." };
95776 _this.sendResponse(response);
95777 }
95778 break;
95779 }
95780 case "inspectValue": {
95781 var response = { kind: server.ActionValueInspected, result: ts.inspectModule(req.options.fileNameToRequire) };
95782 _this.sendResponse(response);
95783 break;
95784 }
95785 default:
95786 ts.Debug.assertNever(req);
95787 }
95788 });
95789 };
95790 NodeTypingsInstaller.prototype.sendResponse = function (response) {
95791 if (this.log.isEnabled()) {
95792 this.log.writeLine("Sending response:\n " + JSON.stringify(response));
95793 }
95794 process.send(response);
95795 if (this.log.isEnabled()) {
95796 this.log.writeLine("Response has been sent.");
95797 }
95798 };
95799 NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) {
95800 var _this = this;
95801 if (this.log.isEnabled()) {
95802 this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'.");
95803 }
95804 var start = Date.now();
95805 var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); });
95806 if (this.log.isEnabled()) {
95807 this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms");
95808 }
95809 onRequestCompleted(!hasError);
95810 };
95811 NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) {
95812 if (this.log.isEnabled()) {
95813 this.log.writeLine("Exec: " + command);
95814 }
95815 try {
95816 var stdout = this.nodeExecSync(command, __assign({}, options, { encoding: "utf-8" }));
95817 if (this.log.isEnabled()) {
95818 this.log.writeLine(" Succeeded. stdout:" + indent(ts.sys.newLine, stdout));
95819 }
95820 return false;
95821 }
95822 catch (error) {
95823 var stdout = error.stdout, stderr = error.stderr;
95824 this.log.writeLine(" Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + " stderr:" + indent(ts.sys.newLine, stderr));
95825 return true;
95826 }
95827 };
95828 return NodeTypingsInstaller;
95829 }(typingsInstaller.TypingsInstaller));
95830 typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller;
95831 function getDirectoryOfPackageJson(fileName, host) {
95832 return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) {
95833 if (host.fileExists(ts.combinePaths(directory, "package.json"))) {
95834 return directory;
95835 }
95836 });
95837 }
95838 var logFilePath = server.findArgument(server.Arguments.LogFile);
95839 var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation);
95840 var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
95841 var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
95842 var npmLocation = server.findArgument(server.Arguments.NpmLocation);
95843 var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
95844 var log = new FileLog(logFilePath);
95845 if (log.isEnabled()) {
95846 process.on("uncaughtException", function (e) {
95847 log.writeLine("Unhandled exception: " + e + " at " + e.stack);
95848 });
95849 }
95850 process.on("disconnect", function () {
95851 if (log.isEnabled()) {
95852 log.writeLine("Parent process has exited, shutting down...");
95853 }
95854 process.exit(0);
95855 });
95856 var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
95857 installer.listen();
95858 function indent(newline, str) {
95859 return newline + " " + str.replace(/\r?\n/, newline + " ");
95860 }
95861 })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
95862 })(server = ts.server || (ts.server = {}));
95863})(ts || (ts = {}));
95864//# sourceMappingURL=typingsInstaller.js.map
\No newline at end of file