-
Notifications
You must be signed in to change notification settings - Fork 12.5k
/
utilitiesPublic.ts
2579 lines (2294 loc) · 96.3 KB
/
utilitiesPublic.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
__String,
AccessExpression,
AccessorDeclaration,
ArrayBindingElement,
ArrayBindingOrAssignmentElement,
ArrayBindingOrAssignmentPattern,
AssertionExpression,
AssertionKey,
AssignmentDeclarationKind,
AssignmentPattern,
AutoAccessorPropertyDeclaration,
BinaryExpression,
BindableObjectDefinePropertyCall,
BindingElement,
BindingName,
BindingOrAssignmentElement,
BindingOrAssignmentElementTarget,
BindingOrAssignmentPattern,
BindingPattern,
Block,
BooleanLiteral,
BreakOrContinueStatement,
CallChain,
CallExpression,
CallLikeExpression,
canHaveIllegalTypeParameters,
canHaveJSDoc,
CaseOrDefaultClause,
CharacterCodes,
ClassElement,
ClassLikeDeclaration,
ClassStaticBlockDeclaration,
combinePaths,
compareDiagnostics,
CompilerOptions,
ConciseBody,
ConstructorDeclaration,
ConstructorTypeNode,
contains,
createCompilerDiagnostic,
Debug,
Declaration,
DeclarationName,
DeclarationStatement,
DeclarationWithTypeParameters,
Decorator,
Diagnostic,
Diagnostics,
ElementAccessChain,
ElementAccessExpression,
emptyArray,
EntityName,
entityNameToString,
EnumDeclaration,
every,
ExportAssignment,
ExportDeclaration,
ExportSpecifier,
Expression,
FileReference,
filter,
find,
flatMap,
ForInitializer,
ForInOrOfStatement,
FunctionBody,
FunctionLikeDeclaration,
FunctionTypeNode,
GeneratedIdentifier,
GeneratedPrivateIdentifier,
GetAccessorDeclaration,
getAssignmentDeclarationKind,
getDirectoryPath,
getEffectiveModifierFlags,
getEffectiveModifierFlagsAlwaysIncludeJSDoc,
getElementOrPropertyAccessArgumentExpressionOrName,
getEmitScriptTarget,
getJSDocCommentsAndTags,
getJSDocRoot,
getJSDocTypeParameterDeclarations,
hasAccessorModifier,
HasDecorators,
hasDecorators,
HasExpressionInitializer,
HasInitializer,
HasJSDoc,
HasLocals,
HasModifiers,
hasProperty,
hasSyntacticModifier,
HasType,
Identifier,
ImportClause,
ImportEqualsDeclaration,
ImportSpecifier,
ImportTypeNode,
isAccessExpression,
isAmbientModule,
isAnyImportOrReExport,
isArrowFunction,
isAssignmentExpression,
isBinaryExpression,
isBindableStaticElementAccessExpression,
isBindingElement,
isBlock,
isCallExpression,
isCallSignatureDeclaration,
isClassExpression,
isClassStaticBlockDeclaration,
isDecorator,
isElementAccessExpression,
isExportAssignment,
isExportDeclaration,
isExportSpecifier,
isFunctionBlock,
isFunctionExpression,
isFunctionTypeNode,
isIdentifier,
isImportSpecifier,
isInJSFile,
isJSDoc,
isJSDocAugmentsTag,
isJSDocClassTag,
isJSDocDeprecatedTag,
isJSDocEnumTag,
isJSDocFunctionType,
isJSDocImplementsTag,
isJSDocOverloadTag,
isJSDocOverrideTag,
isJSDocParameterTag,
isJSDocPrivateTag,
isJSDocProtectedTag,
isJSDocPublicTag,
isJSDocReadonlyTag,
isJSDocReturnTag,
isJSDocSatisfiesTag,
isJSDocSignature,
isJSDocTemplateTag,
isJSDocThisTag,
isJSDocTypeAlias,
isJSDocTypeLiteral,
isJSDocTypeTag,
isKeyword,
isModuleBlock,
isNonNullExpression,
isNotEmittedStatement,
isOmittedExpression,
isParameter,
isPartiallyEmittedExpression,
isPrivateIdentifier,
isPropertyAccessExpression,
isPropertyAssignment,
isPropertyDeclaration,
isRootedDiskPath,
isSourceFile,
isStringLiteral,
isTypeLiteralNode,
isTypeNodeKind,
isTypeReferenceNode,
isVariableDeclaration,
isVariableDeclarationList,
isVariableStatement,
isWhiteSpaceLike,
IterationStatement,
JSDocAugmentsTag,
JSDocClassTag,
JSDocComment,
JSDocContainer,
JSDocDeprecatedTag,
JSDocEnumTag,
JSDocImplementsTag,
JSDocLink,
JSDocLinkCode,
JSDocLinkPlain,
JSDocNamespaceBody,
JSDocOverrideTag,
JSDocParameterTag,
JSDocPrivateTag,
JSDocPropertyLikeTag,
JSDocProtectedTag,
JSDocPublicTag,
JSDocReadonlyTag,
JSDocReturnTag,
JSDocSatisfiesTag,
JSDocSignature,
JSDocTag,
JSDocTemplateTag,
JSDocThisTag,
JSDocTypedefTag,
JSDocTypeTag,
JsxAttributeLike,
JsxChild,
JsxExpression,
JsxOpeningLikeElement,
JsxTagNameExpression,
KeywordSyntaxKind,
LabeledStatement,
lastOrUndefined,
LeftHandSideExpression,
length,
LiteralExpression,
LiteralToken,
MemberName,
MethodDeclaration,
Modifier,
ModifierFlags,
ModifierLike,
modifierToFlag,
ModuleBody,
ModuleDeclaration,
ModuleReference,
NamedDeclaration,
NamedExportBindings,
NamedImportBindings,
NamespaceBody,
NamespaceExport,
NamespaceImport,
NewExpression,
Node,
NodeArray,
NodeFlags,
NonNullChain,
normalizePath,
NotEmittedStatement,
NullLiteral,
ObjectBindingOrAssignmentElement,
ObjectBindingOrAssignmentPattern,
ObjectLiteralElement,
ObjectLiteralElementLike,
OptionalChain,
OptionalChainRoot,
OuterExpressionKinds,
ParameterDeclaration,
PartiallyEmittedExpression,
pathIsRelative,
PostfixUnaryExpression,
PrefixUnaryExpression,
PrivateClassElementDeclaration,
PrivateIdentifier,
PrivateIdentifierPropertyAccessExpression,
PropertyAccessChain,
PropertyAccessExpression,
PropertyDeclaration,
PropertyName,
Push,
QualifiedName,
ScriptTarget,
SetAccessorDeclaration,
setLocalizedDiagnosticMessages,
setUILocale,
SignatureDeclaration,
skipOuterExpressions,
some,
sortAndDeduplicate,
SortedReadonlyArray,
Statement,
StringLiteral,
StringLiteralLike,
stringToToken,
Symbol,
SyntaxKind,
TemplateLiteral,
TemplateLiteralToken,
TemplateMiddle,
TemplateTail,
TextChangeRange,
TextRange,
TextSpan,
tryCast,
TypeElement,
TypeNode,
TypeOnlyAliasDeclaration,
TypeOnlyExportDeclaration,
TypeOnlyImportDeclaration,
TypeParameterDeclaration,
TypeReferenceType,
UnaryExpression,
UnparsedNode,
UnparsedTextLike,
VariableDeclaration,
} from "./_namespaces/ts";
export function isExternalModuleNameRelative(moduleName: string): boolean {
// TypeScript 1.0 spec (April 2014): 11.2.1
// An external module name is "relative" if the first term is "." or "..".
// Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module.
return pathIsRelative(moduleName) || isRootedDiskPath(moduleName);
}
export function sortAndDeduplicateDiagnostics<T extends Diagnostic>(diagnostics: readonly T[]): SortedReadonlyArray<T> {
return sortAndDeduplicate<T>(diagnostics, compareDiagnostics);
}
export function getDefaultLibFileName(options: CompilerOptions): string {
switch (getEmitScriptTarget(options)) {
case ScriptTarget.ESNext:
return "lib.esnext.full.d.ts";
case ScriptTarget.ES2022:
return "lib.es2022.full.d.ts";
case ScriptTarget.ES2021:
return "lib.es2021.full.d.ts";
case ScriptTarget.ES2020:
return "lib.es2020.full.d.ts";
case ScriptTarget.ES2019:
return "lib.es2019.full.d.ts";
case ScriptTarget.ES2018:
return "lib.es2018.full.d.ts";
case ScriptTarget.ES2017:
return "lib.es2017.full.d.ts";
case ScriptTarget.ES2016:
return "lib.es2016.full.d.ts";
case ScriptTarget.ES2015:
return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
default:
return "lib.d.ts";
}
}
export function textSpanEnd(span: TextSpan) {
return span.start + span.length;
}
export function textSpanIsEmpty(span: TextSpan) {
return span.length === 0;
}
export function textSpanContainsPosition(span: TextSpan, position: number) {
return position >= span.start && position < textSpanEnd(span);
}
/** @internal */
export function textRangeContainsPositionInclusive(span: TextRange, position: number): boolean {
return position >= span.pos && position <= span.end;
}
// Returns true if 'span' contains 'other'.
export function textSpanContainsTextSpan(span: TextSpan, other: TextSpan) {
return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
}
export function textSpanOverlapsWith(span: TextSpan, other: TextSpan) {
return textSpanOverlap(span, other) !== undefined;
}
export function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined {
const overlap = textSpanIntersection(span1, span2);
return overlap && overlap.length === 0 ? undefined : overlap;
}
export function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan) {
return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
}
export function textSpanIntersectsWith(span: TextSpan, start: number, length: number) {
return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
}
export function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number) {
const end1 = start1 + length1;
const end2 = start2 + length2;
return start2 <= end1 && end2 >= start1;
}
export function textSpanIntersectsWithPosition(span: TextSpan, position: number) {
return position <= textSpanEnd(span) && position >= span.start;
}
export function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined {
const start = Math.max(span1.start, span2.start);
const end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
return start <= end ? createTextSpanFromBounds(start, end) : undefined;
}
export function createTextSpan(start: number, length: number): TextSpan {
if (start < 0) {
throw new Error("start < 0");
}
if (length < 0) {
throw new Error("length < 0");
}
return { start, length };
}
export function createTextSpanFromBounds(start: number, end: number) {
return createTextSpan(start, end - start);
}
export function textChangeRangeNewSpan(range: TextChangeRange) {
return createTextSpan(range.span.start, range.newLength);
}
export function textChangeRangeIsUnchanged(range: TextChangeRange) {
return textSpanIsEmpty(range.span) && range.newLength === 0;
}
export function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange {
if (newLength < 0) {
throw new Error("newLength < 0");
}
return { span, newLength };
}
export let unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
/**
* Called to merge all the changes that occurred across several versions of a script snapshot
* into a single change. i.e. if a user keeps making successive edits to a script we will
* have a text change from V1 to V2, V2 to V3, ..., Vn.
*
* This function will then merge those changes into a single change range valid between V1 and
* Vn.
*/
export function collapseTextChangeRangesAcrossMultipleVersions(changes: readonly TextChangeRange[]): TextChangeRange {
if (changes.length === 0) {
return unchangedTextChangeRange;
}
if (changes.length === 1) {
return changes[0];
}
// We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
// as it makes things much easier to reason about.
const change0 = changes[0];
let oldStartN = change0.span.start;
let oldEndN = textSpanEnd(change0.span);
let newEndN = oldStartN + change0.newLength;
for (let i = 1; i < changes.length; i++) {
const nextChange = changes[i];
// Consider the following case:
// i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting
// at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }.
// i.e. the span starting at 30 with length 30 is increased to length 40.
//
// 0 10 20 30 40 50 60 70 80 90 100
// -------------------------------------------------------------------------------------------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// -------------------------------------------------------------------------------------------------------
// | \
// | \
// T2 | \
// | \
// | \
// -------------------------------------------------------------------------------------------------------
//
// Merging these turns out to not be too difficult. First, determining the new start of the change is trivial
// it's just the min of the old and new starts. i.e.:
//
// 0 10 20 30 40 50 60 70 80 90 100
// ------------------------------------------------------------*------------------------------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// ----------------------------------------$-------------------$------------------------------------------
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// ----------------------------------------------------------------------*--------------------------------
//
// (Note the dots represent the newly inferred start.
// Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the
// absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
// which if the two $'s precedes the other, and we move that one forward until they line up. in this case that
// means:
//
// 0 10 20 30 40 50 60 70 80 90 100
// --------------------------------------------------------------------------------*----------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// ------------------------------------------------------------$------------------------------------------
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// ----------------------------------------------------------------------*--------------------------------
//
// In other words (in this case), we're recognizing that the second edit happened after where the first edit
// ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started
// that's the same as if we started at char 80 instead of 60.
//
// As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather
// than pushing the first edit forward to match the second, we'll push the second edit forward to match the
// first.
//
// In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
// semantics: { { start: 10, length: 70 }, newLength: 60 }
//
// The math then works out as follows.
// If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
// final result like so:
//
// {
// oldStart3: Min(oldStart1, oldStart2),
// oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
// newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
// }
const oldStart1 = oldStartN;
const oldEnd1 = oldEndN;
const newEnd1 = newEndN;
const oldStart2 = nextChange.span.start;
const oldEnd2 = textSpanEnd(nextChange.span);
const newEnd2 = oldStart2 + nextChange.newLength;
oldStartN = Math.min(oldStart1, oldStart2);
oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
}
return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
}
export function getTypeParameterOwner(d: Declaration): Declaration | undefined {
if (d && d.kind === SyntaxKind.TypeParameter) {
for (let current: Node = d; current; current = current.parent) {
if (isFunctionLike(current) || isClassLike(current) || current.kind === SyntaxKind.InterfaceDeclaration) {
return current as Declaration;
}
}
}
}
export type ParameterPropertyDeclaration = ParameterDeclaration & { parent: ConstructorDeclaration, name: Identifier };
export function isParameterPropertyDeclaration(node: Node, parent: Node): node is ParameterPropertyDeclaration {
return isParameter(node) && hasSyntacticModifier(node, ModifierFlags.ParameterPropertyModifier) && parent.kind === SyntaxKind.Constructor;
}
export function isEmptyBindingPattern(node: BindingName): node is BindingPattern {
if (isBindingPattern(node)) {
return every(node.elements, isEmptyBindingElement);
}
return false;
}
// TODO(jakebailey): It is very weird that we have BindingElement and ArrayBindingElement;
// we should have ObjectBindingElement and ArrayBindingElement, which are both BindingElement,
// just like BindingPattern is a ObjectBindingPattern or a ArrayBindingPattern.
export function isEmptyBindingElement(node: BindingElement | ArrayBindingElement): boolean {
if (isOmittedExpression(node)) {
return true;
}
return isEmptyBindingPattern(node.name);
}
export function walkUpBindingElementsAndPatterns(binding: BindingElement): VariableDeclaration | ParameterDeclaration {
let node = binding.parent;
while (isBindingElement(node.parent)) {
node = node.parent.parent;
}
return node.parent;
}
function getCombinedFlags(node: Node, getFlags: (n: Node) => number): number {
if (isBindingElement(node)) {
node = walkUpBindingElementsAndPatterns(node);
}
let flags = getFlags(node);
if (node.kind === SyntaxKind.VariableDeclaration) {
node = node.parent;
}
if (node && node.kind === SyntaxKind.VariableDeclarationList) {
flags |= getFlags(node);
node = node.parent;
}
if (node && node.kind === SyntaxKind.VariableStatement) {
flags |= getFlags(node);
}
return flags;
}
export function getCombinedModifierFlags(node: Declaration): ModifierFlags {
return getCombinedFlags(node, getEffectiveModifierFlags);
}
/** @internal */
export function getCombinedNodeFlagsAlwaysIncludeJSDoc(node: Declaration): ModifierFlags {
return getCombinedFlags(node, getEffectiveModifierFlagsAlwaysIncludeJSDoc);
}
// Returns the node flags for this node and all relevant parent nodes. This is done so that
// nodes like variable declarations and binding elements can returned a view of their flags
// that includes the modifiers from their container. i.e. flags like export/declare aren't
// stored on the variable declaration directly, but on the containing variable statement
// (if it has one). Similarly, flags for let/const are stored on the variable declaration
// list. By calling this function, all those flags are combined so that the client can treat
// the node as if it actually had those flags.
export function getCombinedNodeFlags(node: Node): NodeFlags {
return getCombinedFlags(node, n => n.flags);
}
/** @internal */
export const supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"];
/**
* Checks to see if the locale is in the appropriate format,
* and if it is, attempts to set the appropriate language.
*/
export function validateLocaleAndSetLanguage(
locale: string,
sys: { getExecutingFilePath(): string, resolvePath(path: string): string, fileExists(fileName: string): boolean, readFile(fileName: string): string | undefined },
errors?: Diagnostic[]) {
const lowerCaseLocale = locale.toLowerCase();
const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale);
if (!matchResult) {
if (errors) {
errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
}
return;
}
const language = matchResult[1];
const territory = matchResult[3];
// First try the entire locale, then fall back to just language if that's all we have.
// Either ways do not fail, and fallback to the English diagnostic strings.
if (contains(supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) {
trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
}
// Set the UI locale for string collation
setUILocale(locale);
function trySetLanguageAndTerritory(language: string, territory: string | undefined, errors?: Push<Diagnostic>): boolean {
const compilerFilePath = normalizePath(sys.getExecutingFilePath());
const containingDirectoryPath = getDirectoryPath(compilerFilePath);
let filePath = combinePaths(containingDirectoryPath, language);
if (territory) {
filePath = filePath + "-" + territory;
}
filePath = sys.resolvePath(combinePaths(filePath, "diagnosticMessages.generated.json"));
if (!sys.fileExists(filePath)) {
return false;
}
// TODO: Add codePage support for readFile?
let fileContents: string | undefined = "";
try {
fileContents = sys.readFile(filePath);
}
catch (e) {
if (errors) {
errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath));
}
return false;
}
try {
// this is a global mutation (or live binding update)!
setLocalizedDiagnosticMessages(JSON.parse(fileContents!));
}
catch {
if (errors) {
errors.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath));
}
return false;
}
return true;
}
}
export function getOriginalNode(node: Node): Node;
export function getOriginalNode<T extends Node>(node: Node, nodeTest: (node: Node) => node is T): T;
export function getOriginalNode(node: Node | undefined): Node | undefined;
export function getOriginalNode<T extends Node>(node: Node | undefined, nodeTest: (node: Node) => node is T): T | undefined;
export function getOriginalNode<T extends Node>(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined {
if (node) {
while (node.original !== undefined) {
node = node.original;
}
}
if (!node || !nodeTest) {
return node as T | undefined;
}
return nodeTest(node) ? node : undefined;
}
/**
* Iterates through the parent chain of a node and performs the callback on each parent until the callback
* returns a truthy value, then returns that value.
* If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit"
* At that point findAncestor returns undefined.
*/
export function findAncestor<T extends Node>(node: Node | undefined, callback: (element: Node) => element is T): T | undefined;
export function findAncestor(node: Node | undefined, callback: (element: Node) => boolean | "quit"): Node | undefined;
export function findAncestor(node: Node | undefined, callback: (element: Node) => boolean | "quit"): Node | undefined {
while (node) {
const result = callback(node);
if (result === "quit") {
return undefined;
}
else if (result) {
return node;
}
node = node.parent;
}
return undefined;
}
/**
* Gets a value indicating whether a node originated in the parse tree.
*
* @param node The node to test.
*/
export function isParseTreeNode(node: Node): boolean {
return (node.flags & NodeFlags.Synthesized) === 0;
}
/**
* Gets the original parse tree node for a node.
*
* @param node The original node.
* @returns The original parse tree node if found; otherwise, undefined.
*/
export function getParseTreeNode(node: Node | undefined): Node | undefined;
/**
* Gets the original parse tree node for a node.
*
* @param node The original node.
* @param nodeTest A callback used to ensure the correct type of parse tree node is returned.
* @returns The original parse tree node if found; otherwise, undefined.
*/
export function getParseTreeNode<T extends Node>(node: T | undefined, nodeTest?: (node: Node) => node is T): T | undefined;
export function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => boolean): Node | undefined {
if (node === undefined || isParseTreeNode(node)) {
return node;
}
node = node.original;
while (node) {
if (isParseTreeNode(node)) {
return !nodeTest || nodeTest(node) ? node : undefined;
}
node = node.original;
}
}
/** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
export function escapeLeadingUnderscores(identifier: string): __String {
return (identifier.length >= 2 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ ? "_" + identifier : identifier) as __String;
}
/**
* Remove extra underscore from escaped identifier text content.
*
* @param identifier The escaped identifier text.
* @returns The unescaped identifier text.
*/
export function unescapeLeadingUnderscores(identifier: __String): string {
const id = identifier as string;
return id.length >= 3 && id.charCodeAt(0) === CharacterCodes._ && id.charCodeAt(1) === CharacterCodes._ && id.charCodeAt(2) === CharacterCodes._ ? id.substr(1) : id;
}
export function idText(identifierOrPrivateName: Identifier | PrivateIdentifier): string {
return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
}
/**
* If the text of an Identifier matches a keyword (including contextual and TypeScript-specific keywords), returns the
* SyntaxKind for the matching keyword.
*/
export function identifierToKeywordKind(node: Identifier): KeywordSyntaxKind | undefined {
const token = stringToToken(node.escapedText as string);
return token ? tryCast(token, isKeyword) : undefined;
}
export function symbolName(symbol: Symbol): string {
if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) {
return idText(symbol.valueDeclaration.name);
}
return unescapeLeadingUnderscores(symbol.escapedName);
}
/**
* A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
* attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
* will be merged with)
*/
function nameForNamelessJSDocTypedef(declaration: JSDocTypedefTag | JSDocEnumTag): Identifier | PrivateIdentifier | undefined {
const hostNode = declaration.parent.parent;
if (!hostNode) {
return undefined;
}
// Covers classes, functions - any named declaration host node
if (isDeclaration(hostNode)) {
return getDeclarationIdentifier(hostNode);
}
// Covers remaining cases (returning undefined if none match).
switch (hostNode.kind) {
case SyntaxKind.VariableStatement:
if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
}
break;
case SyntaxKind.ExpressionStatement:
let expr = hostNode.expression;
if (expr.kind === SyntaxKind.BinaryExpression && (expr as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) {
expr = (expr as BinaryExpression).left;
}
switch (expr.kind) {
case SyntaxKind.PropertyAccessExpression:
return (expr as PropertyAccessExpression).name;
case SyntaxKind.ElementAccessExpression:
const arg = (expr as ElementAccessExpression).argumentExpression;
if (isIdentifier(arg)) {
return arg;
}
}
break;
case SyntaxKind.ParenthesizedExpression: {
return getDeclarationIdentifier(hostNode.expression);
}
case SyntaxKind.LabeledStatement: {
if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
return getDeclarationIdentifier(hostNode.statement);
}
break;
}
}
}
function getDeclarationIdentifier(node: Declaration | Expression): Identifier | undefined {
const name = getNameOfDeclaration(node);
return name && isIdentifier(name) ? name : undefined;
}
/** @internal */
export function nodeHasName(statement: Node, name: Identifier) {
if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name as Identifier) === idText(name)) {
return true;
}
if (isVariableStatement(statement) && some(statement.declarationList.declarations, d => nodeHasName(d, name))) {
return true;
}
return false;
}
export function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined {
return declaration.name || nameForNamelessJSDocTypedef(declaration);
}
/** @internal */
export function isNamedDeclaration(node: Node): node is NamedDeclaration & { name: DeclarationName } {
return !!(node as NamedDeclaration).name; // A 'name' property should always be a DeclarationName.
}
/** @internal */
export function getNonAssignedNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined {
switch (declaration.kind) {
case SyntaxKind.Identifier:
return declaration as Identifier;
case SyntaxKind.JSDocPropertyTag:
case SyntaxKind.JSDocParameterTag: {
const { name } = declaration as JSDocPropertyLikeTag;
if (name.kind === SyntaxKind.QualifiedName) {
return name.right;
}
break;
}
case SyntaxKind.CallExpression:
case SyntaxKind.BinaryExpression: {
const expr = declaration as BinaryExpression | CallExpression;
switch (getAssignmentDeclarationKind(expr)) {
case AssignmentDeclarationKind.ExportsProperty:
case AssignmentDeclarationKind.ThisProperty:
case AssignmentDeclarationKind.Property:
case AssignmentDeclarationKind.PrototypeProperty:
return getElementOrPropertyAccessArgumentExpressionOrName((expr as BinaryExpression).left as AccessExpression);
case AssignmentDeclarationKind.ObjectDefinePropertyValue:
case AssignmentDeclarationKind.ObjectDefinePropertyExports:
case AssignmentDeclarationKind.ObjectDefinePrototypeProperty:
return (expr as BindableObjectDefinePropertyCall).arguments[1];
default:
return undefined;
}
}
case SyntaxKind.JSDocTypedefTag:
return getNameOfJSDocTypedef(declaration as JSDocTypedefTag);
case SyntaxKind.JSDocEnumTag:
return nameForNamelessJSDocTypedef(declaration as JSDocEnumTag);
case SyntaxKind.ExportAssignment: {
const { expression } = declaration as ExportAssignment;
return isIdentifier(expression) ? expression : undefined;
}
case SyntaxKind.ElementAccessExpression:
const expr = declaration as ElementAccessExpression;
if (isBindableStaticElementAccessExpression(expr)) {
return expr.argumentExpression;
}
}
return (declaration as NamedDeclaration).name;
}
export function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined {
if (declaration === undefined) return undefined;
return getNonAssignedNameOfDeclaration(declaration) ||
(isFunctionExpression(declaration) || isArrowFunction(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
}
/** @internal */
export function getAssignedName(node: Node): DeclarationName | undefined {
if (!node.parent) {
return undefined;
}
else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) {
return node.parent.name;
}
else if (isBinaryExpression(node.parent) && node === node.parent.right) {
if (isIdentifier(node.parent.left)) {
return node.parent.left;
}
else if (isAccessExpression(node.parent.left)) {
return getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
}
}
else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) {
return node.parent.name;
}
}
export function getDecorators(node: HasDecorators): readonly Decorator[] | undefined {
if (hasDecorators(node)) {
return filter(node.modifiers, isDecorator);
}
}
export function getModifiers(node: HasModifiers): readonly Modifier[] | undefined {
if (hasSyntacticModifier(node, ModifierFlags.Modifier)) {
return filter(node.modifiers, isModifier);
}
}
function getJSDocParameterTagsWorker(param: ParameterDeclaration, noCache?: boolean): readonly JSDocParameterTag[] {
if (param.name) {
if (isIdentifier(param.name)) {
const name = param.name.escapedText;
return getJSDocTagsWorker(param.parent, noCache).filter((tag): tag is JSDocParameterTag => isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name);
}
else {
const i = param.parent.parameters.indexOf(param);
Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
const paramTags = getJSDocTagsWorker(param.parent, noCache).filter(isJSDocParameterTag);
if (i < paramTags.length) {
return [paramTags[i]];
}
}
}
// return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
return emptyArray;
}
/**
* Gets the JSDoc parameter tags for the node if present.
*
* @remarks Returns any JSDoc param tag whose name matches the provided
* parameter, whether a param tag on a containing function
* expression, or a param tag on a variable declaration whose
* initializer is the containing function. The tags closest to the
* node are returned first, so in the previous example, the param
* tag on the containing function expression would be first.
*
* For binding patterns, parameter tags are matched by position.
*/
export function getJSDocParameterTags(param: ParameterDeclaration): readonly JSDocParameterTag[] {
return getJSDocParameterTagsWorker(param, /*noCache*/ false);
}
/** @internal */
export function getJSDocParameterTagsNoCache(param: ParameterDeclaration): readonly JSDocParameterTag[] {
return getJSDocParameterTagsWorker(param, /*noCache*/ true);
}
function getJSDocTypeParameterTagsWorker(param: TypeParameterDeclaration, noCache?: boolean): readonly JSDocTemplateTag[] {