-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
Copy pathstringCompletions.ts
1430 lines (1318 loc) · 69.7 KB
/
stringCompletions.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 {
CompletionKind,
createCompletionDetails,
createCompletionDetailsForSymbol,
getCompletionEntriesFromSymbols,
getDefaultCommitCharacters,
getPropertiesForObjectExpression,
Log,
SortText,
} from "./_namespaces/ts.Completions.js";
import {
addToSeen,
altDirectorySeparator,
arrayFrom,
BinaryExpression,
CallLikeExpression,
CancellationToken,
CaseClause,
changeExtension,
CharacterCodes,
combinePaths,
comparePaths,
comparePatternKeys,
compareStringsCaseSensitive,
compareValues,
Comparison,
CompilerOptions,
CompletionEntry,
CompletionEntryDetails,
CompletionInfo,
concatenate,
contains,
containsPath,
ContextFlags,
createModuleSpecifierResolutionHost,
createSortedArray,
createTextSpan,
createTextSpanFromStringLiteralLikeContent,
Debug,
deduplicate,
directorySeparator,
ElementAccessExpression,
emptyArray,
endsWith,
ensureTrailingDirectorySeparator,
equateStringsCaseSensitive,
escapeString,
Extension,
fileExtensionIsOneOf,
filter,
find,
findAncestor,
findPackageJson,
findPackageJsons,
firstDefined,
firstOrUndefined,
flatMap,
flatten,
forEachAncestorDirectoryStoppingAtGlobalCache,
getBaseFileName,
getConditions,
getContextualTypeFromParent,
getDeclarationEmitExtensionForPath,
getDirectoryPath,
getEffectiveTypeRoots,
getEmitModuleResolutionKind,
getLeadingCommentRanges,
getOwnKeys,
getPackageJsonTypesVersionsPaths,
getPathComponents,
getPathsBasePath,
getPossibleOriginalInputExtensionForExtension,
getPossibleOriginalInputPathWithoutChangingExt,
getReplacementSpanForContextToken,
getResolvePackageJsonExports,
getResolvePackageJsonImports,
getSupportedExtensions,
getSupportedExtensionsWithJsonIfResolveJsonModule,
getTextOfJsxAttributeName,
getTextOfNode,
getTokenAtPosition,
hasIndexSignature,
hasProperty,
hasTrailingDirectorySeparator,
hostGetCanonicalFileName,
hostUsesCaseSensitiveFileNames,
ImportOrExportSpecifier,
IndexedAccessTypeNode,
InternalSymbolName,
isApplicableVersionedTypesKey,
isArray,
isCallExpression,
isIdentifier,
isIdentifierText,
isImportCall,
isInReferenceComment,
isInString,
isJsxAttribute,
isJsxOpeningLikeElement,
isLiteralTypeNode,
isObjectLiteralExpression,
isPatternMatch,
isPrivateIdentifierClassElementDeclaration,
isRootedDiskPath,
isString,
isStringLiteral,
isStringLiteralLike,
isUrl,
JsxAttribute,
LanguageServiceHost,
length,
LiteralExpression,
LiteralTypeNode,
mapDefined,
MapLike,
moduleExportNameTextEscaped,
moduleResolutionUsesNodeModules,
ModuleSpecifierEnding,
ModuleSpecifierResolutionHost,
moduleSpecifiers,
newCaseClauseTracker,
Node,
normalizePath,
normalizeSlashes,
ObjectLiteralExpression,
Path,
Program,
PropertyAssignment,
rangeContainsPosition,
readJson,
removeFileExtension,
removePrefix,
removeTrailingDirectorySeparator,
ResolutionMode,
resolvePath,
ScriptElementKind,
ScriptElementKindModifier,
ScriptTarget,
signatureHasRestParameter,
SignatureHelp,
singleElementArray,
skipConstraint,
skipParentheses,
SourceFile,
startsWith,
StringLiteralLike,
StringLiteralType,
stripQuotes,
supportedTSImplementationExtensions,
Symbol,
SyntaxKind,
textPart,
TextSpan,
tryAndIgnoreErrors,
tryDirectoryExists,
tryFileExists,
tryGetDirectories,
tryGetExtensionFromPath,
tryParsePattern,
tryReadDirectory,
tryRemoveDirectoryPrefix,
tryRemovePrefix,
Type,
TypeChecker,
TypeFlags,
UnionTypeNode,
unmangleScopedPackageName,
UserPreferences,
walkUpParenthesizedExpressions,
walkUpParenthesizedTypes,
} from "./_namespaces/ts.js";
interface NameAndKindSet {
add(value: NameAndKind): void;
has(name: string): boolean;
values(): IterableIterator<NameAndKind>;
}
const kindPrecedence = {
[ScriptElementKind.directory]: 0,
[ScriptElementKind.scriptElement]: 1,
[ScriptElementKind.externalModuleName]: 2,
};
function createNameAndKindSet(): NameAndKindSet {
const map = new Map<string, NameAndKind>();
function add(value: NameAndKind) {
const existing = map.get(value.name);
if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value.kind]) {
map.set(value.name, value);
}
}
return {
add,
has: map.has.bind(map),
values: map.values.bind(map),
};
}
/** @internal */
export function getStringLiteralCompletions(
sourceFile: SourceFile,
position: number,
contextToken: Node | undefined,
options: CompilerOptions,
host: LanguageServiceHost,
program: Program,
log: Log,
preferences: UserPreferences,
includeSymbol: boolean,
): CompletionInfo | undefined {
if (isInReferenceComment(sourceFile, position)) {
const entries = getTripleSlashReferenceCompletion(sourceFile, position, program, host, createModuleSpecifierResolutionHost(program, host));
return entries && convertPathCompletions(entries);
}
if (isInString(sourceFile, position, contextToken)) {
if (!contextToken || !isStringLiteralLike(contextToken)) return undefined;
const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program, host, preferences);
return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol);
}
}
function convertStringLiteralCompletions(
completion: StringLiteralCompletion | undefined,
contextToken: StringLiteralLike,
sourceFile: SourceFile,
host: LanguageServiceHost,
program: Program,
log: Log,
options: CompilerOptions,
preferences: UserPreferences,
position: number,
includeSymbol: boolean,
): CompletionInfo | undefined {
if (completion === undefined) {
return undefined;
}
const optionalReplacementSpan = createTextSpanFromStringLiteralLikeContent(contextToken, position);
switch (completion.kind) {
case StringLiteralCompletionKind.Paths:
return convertPathCompletions(completion.paths);
case StringLiteralCompletionKind.Properties: {
const entries = createSortedArray<CompletionEntry>();
getCompletionEntriesFromSymbols(
completion.symbols,
entries,
contextToken,
contextToken,
sourceFile,
position,
sourceFile,
host,
program,
ScriptTarget.ESNext,
log,
CompletionKind.String,
preferences,
options,
/*formatContext*/ undefined,
/*isTypeOnlyLocation*/ undefined,
/*propertyAccessToConvert*/ undefined,
/*jsxIdentifierExpected*/ undefined,
/*isJsxInitializer*/ undefined,
/*importStatementCompletion*/ undefined,
/*recommendedCompletion*/ undefined,
/*symbolToOriginInfoMap*/ undefined,
/*symbolToSortTextMap*/ undefined,
/*isJsxIdentifierExpected*/ undefined,
/*isRightOfOpenTag*/ undefined,
includeSymbol,
); // Target will not be used, so arbitrary
return {
isGlobalCompletion: false,
isMemberCompletion: true,
isNewIdentifierLocation: completion.hasIndexSignature,
optionalReplacementSpan,
entries,
defaultCommitCharacters: getDefaultCommitCharacters(completion.hasIndexSignature),
};
}
case StringLiteralCompletionKind.Types: {
const quoteChar = contextToken.kind === SyntaxKind.NoSubstitutionTemplateLiteral
? CharacterCodes.backtick
: startsWith(getTextOfNode(contextToken), "'")
? CharacterCodes.singleQuote
: CharacterCodes.doubleQuote;
const entries = completion.types.map(type => ({
name: escapeString(type.value, quoteChar),
kindModifiers: ScriptElementKindModifier.none,
kind: ScriptElementKind.string,
sortText: SortText.LocationPriority,
replacementSpan: getReplacementSpanForContextToken(contextToken, position),
commitCharacters: [],
}));
return {
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: completion.isNewIdentifier,
optionalReplacementSpan,
entries,
defaultCommitCharacters: getDefaultCommitCharacters(completion.isNewIdentifier),
};
}
default:
return Debug.assertNever(completion);
}
}
/** @internal */
export function getStringLiteralCompletionDetails(
name: string,
sourceFile: SourceFile,
position: number,
contextToken: Node | undefined,
program: Program,
host: LanguageServiceHost,
cancellationToken: CancellationToken,
preferences: UserPreferences,
): CompletionEntryDetails | undefined {
if (!contextToken || !isStringLiteralLike(contextToken)) return undefined;
const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program, host, preferences);
return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, program.getTypeChecker(), cancellationToken);
}
function stringLiteralCompletionDetails(name: string, location: Node, completion: StringLiteralCompletion, sourceFile: SourceFile, checker: TypeChecker, cancellationToken: CancellationToken): CompletionEntryDetails | undefined {
switch (completion.kind) {
case StringLiteralCompletionKind.Paths: {
const match = find(completion.paths, p => p.name === name);
return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [textPart(name)]);
}
case StringLiteralCompletionKind.Properties: {
const match = find(completion.symbols, s => s.name === name);
return match && createCompletionDetailsForSymbol(match, match.name, checker, sourceFile, location, cancellationToken);
}
case StringLiteralCompletionKind.Types:
return find(completion.types, t => t.value === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.string, [textPart(name)]) : undefined;
default:
return Debug.assertNever(completion);
}
}
function convertPathCompletions(pathCompletions: readonly PathCompletion[]): CompletionInfo {
const isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment.
const isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of.
const entries = pathCompletions.map(({ name, kind, span, extension }): CompletionEntry => ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: SortText.LocationPriority, replacementSpan: span }));
return {
isGlobalCompletion,
isMemberCompletion: false,
isNewIdentifierLocation,
entries,
defaultCommitCharacters: getDefaultCommitCharacters(isNewIdentifierLocation),
};
}
function kindModifiersFromExtension(extension: Extension | undefined): ScriptElementKindModifier {
switch (extension) {
case Extension.Dts:
return ScriptElementKindModifier.dtsModifier;
case Extension.Js:
return ScriptElementKindModifier.jsModifier;
case Extension.Json:
return ScriptElementKindModifier.jsonModifier;
case Extension.Jsx:
return ScriptElementKindModifier.jsxModifier;
case Extension.Ts:
return ScriptElementKindModifier.tsModifier;
case Extension.Tsx:
return ScriptElementKindModifier.tsxModifier;
case Extension.Dmts:
return ScriptElementKindModifier.dmtsModifier;
case Extension.Mjs:
return ScriptElementKindModifier.mjsModifier;
case Extension.Mts:
return ScriptElementKindModifier.mtsModifier;
case Extension.Dcts:
return ScriptElementKindModifier.dctsModifier;
case Extension.Cjs:
return ScriptElementKindModifier.cjsModifier;
case Extension.Cts:
return ScriptElementKindModifier.ctsModifier;
case Extension.TsBuildInfo:
return Debug.fail(`Extension ${Extension.TsBuildInfo} is unsupported.`);
case undefined:
return ScriptElementKindModifier.none;
default:
return Debug.assertNever(extension);
}
}
const enum StringLiteralCompletionKind {
Paths,
Properties,
Types,
}
interface StringLiteralCompletionsFromProperties {
readonly kind: StringLiteralCompletionKind.Properties;
readonly symbols: readonly Symbol[];
readonly hasIndexSignature: boolean;
}
interface StringLiteralCompletionsFromTypes {
readonly kind: StringLiteralCompletionKind.Types;
readonly types: readonly StringLiteralType[];
readonly isNewIdentifier: boolean;
}
type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths; readonly paths: readonly PathCompletion[]; } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes;
function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, program: Program, host: LanguageServiceHost, preferences: UserPreferences): StringLiteralCompletion | undefined {
const typeChecker = program.getTypeChecker();
const parent = walkUpParentheses(node.parent);
switch (parent.kind) {
case SyntaxKind.LiteralType: {
const grandParent = walkUpParentheses(parent.parent);
if (grandParent.kind === SyntaxKind.ImportType) {
return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, program, host, preferences) };
}
return fromUnionableLiteralType(grandParent);
}
case SyntaxKind.PropertyAssignment:
if (isObjectLiteralExpression(parent.parent) && (parent as PropertyAssignment).name === node) {
// Get quoted name of properties of the object literal expression
// i.e. interface ConfigFiles {
// 'jspm:dev': string
// }
// let files: ConfigFiles = {
// '/*completion position*/'
// }
//
// function foo(c: ConfigFiles) {}
// foo({
// '/*completion position*/'
// });
return stringLiteralCompletionsForObjectLiteral(typeChecker, parent.parent);
}
return fromContextualType() || fromContextualType(ContextFlags.None);
case SyntaxKind.ElementAccessExpression: {
const { expression, argumentExpression } = parent as ElementAccessExpression;
if (node === skipParentheses(argumentExpression)) {
// Get all names of properties on the expression
// i.e. interface A {
// 'prop1': string
// }
// let a: A;
// a['/*completion position*/']
return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression));
}
return undefined;
}
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.JsxAttribute:
if (!isRequireCallArgument(node) && !isImportCall(parent)) {
const argumentInfo = SignatureHelp.getArgumentInfoForCompletions(parent.kind === SyntaxKind.JsxAttribute ? parent.parent : node, position, sourceFile, typeChecker);
// Get string literal completions from specialized signatures of the target
// i.e. declare function f(a: 'A');
// f("/*completion position*/")
return argumentInfo && getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || fromContextualType(ContextFlags.None);
}
// falls through (is `require("")` or `require(""` or `import("")`)
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ExportDeclaration:
case SyntaxKind.ExternalModuleReference:
case SyntaxKind.JSDocImportTag:
// Get all known external module names or complete a path to a module
// i.e. import * as ns from "/*completion position*/";
// var y = import("/*completion position*/");
// import x = require("/*completion position*/");
// var y = require("/*completion position*/");
// export * from "/*completion position*/";
return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, program, host, preferences) };
case SyntaxKind.CaseClause:
const tracker = newCaseClauseTracker(typeChecker, (parent as CaseClause).parent.clauses);
const contextualTypes = fromContextualType();
if (!contextualTypes) {
return;
}
const literals = contextualTypes.types.filter(literal => !tracker.hasValue(literal.value));
return { kind: StringLiteralCompletionKind.Types, types: literals, isNewIdentifier: false };
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
// Complete string aliases in `import { "|" } from` and `export { "|" } from`
const specifier = parent as ImportOrExportSpecifier;
if (specifier.propertyName && node !== specifier.propertyName) {
return; // Don't complete in `export { "..." as "|" } from`
}
const namedImportsOrExports = specifier.parent;
const { moduleSpecifier } = namedImportsOrExports.kind === SyntaxKind.NamedImports ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent;
if (!moduleSpecifier) return;
const moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217
if (!moduleSpecifierSymbol) return;
const exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol);
const existing = new Set(namedImportsOrExports.elements.map(n => moduleExportNameTextEscaped(n.propertyName || n.name)));
const uniques = exports.filter(e => e.escapedName !== InternalSymbolName.Default && !existing.has(e.escapedName));
return { kind: StringLiteralCompletionKind.Properties, symbols: uniques, hasIndexSignature: false };
case SyntaxKind.BinaryExpression:
if ((parent as BinaryExpression).operatorToken.kind === SyntaxKind.InKeyword) {
const type = typeChecker.getTypeAtLocation((parent as BinaryExpression).right);
const properties = type.isUnion() ? typeChecker.getAllPossiblePropertiesOfTypes(type.types) : type.getApparentProperties();
return {
kind: StringLiteralCompletionKind.Properties,
symbols: properties.filter(prop => !prop.valueDeclaration || !isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)),
hasIndexSignature: false,
};
}
return fromContextualType(ContextFlags.None);
default:
return fromContextualType() || fromContextualType(ContextFlags.None);
}
function fromUnionableLiteralType(grandParent: Node): StringLiteralCompletionsFromTypes | StringLiteralCompletionsFromProperties | undefined {
switch (grandParent.kind) {
case SyntaxKind.ExpressionWithTypeArguments:
case SyntaxKind.TypeReference: {
const typeArgument = findAncestor(parent, n => n.parent === grandParent) as LiteralTypeNode;
if (typeArgument) {
return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), isNewIdentifier: false };
}
return undefined;
}
case SyntaxKind.IndexedAccessType:
// Get all apparent property names
// i.e. interface Foo {
// foo: string;
// bar: string;
// }
// let x: Foo["/*completion position*/"]
const { indexType, objectType } = grandParent as IndexedAccessTypeNode;
if (!rangeContainsPosition(indexType, position)) {
return undefined;
}
return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType));
case SyntaxKind.UnionType: {
const result = fromUnionableLiteralType(walkUpParentheses(grandParent.parent));
if (!result) {
return undefined;
}
const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(grandParent as UnionTypeNode, parent as LiteralTypeNode);
if (result.kind === StringLiteralCompletionKind.Properties) {
return { kind: StringLiteralCompletionKind.Properties, symbols: result.symbols.filter(sym => !contains(alreadyUsedTypes, sym.name)), hasIndexSignature: result.hasIndexSignature };
}
return { kind: StringLiteralCompletionKind.Types, types: result.types.filter(t => !contains(alreadyUsedTypes, t.value)), isNewIdentifier: false };
}
default:
return undefined;
}
}
function fromContextualType(contextFlags: ContextFlags = ContextFlags.Completions): StringLiteralCompletionsFromTypes | undefined {
// Get completion for string literal from string literal type
// i.e. var x: "hi" | "hello" = "/*completion position*/"
const types = getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker, contextFlags));
if (!types.length) {
return;
}
return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier: false };
}
}
function walkUpParentheses(node: Node) {
switch (node.kind) {
case SyntaxKind.ParenthesizedType:
return walkUpParenthesizedTypes(node);
case SyntaxKind.ParenthesizedExpression:
return walkUpParenthesizedExpressions(node);
default:
return node;
}
}
function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current: LiteralTypeNode): readonly string[] {
return mapDefined(union.types, type => type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined);
}
function getStringLiteralCompletionsFromSignature(call: CallLikeExpression, arg: StringLiteralLike, argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker): StringLiteralCompletionsFromTypes | undefined {
let isNewIdentifier = false;
const uniques = new Set<string>();
const editingArgument = isJsxOpeningLikeElement(call) ? Debug.checkDefined(findAncestor(arg.parent, isJsxAttribute)) : arg;
const candidates = checker.getCandidateSignaturesForStringLiteralCompletions(call, editingArgument);
const types = flatMap(candidates, candidate => {
if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return;
let type = candidate.getTypeParameterAtPosition(argumentInfo.argumentIndex);
if (isJsxOpeningLikeElement(call)) {
const propType = checker.getTypeOfPropertyOfType(type, getTextOfJsxAttributeName((editingArgument as JsxAttribute).name));
if (propType) {
type = propType;
}
}
isNewIdentifier = isNewIdentifier || !!(type.flags & TypeFlags.String);
return getStringLiteralTypes(type, uniques);
});
return length(types) ? { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier } : undefined;
}
function stringLiteralCompletionsFromProperties(type: Type | undefined): StringLiteralCompletionsFromProperties | undefined {
return type && {
kind: StringLiteralCompletionKind.Properties,
symbols: filter(type.getApparentProperties(), prop => !(prop.valueDeclaration && isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration))),
hasIndexSignature: hasIndexSignature(type),
};
}
function stringLiteralCompletionsForObjectLiteral(checker: TypeChecker, objectLiteralExpression: ObjectLiteralExpression): StringLiteralCompletionsFromProperties | undefined {
const contextualType = checker.getContextualType(objectLiteralExpression);
if (!contextualType) return undefined;
const completionsType = checker.getContextualType(objectLiteralExpression, ContextFlags.Completions);
const symbols = getPropertiesForObjectExpression(
contextualType,
completionsType,
objectLiteralExpression,
checker,
);
return {
kind: StringLiteralCompletionKind.Properties,
symbols,
hasIndexSignature: hasIndexSignature(contextualType),
};
}
function getStringLiteralTypes(type: Type | undefined, uniques = new Set<string>()): readonly StringLiteralType[] {
if (!type) return emptyArray;
type = skipConstraint(type);
return type.isUnion() ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) :
type.isStringLiteral() && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, type.value) ? [type] : emptyArray;
}
interface NameAndKind {
readonly name: string;
readonly kind: ScriptElementKind.scriptElement | ScriptElementKind.directory | ScriptElementKind.externalModuleName;
readonly extension: Extension | undefined;
}
interface PathCompletion extends NameAndKind {
readonly span: TextSpan | undefined;
}
function nameAndKind(name: string, kind: NameAndKind["kind"], extension: Extension | undefined): NameAndKind {
return { name, kind, extension };
}
function directoryResult(name: string): NameAndKind {
return nameAndKind(name, ScriptElementKind.directory, /*extension*/ undefined);
}
function addReplacementSpans(text: string, textStart: number, names: readonly NameAndKind[]): readonly PathCompletion[] {
const span = getDirectoryFragmentTextSpan(text, textStart);
const wholeSpan = text.length === 0 ? undefined : createTextSpan(textStart, text.length);
return names.map(({ name, kind, extension }): PathCompletion => (name.includes(directorySeparator) || name.includes(altDirectorySeparator)) ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span });
}
function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, program: Program, host: LanguageServiceHost, preferences: UserPreferences): readonly PathCompletion[] {
return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, program, host, preferences));
}
function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile: SourceFile, node: LiteralExpression, program: Program, host: LanguageServiceHost, preferences: UserPreferences): readonly NameAndKind[] {
const literalValue = normalizeSlashes(node.text);
const mode = isStringLiteralLike(node) ? program.getModeForUsageLocation(sourceFile, node) : undefined;
const scriptPath = sourceFile.path;
const scriptDirectory = getDirectoryPath(scriptPath);
const compilerOptions = program.getCompilerOptions();
const typeChecker = program.getTypeChecker();
const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host);
const extensionOptions = getExtensionOptions(compilerOptions, ReferenceKind.ModuleSpecifier, sourceFile, typeChecker, preferences, mode);
return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && !compilerOptions.paths && (isRootedDiskPath(literalValue) || isUrl(literalValue))
? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, program, host, moduleSpecifierResolutionHost, scriptPath, extensionOptions)
: getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, program, host, moduleSpecifierResolutionHost, extensionOptions);
}
interface ExtensionOptions {
readonly extensionsToSearch: readonly string[];
readonly referenceKind: ReferenceKind;
readonly importingSourceFile: SourceFile;
readonly endingPreference?: UserPreferences["importModuleSpecifierEnding"];
readonly resolutionMode?: ResolutionMode;
}
function getExtensionOptions(compilerOptions: CompilerOptions, referenceKind: ReferenceKind, importingSourceFile: SourceFile, typeChecker?: TypeChecker, preferences?: UserPreferences, resolutionMode?: ResolutionMode): ExtensionOptions {
return {
extensionsToSearch: flatten(getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker)),
referenceKind,
importingSourceFile,
endingPreference: preferences?.importModuleSpecifierEnding,
resolutionMode,
};
}
function getCompletionEntriesForRelativeModules(literalValue: string, scriptDirectory: string, program: Program, host: LanguageServiceHost, moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost, scriptPath: Path, extensionOptions: ExtensionOptions) {
const compilerOptions = program.getCompilerOptions();
if (compilerOptions.rootDirs) {
return getCompletionEntriesForDirectoryFragmentWithRootDirs(
compilerOptions.rootDirs,
literalValue,
scriptDirectory,
extensionOptions,
program,
host,
moduleSpecifierResolutionHost,
scriptPath,
);
}
else {
return arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ true, scriptPath).values());
}
}
function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions, typeChecker?: TypeChecker): readonly string[][] {
/** file extensions from ambient modules declarations e.g. *.css */
const ambientModulesExtensions = !typeChecker ? [] : mapDefined(typeChecker.getAmbientModules(), module => {
const name = module.name.slice(1, -1);
if (!name.startsWith("*.") || name.includes("/")) return;
return name.slice(1);
});
const extensions = [...getSupportedExtensions(compilerOptions), ambientModulesExtensions];
const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
return moduleResolutionUsesNodeModules(moduleResolution) ?
getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, extensions) :
extensions;
}
/**
* Takes a script path and returns paths for all potential folders that could be merged with its
* containing folder via the "rootDirs" compiler option
*/
function getBaseDirectoriesFromRootDirs(rootDirs: string[], basePath: string, scriptDirectory: string, ignoreCase: boolean): readonly string[] {
// Make all paths absolute/normalized if they are not already
rootDirs = rootDirs.map(rootDirectory => ensureTrailingDirectorySeparator(normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory))));
// Determine the path to the directory containing the script relative to the root directory it is contained within
const relativeDirectory = firstDefined(rootDirs, rootDirectory => containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined)!; // TODO: GH#18217
// Now find a path for each potential directory that is to be merged with the one containing the script
return deduplicate<string>(
[...rootDirs.map(rootDirectory => combinePaths(rootDirectory, relativeDirectory)), scriptDirectory].map(baseDir => removeTrailingDirectorySeparator(baseDir)),
equateStringsCaseSensitive,
compareStringsCaseSensitive,
);
}
function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs: string[], fragment: string, scriptDirectory: string, extensionOptions: ExtensionOptions, program: Program, host: LanguageServiceHost, moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost, exclude: string): readonly NameAndKind[] {
const compilerOptions = program.getCompilerOptions();
const basePath = compilerOptions.project || host.getCurrentDirectory();
const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
return deduplicate<NameAndKind>(
flatMap(baseDirectories, baseDirectory => arrayFrom(getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ true, exclude).values())),
(itemA, itemB) => itemA.name === itemB.name && itemA.kind === itemB.kind && itemA.extension === itemB.extension,
);
}
const enum ReferenceKind {
Filename,
ModuleSpecifier,
}
/**
* Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
*/
function getCompletionEntriesForDirectoryFragment(
fragment: string,
scriptDirectory: string,
extensionOptions: ExtensionOptions,
program: Program,
host: LanguageServiceHost,
moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost,
moduleSpecifierIsRelative: boolean,
exclude?: string,
result = createNameAndKindSet(),
): NameAndKindSet {
if (fragment === undefined) {
fragment = "";
}
fragment = normalizeSlashes(fragment);
/**
* Remove the basename from the path. Note that we don't use the basename to filter completions;
* the client is responsible for refining completions.
*/
if (!hasTrailingDirectorySeparator(fragment)) {
fragment = getDirectoryPath(fragment);
}
if (fragment === "") {
fragment = "." + directorySeparator;
}
fragment = ensureTrailingDirectorySeparator(fragment);
const absolutePath = resolvePath(scriptDirectory, fragment);
const baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath);
if (!moduleSpecifierIsRelative) {
// check for a version redirect
const packageJsonPath = findPackageJson(baseDirectory, host);
if (packageJsonPath) {
const packageJson = readJson(packageJsonPath, host as { readFile: (filename: string) => string | undefined; });
const typesVersions = (packageJson as any).typesVersions;
if (typeof typesVersions === "object") {
const versionPaths = getPackageJsonTypesVersionsPaths(typesVersions)?.paths;
if (versionPaths) {
const packageDirectory = getDirectoryPath(packageJsonPath);
const pathInPackage = absolutePath.slice(ensureTrailingDirectorySeparator(packageDirectory).length);
if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, versionPaths)) {
// A true result means one of the `versionPaths` was matched, which will block relative resolution
// to files and folders from here. All reachable paths given the pattern match are already added.
return result;
}
}
}
}
}
const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
if (!tryDirectoryExists(host, baseDirectory)) return result;
// Enumerate the available files if possible
const files = tryReadDirectory(host, baseDirectory, extensionOptions.extensionsToSearch, /*exclude*/ undefined, /*include*/ ["./*"]);
if (files) {
for (let filePath of files) {
filePath = normalizePath(filePath);
if (exclude && comparePaths(filePath, exclude, scriptDirectory, ignoreCase) === Comparison.EqualTo) {
continue;
}
const { name, extension } = getFilenameWithExtensionOption(getBaseFileName(filePath), program, extensionOptions, /*isExportsOrImportsWildcard*/ false);
result.add(nameAndKind(name, ScriptElementKind.scriptElement, extension));
}
}
// If possible, get folder completion as well
const directories = tryGetDirectories(host, baseDirectory);
if (directories) {
for (const directory of directories) {
const directoryName = getBaseFileName(normalizePath(directory));
if (directoryName !== "@types") {
result.add(directoryResult(directoryName));
}
}
}
return result;
}
function getFilenameWithExtensionOption(name: string, program: Program, extensionOptions: ExtensionOptions, isExportsOrImportsWildcard: boolean): { name: string; extension: Extension | undefined; } {
const nonJsResult = moduleSpecifiers.tryGetRealFileNameForNonJsDeclarationFileName(name);
if (nonJsResult) {
return { name: nonJsResult, extension: tryGetExtensionFromPath(nonJsResult) };
}
if (extensionOptions.referenceKind === ReferenceKind.Filename) {
return { name, extension: tryGetExtensionFromPath(name) };
}
let allowedEndings = moduleSpecifiers.getModuleSpecifierPreferences(
{ importModuleSpecifierEnding: extensionOptions.endingPreference },
program,
program.getCompilerOptions(),
extensionOptions.importingSourceFile,
).getAllowedEndingsInPreferredOrder(extensionOptions.resolutionMode);
if (isExportsOrImportsWildcard) {
// If we're completing `import {} from "foo/|"` and subpaths are available via `"exports": { "./*": "./src/*" }`,
// the completion must be a (potentially extension-swapped) file name. Dropping extensions and index files is not allowed.
allowedEndings = allowedEndings.filter(e => e !== ModuleSpecifierEnding.Minimal && e !== ModuleSpecifierEnding.Index);
}
if (allowedEndings[0] === ModuleSpecifierEnding.TsExtension) {
if (fileExtensionIsOneOf(name, supportedTSImplementationExtensions)) {
return { name, extension: tryGetExtensionFromPath(name) };
}
const outputExtension = moduleSpecifiers.tryGetJSExtensionForFile(name, program.getCompilerOptions());
return outputExtension
? { name: changeExtension(name, outputExtension), extension: outputExtension }
: { name, extension: tryGetExtensionFromPath(name) };
}
if (
!isExportsOrImportsWildcard &&
(allowedEndings[0] === ModuleSpecifierEnding.Minimal || allowedEndings[0] === ModuleSpecifierEnding.Index) &&
fileExtensionIsOneOf(name, [Extension.Js, Extension.Jsx, Extension.Ts, Extension.Tsx, Extension.Dts])
) {
return { name: removeFileExtension(name), extension: tryGetExtensionFromPath(name) };
}
const outputExtension = moduleSpecifiers.tryGetJSExtensionForFile(name, program.getCompilerOptions());
return outputExtension
? { name: changeExtension(name, outputExtension), extension: outputExtension }
: { name, extension: tryGetExtensionFromPath(name) };
}
/** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */
function addCompletionEntriesFromPaths(
result: NameAndKindSet,
fragment: string,
baseDirectory: string,
extensionOptions: ExtensionOptions,
program: Program,
host: LanguageServiceHost,
moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost,
paths: MapLike<string[]>,
) {
const getPatternsForKey = (key: string) => paths[key];
const comparePaths = (a: string, b: string): Comparison => {
const patternA = tryParsePattern(a);
const patternB = tryParsePattern(b);
const lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length;
const lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length;
return compareValues(lengthB, lengthA);
};
return addCompletionEntriesFromPathsOrExportsOrImports(result, /*isExports*/ false, /*isImports*/ false, fragment, baseDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, getOwnKeys(paths), getPatternsForKey, comparePaths);
}
/** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */
function addCompletionEntriesFromPathsOrExportsOrImports(
result: NameAndKindSet,
isExports: boolean,
isImports: boolean,
fragment: string,
baseDirectory: string,
extensionOptions: ExtensionOptions,
program: Program,
host: LanguageServiceHost,
moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost,
keys: readonly string[],
getPatternsForKey: (key: string) => string[] | undefined,
comparePaths: (a: string, b: string) => Comparison,
) {
let pathResults: { results: NameAndKind[]; matchedPattern: boolean; }[] = [];
let matchedPath: string | undefined;
for (const key of keys) {
if (key === ".") continue;
const keyWithoutLeadingDotSlash = key
.replace(/^\.\//, "") // remove leading "./"
+ ((isExports || isImports) && endsWith(key, "/") ? "*" : ""); // normalize trailing `/` to `/*`
const patterns = getPatternsForKey(key);
if (patterns) {
const pathPattern = tryParsePattern(keyWithoutLeadingDotSlash);
if (!pathPattern) continue;
const isMatch = typeof pathPattern === "object" && isPatternMatch(pathPattern, fragment);
const isLongestMatch = isMatch && (matchedPath === undefined || comparePaths(keyWithoutLeadingDotSlash, matchedPath) === Comparison.LessThan);
if (isLongestMatch) {
// If this is a higher priority match than anything we've seen so far, previous results from matches are invalid, e.g.
// for `import {} from "some-package/|"` with a typesVersions:
// {
// "bar/*": ["bar/*"], // <-- 1. We add 'bar', but 'bar/*' doesn't match yet.
// "*": ["dist/*"], // <-- 2. We match here and add files from dist. 'bar' is still ok because it didn't come from a match.
// "foo/*": ["foo/*"] // <-- 3. We matched '*' earlier and added results from dist, but if 'foo/*' also matched,
// } results in dist would not be visible. 'bar' still stands because it didn't come from a match.
// This is especially important if `dist/foo` is a folder, because if we fail to clear results
// added by the '*' match, after typing `"some-package/foo/|"` we would get file results from both
// ./dist/foo and ./foo, when only the latter will actually be resolvable.
// See pathCompletionsTypesVersionsWildcard6.ts.
matchedPath = keyWithoutLeadingDotSlash;
pathResults = pathResults.filter(r => !r.matchedPattern);
}
if (typeof pathPattern === "string" || matchedPath === undefined || comparePaths(keyWithoutLeadingDotSlash, matchedPath) !== Comparison.GreaterThan) {
pathResults.push({
matchedPattern: isMatch,
results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost)
.map(({ name, kind, extension }) => nameAndKind(name, kind, extension)),
});
}
}
}
pathResults.forEach(pathResult => pathResult.results.forEach(r => result.add(r)));
return matchedPath !== undefined;
}
/**
* Check all of the declared modules and those in node modules. Possible sources of modules:
* Modules that are found by the type checker
* Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option)
* Modules from node_modules (i.e. those listed in package.json)
* This includes all files that are found in node_modules/moduleName/ with acceptable file extensions
*/
function getCompletionEntriesForNonRelativeModules(
fragment: string,
scriptPath: string,
mode: ResolutionMode,
program: Program,
host: LanguageServiceHost,
moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost,
extensionOptions: ExtensionOptions,
): readonly NameAndKind[] {
const typeChecker = program.getTypeChecker();
const compilerOptions = program.getCompilerOptions();
const { baseUrl, paths } = compilerOptions;
const result = createNameAndKindSet();
const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
if (baseUrl) {
const absolute = normalizePath(combinePaths(host.getCurrentDirectory(), baseUrl));
getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, program, host, moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ false, /*exclude*/ undefined, result);
}
if (paths) {
const absolute = getPathsBasePath(compilerOptions, host)!;