-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
autoImporter.ts
836 lines (728 loc) · 31 KB
/
autoImporter.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
/*
* autoImporter.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*
* Logic for performing auto-import completions.
*/
import { CancellationToken, CompletionItem, CompletionItemKind, SymbolKind } from 'vscode-languageserver';
import { DeclarationType } from '../analyzer/declaration';
import { ImportResolver, ModuleNameAndType } from '../analyzer/importResolver';
import { ImportType } from '../analyzer/importResult';
import {
ImportGroup,
ImportNameInfo,
ImportStatements,
ModuleNameInfo,
getImportGroup,
getImportGroupFromModuleNameAndType,
getTextEditsForAutoImportInsertion,
getTextEditsForAutoImportSymbolAddition,
getTopLevelImports,
} from '../analyzer/importStatementUtils';
import { isUserCode } from '../analyzer/sourceFileInfoUtils';
import { Symbol } from '../analyzer/symbol';
import * as SymbolNameUtils from '../analyzer/symbolNameUtils';
import { isVisibleExternally } from '../analyzer/symbolUtils';
import { throwIfCancellationRequested } from '../common/cancellationUtils';
import { appendArray } from '../common/collectionUtils';
import { ExecutionEnvironment } from '../common/configOptions';
import { TextEditAction } from '../common/editAction';
import { ProgramView, SourceFileInfo } from '../common/extensibility';
import { stripFileExtension } from '../common/pathUtils';
import * as StringUtils from '../common/stringUtils';
import { Position } from '../common/textRange';
import { Uri } from '../common/uri/uri';
import { ParseNodeType } from '../parser/parseNodes';
import { ParseFileResults } from '../parser/parser';
import { CompletionItemData, CompletionMap } from './completionProvider';
import { IndexAliasData } from './symbolIndexer';
import { fromLSPAny } from '../common/lspUtils';
export interface AutoImportSymbol {
readonly importAlias?: IndexAliasData;
readonly symbol?: Symbol;
readonly kind?: SymbolKind;
readonly itemKind?: CompletionItemKind;
}
export interface ModuleSymbolTable {
uri: Uri;
forEach(callbackfn: (symbol: AutoImportSymbol, name: string, library: boolean) => void): void;
}
export type ModuleSymbolMap = Map<string, ModuleSymbolTable>;
export interface AutoImportResult {
readonly name: string;
readonly declUri: Uri;
readonly originalName: string;
readonly originalDeclUri: Uri;
readonly insertionText: string;
readonly symbol?: Symbol;
readonly source?: string;
readonly edits?: TextEditAction[];
readonly alias?: string;
readonly kind?: CompletionItemKind;
}
export interface AutoImportOptions {
readonly patternMatcher?: (pattern: string, name: string) => boolean;
readonly allowVariableInAll?: boolean;
readonly lazyEdit?: boolean;
}
export interface ImportParts {
readonly importName: string;
readonly symbolName?: string;
readonly importFrom?: string;
readonly fileUri: Uri;
readonly dotCount: number;
readonly moduleNameAndType: ModuleNameAndType;
}
export interface ImportAliasData {
readonly importParts: ImportParts;
readonly importGroup: ImportGroup;
readonly symbol?: Symbol;
readonly kind?: SymbolKind;
readonly itemKind?: CompletionItemKind;
readonly fileUri: Uri;
}
export type AutoImportResultMap = Map<string, AutoImportResult[]>;
// Build a map of all modules within this program and the module-
// level scope that contains the symbol table for the module.
export function buildModuleSymbolsMap(files: readonly SourceFileInfo[]): ModuleSymbolMap {
const map = new Map<string, ModuleSymbolTable>();
addModuleSymbolsMap(files, map);
return map;
}
export function addModuleSymbolsMap(files: readonly SourceFileInfo[], moduleSymbolMap: ModuleSymbolMap): void {
files.forEach((file) => {
if (file.shadows.length > 0) {
// There is corresponding stub file. Don't add
// duplicated files in the map.
return;
}
const uri = file.sourceFile.getUri();
const symbolTable = file.sourceFile.getModuleSymbolTable();
if (!symbolTable) {
return;
}
const fileName = stripFileExtension(uri.fileName);
// Don't offer imports from files that are named with private
// naming semantics like "_ast.py" unless they're in the current userfile list.
if (SymbolNameUtils.isPrivateOrProtectedName(fileName) && !isUserCode(file)) {
return;
}
moduleSymbolMap.set(uri.key, {
uri,
forEach(callbackfn: (value: AutoImportSymbol, key: string, library: boolean) => void): void {
symbolTable.forEach((symbol, name) => {
if (!isVisibleExternally(symbol)) {
return;
}
const declarations = symbol.getDeclarations();
if (!declarations || declarations.length === 0) {
return;
}
const declaration = declarations[0];
if (!declaration) {
return;
}
if (declaration.type === DeclarationType.Alias && isUserCode(file)) {
// We don't include import alias in auto import
// for workspace files.
return;
}
const variableKind =
declaration.type === DeclarationType.Variable && !declaration.isConstant && !declaration.isFinal
? SymbolKind.Variable
: undefined;
callbackfn({ symbol, kind: variableKind }, name, /* library */ !isUserCode(file));
});
},
});
return;
});
}
export class AutoImporter {
private readonly _importStatements: ImportStatements;
constructor(
protected readonly execEnvironment: ExecutionEnvironment,
protected readonly program: ProgramView,
protected readonly importResolver: ImportResolver,
protected readonly parseResults: ParseFileResults,
private readonly _invocationPosition: Position,
private readonly _excludes: CompletionMap,
protected readonly moduleSymbolMap: ModuleSymbolMap,
protected readonly options: AutoImportOptions
) {
this._importStatements = getTopLevelImports(
this.parseResults.parserOutput.parseTree,
/* includeImplicitImports */ true
);
}
getAutoImportCandidates(
word: string,
similarityLimit: number,
abbrFromUsers: string | undefined,
token: CancellationToken
) {
const results: AutoImportResult[] = [];
const map = this.getCandidates(word, similarityLimit, abbrFromUsers, token);
map.forEach((v) => appendArray(results, v));
return results;
}
protected getCompletionItemData(item: CompletionItem): CompletionItemData | undefined {
return fromLSPAny<CompletionItemData>(item.data);
}
protected getCandidates(
word: string,
similarityLimit: number,
abbrFromUsers: string | undefined,
token: CancellationToken
) {
const resultMap = new Map<string, AutoImportResult[]>();
const importAliasMap = new Map<string, Map<string, ImportAliasData>>();
this.addImportsFromModuleMap(word, similarityLimit, abbrFromUsers, importAliasMap, resultMap, token);
this.addImportsFromImportAliasMap(importAliasMap, abbrFromUsers, resultMap, token);
return resultMap;
}
protected addImportsFromModuleMap(
word: string,
similarityLimit: number,
abbrFromUsers: string | undefined,
aliasMap: Map<string, Map<string, ImportAliasData>>,
results: AutoImportResultMap,
token: CancellationToken
) {
this.moduleSymbolMap.forEach((topLevelSymbols, key) => {
// See if this file should be offered as an implicit import.
const uriProperties = this.getUriProperties(this.moduleSymbolMap!, topLevelSymbols.uri);
this.processModuleSymbolTable(
topLevelSymbols,
topLevelSymbols.uri,
word,
similarityLimit,
uriProperties,
abbrFromUsers,
aliasMap,
results,
token
);
});
}
protected addImportsFromImportAliasMap(
importAliasMap: Map<string, Map<string, ImportAliasData>>,
abbrFromUsers: string | undefined,
results: AutoImportResultMap,
token: CancellationToken
) {
throwIfCancellationRequested(token);
importAliasMap.forEach((mapPerSymbolName) => {
mapPerSymbolName.forEach((importAliasData, originalName) => {
if (abbrFromUsers) {
// When alias name is used, our regular exclude mechanism would not work. we need to check
// whether import, the alias is referring to, already exists.
// ex) import numpy
// np| <= auto-import here.
// or
// from scipy import io as spio
// io| <= auto-import here
// If import statement for the module already exist, then bail out.
// ex) import module[.submodule] or from module[.submodule] import symbol
if (this._importStatements.mapByFilePath.has(importAliasData.importParts.fileUri.key)) {
return;
}
// If it is the module itself that got imported, make sure we don't import it again.
// ex) from module import submodule as ss
// submodule <= auto-import here
if (importAliasData.importParts.importFrom) {
const imported = this._importStatements.orderedImports.find(
(i) => i.moduleName === importAliasData.importParts.importFrom
);
if (
imported &&
imported.node.nodeType === ParseNodeType.ImportFrom &&
imported.node.d.imports.some(
(i) => i.d.name.d.value === importAliasData.importParts.symbolName
)
) {
return;
}
}
}
const alreadyIncluded = this._containsName(
importAliasData.importParts.importName,
importAliasData.importParts.importFrom,
results
);
if (alreadyIncluded) {
return;
}
const autoImportTextEdits = this._getTextEditsForAutoImportByFilePath(
{ name: importAliasData.importParts.symbolName, alias: abbrFromUsers },
{
name: importAliasData.importParts.importFrom ?? importAliasData.importParts.importName,
},
importAliasData.importParts.importName,
importAliasData.importGroup,
importAliasData.importParts.fileUri
);
this._addResult(results, {
name: importAliasData.importParts.importName,
alias: abbrFromUsers,
symbol: importAliasData.symbol,
kind: importAliasData.itemKind ?? convertSymbolKindToCompletionItemKind(importAliasData.kind),
source: importAliasData.importParts.importFrom,
insertionText: autoImportTextEdits.insertionText,
edits: autoImportTextEdits.edits,
declUri: importAliasData.importParts.fileUri,
originalName,
originalDeclUri: importAliasData.fileUri,
});
});
});
}
protected processModuleSymbolTable(
topLevelSymbols: ModuleSymbolTable,
moduleUri: Uri,
word: string,
similarityLimit: number,
fileProperties: { isStub: boolean; hasInit: boolean; isUserCode: boolean },
abbrFromUsers: string | undefined,
importAliasMap: Map<string, Map<string, ImportAliasData>>,
results: AutoImportResultMap,
token: CancellationToken
) {
throwIfCancellationRequested(token);
const [importSource, importGroup, moduleNameAndType] = this._getImportPartsForSymbols(moduleUri);
if (!importSource) {
return;
}
const dotCount = StringUtils.getCharacterCount(importSource, '.');
topLevelSymbols.forEach((autoImportSymbol, name) => {
if (
!this._shouldIncludeVariable(autoImportSymbol, name, fileProperties.isStub, !fileProperties.isUserCode)
) {
return;
}
// For very short matching strings, we will require an exact match. Otherwise
// we will tend to return a list that's too long. Once we get beyond two
// characters, we can do a fuzzy match.
const isSimilar = this._isSimilar(word, name, similarityLimit);
if (!isSimilar) {
return;
}
const alreadyIncluded = this._containsName(name, importSource, results);
if (alreadyIncluded) {
return;
}
// We will collect all aliases and then process it later
if (autoImportSymbol.importAlias) {
this._addToImportAliasMap(
autoImportSymbol.importAlias,
{
importParts: {
symbolName: name,
importName: name,
importFrom: importSource,
fileUri: moduleUri,
dotCount,
moduleNameAndType,
},
importGroup,
symbol: autoImportSymbol.symbol,
kind: autoImportSymbol.importAlias.kind,
itemKind: autoImportSymbol.importAlias.itemKind,
fileUri: autoImportSymbol.importAlias.moduleUri,
},
importAliasMap
);
return;
}
const nameForImportFrom = this.getNameForImportFrom(/* library */ !fileProperties.isUserCode, moduleUri);
const autoImportTextEdits = this._getTextEditsForAutoImportByFilePath(
{ name, alias: abbrFromUsers },
{ name: importSource, nameForImportFrom },
name,
importGroup,
moduleUri
);
this._addResult(results, {
name,
alias: abbrFromUsers,
symbol: autoImportSymbol.symbol,
source: importSource,
kind: autoImportSymbol.itemKind ?? convertSymbolKindToCompletionItemKind(autoImportSymbol.kind),
insertionText: autoImportTextEdits.insertionText,
edits: autoImportTextEdits.edits,
declUri: moduleUri,
originalName: name,
originalDeclUri: moduleUri,
});
});
// If the current file is in a directory that also contains an "__init__.py[i]"
// file, we can use that directory name as an implicit import target.
// Or if the file is a stub file, we can use it as import target.
// Skip this check for user code.
if (!fileProperties.isStub && !fileProperties.hasInit && !fileProperties.isUserCode) {
return;
}
const importParts = this._getImportParts(moduleUri);
if (!importParts) {
return;
}
const isSimilar = this._isSimilar(word, importParts.importName, similarityLimit);
if (!isSimilar) {
return;
}
const alreadyIncluded = this._containsName(importParts.importName, importParts.importFrom, results);
if (alreadyIncluded) {
return;
}
this._addToImportAliasMap(
{
moduleUri,
originalName: importParts.importName,
kind: SymbolKind.Module,
itemKind: CompletionItemKind.Module,
},
{
importParts,
importGroup,
kind: SymbolKind.Module,
itemKind: CompletionItemKind.Module,
fileUri: moduleUri,
},
importAliasMap
);
}
protected getNameForImportFrom(library: boolean, moduleUri: Uri): string | undefined {
return undefined;
}
protected getUriProperties<T>(map: Map<string, T>, uri: Uri) {
const fileDir = uri.getDirectory();
const initPathPy = fileDir.initPyUri;
const initPathPyi = fileDir.initPyiUri;
const isStub = uri.hasExtension('.pyi');
const hasInit = map.has(initPathPy.key) || map.has(initPathPyi.key);
const sourceFileInfo = this.program.getSourceFileInfo(uri);
return { isStub, hasInit, isUserCode: isUserCode(sourceFileInfo) };
}
private _shouldIncludeVariable(
autoImportSymbol: AutoImportSymbol,
name: string,
isStub: boolean,
library: boolean
) {
// If it is not a stub file and symbol is Variable, we only include it if
// name is public constant or type alias unless it is in __all__ for user files.
if (isStub || autoImportSymbol.kind !== SymbolKind.Variable) {
return true;
}
if (this.options.allowVariableInAll && !library && autoImportSymbol.symbol?.isInDunderAll()) {
return true;
}
return SymbolNameUtils.isPublicConstantOrTypeAlias(name);
}
private _addToImportAliasMap(
alias: IndexAliasData,
data: ImportAliasData,
importAliasMap: Map<string, Map<string, ImportAliasData>>
) {
// Since we don't resolve alias declaration using type evaluator, there is still a chance
// where we show multiple aliases for same symbols. but this should still reduce number of
// such cases.
if (!importAliasMap.has(alias.moduleUri.key)) {
const map = new Map<string, ImportAliasData>();
map.set(alias.originalName, data);
importAliasMap.set(alias.moduleUri.key, map);
return;
}
const map = importAliasMap.get(alias.moduleUri.key)!;
if (!map.has(alias.originalName)) {
map.set(alias.originalName, data);
return;
}
const existingData = map.get(alias.originalName)!;
const comparison = this._compareImportAliasData(existingData, data);
if (comparison <= 0) {
// Existing data is better than new one.
return;
}
// Keep the new data.
map.set(alias.originalName, data);
}
private _compareImportAliasData(left: ImportAliasData, right: ImportAliasData) {
const groupComparison = left.importGroup - right.importGroup;
if (groupComparison !== 0) {
return groupComparison;
}
const dotComparison = left.importParts.dotCount - right.importParts.dotCount;
if (dotComparison !== 0) {
return dotComparison;
}
if (left.symbol && !right.symbol) {
return -1;
}
if (!left.symbol && right.symbol) {
return 1;
}
return StringUtils.getStringComparer()(left.importParts.importName, right.importParts.importName);
}
private _getImportPartsForSymbols(uri: Uri): [string | undefined, ImportGroup, ModuleNameAndType] {
const localImport = this._importStatements.mapByFilePath.get(uri.key);
if (localImport) {
return [
localImport.moduleName,
getImportGroup(localImport),
{
importType: ImportType.Local,
isLocalTypingsFile: false,
moduleName: localImport.moduleName,
},
];
} else {
const moduleNameAndType = this._getModuleNameAndTypeFromFilePath(uri);
return [
moduleNameAndType.moduleName,
getImportGroupFromModuleNameAndType(moduleNameAndType),
moduleNameAndType,
];
}
}
private _getImportParts(uri: Uri) {
const name = stripFileExtension(uri.fileName);
// See if we can import module as "import xxx"
if (name === '__init__') {
return createImportParts(this._getModuleNameAndTypeFromFilePath(uri.getDirectory()));
}
return createImportParts(this._getModuleNameAndTypeFromFilePath(uri));
function createImportParts(module: ModuleNameAndType): ImportParts | undefined {
const moduleName = module.moduleName;
if (!moduleName) {
return undefined;
}
const index = moduleName.lastIndexOf('.');
const importNamePart = index > 0 ? moduleName.substring(index + 1) : undefined;
const importFrom = index > 0 ? moduleName.substring(0, index) : undefined;
return {
symbolName: importNamePart,
importName: importNamePart ?? moduleName,
importFrom,
fileUri: uri,
dotCount: StringUtils.getCharacterCount(moduleName, '.'),
moduleNameAndType: module,
};
}
}
private _isSimilar(word: string, name: string, similarityLimit: number) {
if (similarityLimit === 1) {
return word === name;
}
if (word.length <= 0 || name.length <= 0) {
return false;
}
if (!this.options.patternMatcher) {
const index = word[0] !== '_' && name[0] === '_' && name.length > 1 ? 1 : 0;
if (word[0].toLocaleLowerCase() !== name[index].toLocaleLowerCase()) {
return false;
}
return StringUtils.isPatternInSymbol(word, name);
}
return this.options.patternMatcher(word, name);
}
private _shouldExclude(name: string) {
return this._excludes.has(name, (i) =>
CompletionMap.labelOnlyIgnoringAutoImports(i, this.getCompletionItemData.bind(this))
);
}
private _containsName(name: string, source: string | undefined, results: AutoImportResultMap) {
if (this._shouldExclude(name)) {
return true;
}
const match = results.get(name);
if (match?.some((r) => r.source === source)) {
return true;
}
return false;
}
// Given the file path of a module that we want to import,
// convert to a module name that can be used in an
// 'import from' statement.
private _getModuleNameAndTypeFromFilePath(uri: Uri): ModuleNameAndType {
return this.importResolver.getModuleNameForImport(uri, this.execEnvironment);
}
private _getTextEditsForAutoImportByFilePath(
importNameInfo: ImportNameInfo,
moduleNameInfo: ModuleNameInfo,
insertionText: string,
importGroup: ImportGroup,
fileUri: Uri
): { insertionText: string; edits?: TextEditAction[] | undefined } {
// If there is no symbolName, there can't be existing import statement.
const importStatement = this._importStatements.mapByFilePath.get(fileUri.key);
if (importStatement) {
// Found import for given module. See whether we can use the module as it is.
if (importStatement.node.nodeType === ParseNodeType.Import) {
// For now, we don't check whether alias or moduleName got overwritten at
// given position
const importAlias = importStatement.subnode?.d.alias?.d.value;
if (importNameInfo.name) {
// ex) import module
// method | <= auto-import
return {
insertionText: `${importAlias ?? importStatement.moduleName}.${importNameInfo.name}`,
edits: [],
};
} else if (importAlias) {
// ex) import module as m
// m | <= auto-import
return {
insertionText: `${importAlias}`,
edits: [],
};
}
}
// Does an 'import from' statement already exist?
if (
importNameInfo.name &&
importStatement.node.nodeType === ParseNodeType.ImportFrom &&
!importStatement.node.d.isWildcardImport
) {
// If so, see whether what we want already exist.
const importNode = importStatement.node.d.imports.find((i) => i.d.name.d.value === importNameInfo.name);
if (importNode) {
// For now, we don't check whether alias or moduleName got overwritten at
// given position
const importAlias = importNode.d.alias?.d.value;
return {
insertionText: `${importAlias ?? importNameInfo.name}`,
edits: [],
};
}
// If not, add what we want at the existing 'import from' statement as long as
// what is imported is not module itself.
// ex) don't add "path" to existing "from os.path import dirname" statement.
if (moduleNameInfo.name === importStatement.moduleName) {
return {
insertionText: importNameInfo.alias ?? insertionText,
edits: this.options.lazyEdit
? undefined
: getTextEditsForAutoImportSymbolAddition(
importNameInfo,
importStatement,
this.parseResults
),
};
}
}
} else if (importNameInfo.name) {
// If it is the module itself that got imported, make sure we don't import it again.
// ex) from module import submodule
const imported = this._importStatements.orderedImports.find((i) => i.moduleName === moduleNameInfo.name);
if (imported && imported.node.nodeType === ParseNodeType.ImportFrom && !imported.node.d.isWildcardImport) {
const importFrom = imported.node.d.imports.find((i) => i.d.name.d.value === importNameInfo.name);
if (importFrom) {
// For now, we don't check whether alias or moduleName got overwritten at
// given position. only move to alias, but not the other way around
const importAlias = importFrom.d.alias?.d.value;
if (importAlias) {
return {
insertionText: `${importAlias}`,
edits: [],
};
}
} else {
// If not, add what we want at the existing import from statement.
return {
insertionText: importNameInfo.alias ?? insertionText,
edits: this.options.lazyEdit
? undefined
: getTextEditsForAutoImportSymbolAddition(importNameInfo, imported, this.parseResults),
};
}
}
// Check whether it is one of implicit imports
const importFrom = this._importStatements.implicitImports?.get(fileUri.key);
if (importFrom) {
// For now, we don't check whether alias or moduleName got overwritten at
// given position
const importAlias = importFrom.d.alias?.d.value;
return {
insertionText: `${importAlias ?? importFrom.d.name.d.value}.${importNameInfo.name}`,
edits: [],
};
}
}
return {
insertionText: importNameInfo.alias ?? insertionText,
edits: this.options.lazyEdit
? undefined
: getTextEditsForAutoImportInsertion(
importNameInfo,
moduleNameInfo,
this._importStatements,
importGroup,
this.parseResults,
this._invocationPosition
),
};
}
private _addResult(results: AutoImportResultMap, result: AutoImportResult) {
let entries = results.get(result.name);
if (!entries) {
entries = [];
results.set(result.name, entries);
}
entries.push(result);
}
}
export function convertSymbolKindToCompletionItemKind(kind: SymbolKind | undefined) {
switch (kind) {
case SymbolKind.File:
return CompletionItemKind.File;
case SymbolKind.Module:
case SymbolKind.Namespace:
return CompletionItemKind.Module;
case SymbolKind.Package:
return CompletionItemKind.Folder;
case SymbolKind.Class:
return CompletionItemKind.Class;
case SymbolKind.Method:
return CompletionItemKind.Method;
case SymbolKind.Property:
return CompletionItemKind.Property;
case SymbolKind.Field:
return CompletionItemKind.Field;
case SymbolKind.Constructor:
return CompletionItemKind.Constructor;
case SymbolKind.Enum:
return CompletionItemKind.Enum;
case SymbolKind.Interface:
return CompletionItemKind.Interface;
case SymbolKind.Function:
return CompletionItemKind.Function;
case SymbolKind.Variable:
case SymbolKind.Array:
return CompletionItemKind.Variable;
case SymbolKind.String:
return CompletionItemKind.Constant;
case SymbolKind.Number:
case SymbolKind.Boolean:
return CompletionItemKind.Value;
case SymbolKind.Constant:
case SymbolKind.Null:
return CompletionItemKind.Constant;
case SymbolKind.Object:
case SymbolKind.Key:
return CompletionItemKind.Value;
case SymbolKind.EnumMember:
return CompletionItemKind.EnumMember;
case SymbolKind.Struct:
return CompletionItemKind.Struct;
case SymbolKind.Event:
return CompletionItemKind.Event;
case SymbolKind.Operator:
return CompletionItemKind.Operator;
case SymbolKind.TypeParameter:
return CompletionItemKind.TypeParameter;
default:
return undefined;
}
}