-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathtreeVisitor.ts
More file actions
1732 lines (1489 loc) · 67.6 KB
/
treeVisitor.ts
File metadata and controls
1732 lines (1489 loc) · 67.6 KB
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 * as path from 'path';
import { AnalyzerFileInfo } from 'pyright-internal/analyzer/analyzerFileInfo';
import { getFileInfo, getImportInfo } from 'pyright-internal/analyzer/analyzerNodeInfo';
import { ParseTreeWalker } from 'pyright-internal/analyzer/parseTreeWalker';
import { TypeEvaluator } from 'pyright-internal/analyzer/typeEvaluatorTypes';
import { convertOffsetToPosition } from 'pyright-internal/common/positionUtils';
import { TextRange } from 'pyright-internal/common/textRange';
import { TextRangeCollection } from 'pyright-internal/common/textRangeCollection';
import {
AssignmentNode,
ClassNode,
FunctionNode,
ImportAsNode,
ImportFromAsNode,
ImportFromNode,
ImportNode,
ModuleNameNode,
ModuleNode,
NameNode,
ParameterNode,
ParseNode,
ParseNodeType,
TypeAnnotationNode,
} from 'pyright-internal/parser/parseNodes';
import * as ModifiedTypeUtils from './ModifiedTypeUtils';
import { scip } from './scip';
import * as Symbols from './symbols';
import { ScipSymbol } from './ScipSymbol';
import { Position } from './lsif-typescript/Position';
import { Range } from './lsif-typescript/Range';
import { ScipConfig } from './lib';
import * as ParseTreeUtils from 'pyright-internal/analyzer/parseTreeUtils';
import { ClassType, Type, TypeCategory } from 'pyright-internal/analyzer/types';
import * as Types from 'pyright-internal/analyzer/types';
import { TypeStubExtendedWriter } from './TypeStubExtendedWriter';
import { SourceFile } from 'pyright-internal/analyzer/sourceFile';
import { extractParameterDocumentation } from 'pyright-internal/analyzer/docStringUtils';
import {
Declaration,
DeclarationType,
isAliasDeclaration,
isIntrinsicDeclaration,
} from 'pyright-internal/analyzer/declaration';
import { ConfigOptions, ExecutionEnvironment } from 'pyright-internal/common/configOptions';
import { versionToString } from 'pyright-internal/common/pythonVersion';
import { Program } from 'pyright-internal/analyzer/program';
import PythonEnvironment from './virtualenv/PythonEnvironment';
import { Counter } from './lsif-typescript/Counter';
import PythonPackage from './virtualenv/PythonPackage';
import * as Hardcoded from './hardcoded';
import { Event } from 'vscode-languageserver';
import { HoverResults } from 'pyright-internal/languageService/hoverProvider';
import { convertDocStringToMarkdown } from 'pyright-internal/analyzer/docStringConversion';
import { assert } from 'pyright-internal/common/debug';
import { getClassFieldsRecursive } from 'pyright-internal/analyzer/typeUtils';
// Useful functions for later, but haven't gotten far enough yet to use them.
// extractParameterDocumentation
// import { getModuleDocString } from 'pyright-internal/analyzer/typeDocStringUtils';
// this.evaluator.printType(...)
var errorLevel = 0;
function softAssert(expression: any, message: string, ...exprs: any) {
if (!expression) {
if (errorLevel > 1) {
console.log(message, ...exprs);
assert(expression, message);
} else if (errorLevel === 1) {
console.warn(message, ...exprs);
}
}
return expression;
}
// const _printer = createTracePrinter([process.cwd()]);
const _msgs = new Set<string>();
const _transform = function (exprs: any[]): any[] {
const result: any[] = [];
for (let i = 0; i < exprs.length; i++) {
let val = exprs[i];
if (typeof val === 'function') {
result.push(val(...exprs.slice(i + 1)));
break;
} else {
result.push(val);
}
}
return result;
};
// log is just cheap shorthand logging library
// for debugging in --dev mode.
//
// If you pass a function, all the rest of the arguments will
// be curried into that function if the logging function is called
// (this makes it cheap to skip more expensive debugging information)
const log = {
once: (msg: string) => {
if (_msgs.has(msg)) {
return;
}
_msgs.add(msg);
console.log(msg);
},
debug: (...exprs: any[]) => {
if (errorLevel >= 2) {
console.log(..._transform(exprs));
}
},
info: (...exprs: any[]) => {
if (errorLevel >= 1) {
console.log(..._transform(exprs));
}
},
};
const _cancellationToken = {
isCancellationRequested: false,
onCancellationRequested: Event.None,
};
function parseNodeToRange(name: ParseNode, lines: TextRangeCollection<TextRange>): Range {
const posStart = convertOffsetToPosition(name.start, lines);
const start = new Position(posStart.line, posStart.character);
const posEnd = convertOffsetToPosition(name.start + name.length, lines);
const end = new Position(posEnd.line, posEnd.character);
return new Range(start, end);
}
export interface TreeVisitorConfig {
document: scip.Document;
externalSymbols: Map<string, scip.SymbolInformation>;
sourceFile: SourceFile;
evaluator: TypeEvaluator;
program: Program;
pyrightConfig: ConfigOptions;
scipConfig: ScipConfig;
pythonEnvironment: PythonEnvironment;
globalSymbols: Map<number, ScipSymbol>;
}
interface ScipSymbolOptions {
moduleName: string;
pythonPackage: PythonPackage | undefined;
}
export class TreeVisitor extends ParseTreeWalker {
private fileInfo: AnalyzerFileInfo | undefined;
private symbolInformationForNode: Set<string>;
/// maps node.id -> ScipSymbol, for document local symbols
private documentSymbols: Map<number, ScipSymbol>;
/// maps node.id: ScipSymbol, for globally accesible symbols
private globalSymbols: Map<number, ScipSymbol>;
/// maps symbol.value: SymbolInformation, for externally defined symbols
public externalSymbols: Map<string, scip.SymbolInformation>;
private _docstringWriter: TypeStubExtendedWriter;
private execEnv: ExecutionEnvironment;
private cwd: string;
private projectPackage: PythonPackage;
private stdlibPackage: PythonPackage;
private counter: Counter;
public document: scip.Document;
public evaluator: TypeEvaluator;
public program: Program;
constructor(public config: TreeVisitorConfig) {
super();
// In dev mode, we error instead of just warn
if (this.config.scipConfig.dev) {
errorLevel = 2;
}
log.info('=> Working file:', config.sourceFile.getFilePath(), '<==');
this.evaluator = config.evaluator;
this.program = config.program;
this.document = config.document;
this.externalSymbols = config.externalSymbols;
this.counter = new Counter();
this.documentSymbols = new Map();
this.globalSymbols = this.config.globalSymbols;
this.symbolInformationForNode = new Set();
this.execEnv = this.config.pyrightConfig.getExecutionEnvironments()[0];
this.stdlibPackage = new PythonPackage('python-stdlib', versionToString(this.execEnv.pythonVersion), []);
this.projectPackage = new PythonPackage(
this.config.scipConfig.projectName,
this.config.scipConfig.projectVersion,
[]
);
this.cwd = path.resolve(process.cwd());
this._docstringWriter = new TypeStubExtendedWriter(this.config.sourceFile, this.evaluator);
}
// We have to do this in visitModule because there won't necessarily be a name
// associated with the module. So this is where we can declare the definition
// site of a module (which we can use in imports or usages)
override visitModule(node: ModuleNode): boolean {
const fileInfo = getFileInfo(node);
this.fileInfo = fileInfo;
// Insert definition at the top of the file
const pythonPackage = this.getPackageInfo(node, fileInfo.moduleName);
if (pythonPackage) {
if (softAssert(pythonPackage === this.projectPackage, 'expected pythonPackage to be this.projectPackage')) {
const symbol = Symbols.makeModuleInit(pythonPackage, fileInfo.moduleName);
this.document.occurrences.push(
new scip.Occurrence({
symbol_roles: scip.SymbolRole.Definition,
symbol: symbol.value,
range: [0, 0, 0],
})
);
const documentation = [`(module) ${fileInfo.moduleName}`];
const docstring = ParseTreeUtils.getDocString(node.statements);
if (docstring) {
documentation.push(convertDocStringToMarkdown(docstring.trim()));
}
this.document.symbols.push(
new scip.SymbolInformation({
symbol: symbol.value,
documentation,
})
);
}
} else {
// TODO: We could put a symbol here, but just as a readaccess, not as a definition
// But I'm not sure that's the correct thing -- this is only when we _visit_
// a module, so I don't think we should have to do that.
softAssert(false, 'Unable to find module for node');
}
return true;
}
override visitClass(node: ClassNode): boolean {
this._docstringWriter.visitClass(node);
return true;
}
override visitTypeAnnotation(node: TypeAnnotationNode): boolean {
// We are close to being able to look up a symbol, which could give us additional information here.
// Perhaps we should be using this for additional information for any given name?
// We can revisit this in visitName or perhaps when looking up the lsif symbol
// If we see a type annotation and we are currently inside of a class,
// that means that we are describing fields of a class (as far as I can tell),
// so we need to push a new symbol
const enclosingClass = ParseTreeUtils.getEnclosingClass(node, true);
if (enclosingClass) {
const hoverResult = this.program.getHoverForPosition(
this.fileInfo!.filePath,
convertOffsetToPosition(node.start, this.fileInfo!.lines),
'markdown',
_cancellationToken
);
this.document.symbols.push(
new scip.SymbolInformation({
symbol: this.getScipSymbol(node).value,
documentation: _formatHover(hoverResult!),
})
);
}
return true;
}
override visitAssignment(node: AssignmentNode): boolean {
// Probably not performant, we should figure out if we can tell that
// this particular spot is a definition or not, or potentially cache
// per file or something?
if (node.leftExpression.nodeType == ParseNodeType.Name) {
const decls = this.evaluator.getDeclarationsForNameNode(node.leftExpression) || [];
if (decls.length > 0) {
let dec = decls[0];
if (dec.node.parent && dec.node.parent.id == node.id) {
this._docstringWriter.visitAssignment(node);
let documentation = [];
let assignmentDoc = this._docstringWriter.docstrings.get(node.id);
if (assignmentDoc) {
documentation.push('```python\n' + assignmentDoc.join('\n') + '\n```');
}
// node.typeAnnotationComment
this.document.symbols.push(
new scip.SymbolInformation({
symbol: this.getScipSymbol(dec.node).value,
documentation,
})
);
}
}
}
return true;
}
private getFunctionRelationships(node: FunctionNode): scip.Relationship[] | undefined {
// Skip all dunder methods. They all implement stuff but it's not helpful to see
// at this point in scip-python
if (node.name.value.startsWith('__')) {
return undefined;
}
let functionType = this.evaluator.getTypeOfFunction(node)!;
let enclosingClass = ParseTreeUtils.getEnclosingClass(node, true);
if (!enclosingClass) {
return undefined;
}
// methodAlwaysRaisesNotImplemented <- this is a good one for implemtnations, but maybe we don't need that
const enclosingClassType = this.evaluator.getTypeOfClass(enclosingClass);
if (!enclosingClassType) {
return undefined;
}
let relationshipMap: Map<string, scip.Relationship> = new Map();
let classType = enclosingClassType.classType;
// Use: getClassMemberIterator
// Could use this to handle each of the fields with the same name
// but it's a bit weird if you have A -> B -> C, and then you say
// that C implements A's & B's... that seems perhaps a bit too verbose.
//
// See: https://github.com/sourcegraph/scip-python/issues/50
for (const base of classType.details.baseClasses) {
if (base.category !== TypeCategory.Class) {
continue;
}
let parentMethod = base.details.fields.get(node.name.value);
if (!parentMethod) {
let fieldLookup = getClassFieldsRecursive(base).get(node.name.value);
if (fieldLookup && fieldLookup.classType.category !== TypeCategory.Unknown) {
parentMethod = fieldLookup.classType.details.fields.get(node.name.value)!;
} else {
continue;
}
}
let parentMethodType = this.evaluator.getEffectiveTypeOfSymbol(parentMethod);
if (parentMethodType.category !== TypeCategory.Function) {
continue;
}
if (
!ModifiedTypeUtils.isTypeImplementable(
functionType.functionType,
parentMethodType,
false,
true,
0,
true
)
) {
continue;
}
let decl = parentMethodType.details.declaration!;
let symbol = this.typeToSymbol(decl.node.name, decl.node, parentMethodType);
relationshipMap.set(
symbol.value,
new scip.Relationship({
symbol: symbol.value,
is_implementation: true,
})
);
}
let relationships = Array.from(relationshipMap.values());
return relationships.length > 0 ? relationships : undefined;
}
override visitFunction(node: FunctionNode): boolean {
this._docstringWriter.visitFunction(node);
// does this do return types?
const documentation = [];
let stubs = this._docstringWriter.docstrings.get(node.id)!;
documentation.push('```python\n' + stubs.join('\n') + '\n```');
let functionDoc = ParseTreeUtils.getDocString(node.suite.statements);
if (functionDoc) {
documentation.push(functionDoc);
}
let relationships: scip.Relationship[] | undefined = this.getFunctionRelationships(node);
this.document.symbols.push(
new scip.SymbolInformation({
symbol: this.getScipSymbol(node).value,
documentation,
relationships,
})
);
// Since we are manually handling various aspects, we need to make sure that we handle
// - decorators
// - name
// - return type
// - parameters
node.decorators.forEach((decoratorNode) => this.walk(decoratorNode));
this.visitName(node.name);
if (node.returnTypeAnnotation) {
this.walk(node.returnTypeAnnotation);
}
// Walk the parameters individually, with additional information about the function
node.parameters.forEach((paramNode: ParameterNode) => {
const symbol = this.getScipSymbol(paramNode);
// This pulls documentation of various styles from function docstring
const paramDocstring = paramNode.name
? extractParameterDocumentation(functionDoc || '', paramNode.name!.value)
: undefined;
const paramDocumentation = paramDocstring ? [paramDocstring] : undefined;
this.document.symbols.push(
new scip.SymbolInformation({
symbol: symbol.value,
documentation: paramDocumentation,
})
);
// Walk the parameter child nodes
this.walk(paramNode);
});
// Walk the function definition
this.walk(node.suite);
return false;
}
// `import requests`
// ^^^^^^^^ reference requests
override visitImport(node: ImportNode): boolean {
this._docstringWriter.visitImport(node);
node.list.forEach((child) => this.walk(child));
return false;
}
// from foo.bar import baz, bat
// ^^^^^^^ node.module (one single token)
// ^^^ ^^^ node.imports (individual tokens)
//
// We don't want to walk each individual name part for the node.module,
// because that leads to some confusing behavior. Instead, walk only the imports
// and then declare the new symbol for the entire module. This gives us better
// clicking for goto-def in Sourcegraph
override visitImportFrom(node: ImportFromNode): boolean {
const symbol = this.getScipSymbol(node);
this.document.occurrences.push(
new scip.Occurrence({
symbol_roles: scip.SymbolRole.ReadAccess,
symbol: symbol.value,
range: parseNodeToRange(node.module, this.fileInfo!.lines).toLsif(),
})
);
const symbolPackage = this.moduleNameNodeToPythonPackage(node.module);
if (symbolPackage === this.stdlibPackage) {
this.emitExternalSymbolInformation(node.module, symbol, []);
}
node.imports.forEach((imp) => this.walk(imp));
return false;
}
override visitImportFromAs(node: ImportFromAsNode): boolean {
this.pushNewOccurrence(node, this.getScipSymbol(node));
return false;
}
// import aliased as A
// ^^^^^^^ node.module (create new reference)
// ^ node.alias (create new local definition)
override visitImportAs(node: ImportAsNode): boolean {
const moduleName = _formatModuleName(node.module);
const importInfo = getImportInfo(node.module);
if (
importInfo &&
importInfo.resolvedPaths[0] &&
path.resolve(importInfo.resolvedPaths[0]).startsWith(this.cwd)
) {
const symbol = Symbols.makeModuleInit(this.projectPackage, moduleName);
this.pushNewOccurrence(node.module, symbol);
} else {
const pythonPackage = this.moduleNameNodeToPythonPackage(node.module);
if (pythonPackage) {
const symbol = Symbols.makeModuleInit(pythonPackage, moduleName);
this.pushNewOccurrence(node.module, symbol);
} else {
// For python packages & modules that we cannot resolve,
// we'll just make a local for the file and note that we could not resolve this module.
//
// This should be pretty helpful when debugging (and for giving users feedback when they are
// interacting with sourcegraph).
//
// TODO: The only other question would be what we should do about references to items from this module
const symbol = this.getLocalForDeclaration(node, [
`(module): ${moduleName} [unable to resolve module]`,
]);
this.pushNewOccurrence(node.module, symbol);
}
}
if (node.alias) {
this.pushNewOccurrence(node.alias, this.getLocalForDeclaration(node.alias));
}
return false;
}
private emitDeclarationWithoutNode(node: NameNode, _decl: Declaration): boolean {
const parent = node.parent!;
switch (parent.nodeType) {
// `ModuleName`s do not have nodes for definitions
// because they aren't a syntax node, they are basically
// a file location node.
//
// (as far as I know, they are the only thing to have something
// like this)
case ParseNodeType.ModuleName: {
const symbol = this.getScipSymbol(parent);
if (symbol) {
if (hasAncestor(node, ParseNodeType.ImportAs, ParseNodeType.ImportFrom)) {
softAssert(false, 'Should never see ImportAs or ImportFrom in visitName');
return true;
}
this.pushNewOccurrence(node, symbol);
return true;
}
}
default: {
softAssert(false, 'unhandled missing node for declaration');
return true;
}
}
}
private emitDeclaration(node: NameNode, decl: Declaration): boolean {
const parent = node.parent!;
if (!decl.node) {
return this.emitDeclarationWithoutNode(node, decl);
}
const existingSymbol = this.rawGetLsifSymbol(decl.node);
if (existingSymbol) {
if (decl.node.id === parent.id || decl.node.id === node.id) {
switch (decl.node.nodeType) {
case ParseNodeType.Function:
case ParseNodeType.Class:
this.pushNewOccurrence(node, existingSymbol, scip.SymbolRole.Definition, decl.node);
break;
default:
this.pushNewOccurrence(node, existingSymbol, scip.SymbolRole.Definition);
}
} else {
this.pushNewOccurrence(node, existingSymbol);
}
return true;
}
const isDefinition = decl.node.id === parent.id;
const builtinType = this.evaluator.getBuiltInType(node, node.value);
if (this.isStdlib(decl, builtinType)) {
this.emitBuiltinScipSymbol(node, builtinType, decl);
return true;
}
const declNode = decl.node;
switch (declNode.nodeType) {
case ParseNodeType.ImportAs: {
// If we see that the declaration is for an alias, then we want to just use the
// imported alias local definition. This prevents these from leaking out (which
// I think is the desired behavior)
if (declNode.alias) {
this.pushNewOccurrence(node, this.getScipSymbol(declNode.alias));
return true;
}
const moduleName = _formatModuleName(declNode.module);
const symbol = this.getSymbolOnce(declNode, () => {
const pythonPackage = this.moduleNameNodeToPythonPackage(declNode.module, decl);
if (!pythonPackage) {
return this.getLocalForDeclaration(node);
}
assert(declNode != node.parent, 'Must not be the definition');
assert(pythonPackage, 'Must have a python package: ' + moduleName);
return Symbols.makeModuleInit(pythonPackage, moduleName);
});
// TODO: We could maybe cache this to not always be asking for these names & decls
let nodeForRange: ParseNode = node;
while (nodeForRange.parent && nodeForRange.parent.nodeType === ParseNodeType.MemberAccess) {
const member = nodeForRange.parent.memberName;
const memberDecl = this.evaluator.getDeclarationsForNameNode(member, false);
// OK, so I think _only_ Modules won't have a declaration,
// so keep going until we find something that _has_ a declaration.
//
// That seems a bit goofy, but that lets us get the correct range here:
//
// importlib.resources.read_text('pre_commit.resources', 'filename')
// #^^^^^^^^^^^^^^^^^^ reference python-stdlib 3.10 `importlib.resources`/__init__:
// # ^^^^^^^^^ reference snapshot-util 0.1 `importlib.resources`/read_text().
if (memberDecl && memberDecl.length > 0) {
break;
}
nodeForRange = nodeForRange.parent;
}
this.pushNewOccurrence(nodeForRange, symbol);
return true;
}
case ParseNodeType.Function: {
// Only push an occurrence directly if it's a reference,
// otherwise handle below.
if (isDefinition) {
break;
}
this.pushNewOccurrence(node, this.getScipSymbol(declNode));
return true;
}
case ParseNodeType.Name: {
// Don't allow scope to leak from list/dict comprehensions
// (dict comprehensions are also considered ListComprehensionFor)
//
// TODO: hasAncestor should perhaps also contain the ability to quit when hitting certain nodes
// I don't know that it's great to loop all the way back up for this all the time
// We could provide a list of items that have their own scope that would be OK to be leaked
// because they aren't statements
if (hasAncestor(declNode, ParseNodeType.ListComprehensionFor)) {
this.getLocalForDeclaration(declNode);
}
break;
}
default:
break;
}
if (isIntrinsicDeclaration(decl)) {
this.pushNewOccurrence(node, this.getIntrinsicSymbol(node));
return true;
}
const typeInfo = this.evaluator.getTypeForDeclaration(decl);
if (isAliasDeclaration(decl)) {
const resolved = this.evaluator.resolveAliasDeclaration(decl, true, true);
const resolvedType = resolved ? this.evaluator.getTypeForDeclaration(resolved) : undefined;
if (!resolved) {
log.info('Missing dependency for:', node);
}
if (typeInfo.type) {
this.pushTypeReference(node, decl.node, typeInfo.type);
return true;
}
if (resolved && resolvedType && resolvedType.type) {
const isDefinition = node.id === resolved?.node.id;
const resolvedInfo = getFileInfo(node);
const hoverResult = this.program.getHoverForPosition(
resolvedInfo.filePath,
convertOffsetToPosition(node.start, resolvedInfo.lines),
'markdown',
_cancellationToken
);
if (hoverResult) {
const symbol = this.typeToSymbol(node, declNode, resolvedType.type);
this.rawSetLsifSymbol(declNode, symbol, symbol.isLocal());
if (isDefinition) {
this.emitSymbolInformationOnce(node, symbol, _formatHover(hoverResult));
}
}
this.pushTypeReference(node, resolved.node, resolvedType.type);
return true;
}
this.pushNewOccurrence(node, this.getScipSymbol(decl.node));
return true;
}
if (isDefinition) {
// In this case, decl.node == node.parent
switch (decl.node.nodeType) {
case ParseNodeType.Class: {
const symbol = this.getScipSymbol(parent);
const documentation = [];
const stub = this._docstringWriter.docstrings.get(parent.id)!;
if (stub) {
documentation.push('```python\n' + stub.join('\n') + '\n```');
}
const doc = ParseTreeUtils.getDocString(decl.node.suite.statements)?.trim();
if (doc) {
documentation.push(convertDocStringToMarkdown(doc));
}
let type = typeInfo.type;
let relationships: scip.Relationship[] | undefined = undefined;
if (type && type.category === TypeCategory.Class) {
// TODO: Add Protocol support with:
// base.compatibleProtocols
relationships = type.details.baseClasses
.filter((base) => {
if (base.category !== TypeCategory.Class) {
return false;
}
// Don't show implementations for `object` cause that's pretty useless
if (base.details.moduleName === 'builtins' && base.details.name == 'object') {
return false;
}
const pythonPackage = this.guessPackage(base.details.moduleName, base.details.filePath);
if (!pythonPackage) {
return false;
}
return true;
})
.map((base) => {
// Filtered out in previous filter
assert(base.category === TypeCategory.Class);
const pythonPackage = this.guessPackage(
base.details.moduleName,
base.details.filePath
)!;
const symbol = Symbols.makeClass(
pythonPackage,
base.details.moduleName,
base.details.name
).value;
return new scip.Relationship({
symbol,
is_implementation: true,
});
});
}
this.document.symbols.push(
new scip.SymbolInformation({
symbol: symbol.value,
documentation,
relationships,
})
);
this.pushNewOccurrence(node, this.getScipSymbol(decl.node), scip.SymbolRole.Definition, decl.node);
break;
}
default: {
this.pushNewOccurrence(node, this.getScipSymbol(decl.node), scip.SymbolRole.Definition);
}
}
return true;
}
if (decl.node.id == node.id) {
const symbol = this.getScipSymbol(decl.node);
this.pushNewOccurrence(node, symbol, scip.SymbolRole.Definition);
return true;
}
const existingLsifSymbol = this.rawGetLsifSymbol(decl.node);
if (existingLsifSymbol) {
this.pushNewOccurrence(node, existingLsifSymbol, scip.SymbolRole.ReadAccess);
return true;
}
const symbol = this.getScipSymbol(decl.node);
this.pushNewOccurrence(node, symbol);
return true;
}
private isStdlib(decl: Declaration, builtinType: Type): boolean {
if (Types.isUnknown(builtinType)) {
return false;
}
switch (builtinType.category) {
case TypeCategory.Class:
return ClassType.isBuiltIn(builtinType) || ClassType.isSpecialBuiltIn(builtinType);
case TypeCategory.Module:
return isBuiltinModuleName(builtinType.moduleName);
case TypeCategory.Function:
return isBuiltinModuleName(decl.moduleName);
case TypeCategory.OverloadedFunction:
return this.isStdlib(decl, builtinType.overloads[0]);
case TypeCategory.Union:
return builtinType.subtypes.find((subtype) => this.isStdlib(decl, subtype)) !== undefined;
}
softAssert(false, 'Unhandled builtin category:', builtinType);
return false;
}
private emitNameWithoutDeclaration(node: NameNode): boolean {
let parent = node.parent!;
switch (parent.nodeType) {
case ParseNodeType.ModuleName:
softAssert(false, "I don't think that this should be possible");
break;
// Without a declaration, it doesn't seem useful to try and add member accesses
// with locals. You'll just get a new local for every reference because we can't construct
// what these are.
//
// In the future, it could be possible that we could store what locals we have generated for a file
// (for example `unknown_module.access`, and then use the same local for all of them, but it would be quite
// difficult in my mind).
case ParseNodeType.MemberAccess:
return true;
}
log.debug(' NO DECL:', ParseTreeUtils.printParseNodeType, parent.nodeType);
this.pushNewOccurrence(node, this.getLocalForDeclaration(node));
return true;
}
override visitName(node: NameNode): boolean {
if (!node.parent) {
throw `No parent for named node: ${node.token.value}`;
}
if (node.token.value === '_') {
return true;
}
const decls = this.evaluator.getDeclarationsForNameNode(node) || [];
if (decls.length === 0) {
return this.emitNameWithoutDeclaration(node);
}
// TODO: Consider what to do with additional declarations
// Currently, the only ones that I know that can have multiple declarations are overloaded functions.
// Not sure if there are others.
// At this point, it is acceptable to pick the first one as the definition for what you'd want to do
// with Sourcegraph.
const decl = decls[0];
return this.emitDeclaration(node, decl);
}
private rawGetLsifSymbol(node: ParseNode): ScipSymbol | undefined {
return this.globalSymbols.get(node.id) || this.documentSymbols.get(node.id);
}
private rawSetLsifSymbol(node: ParseNode, sym: ScipSymbol, isLocal: boolean): void {
if (isLocal) {
this.documentSymbols.set(node.id, sym);
} else {
this.globalSymbols.set(node.id, sym);
}
}
private getScipSymbol(node: ParseNode, opts: ScipSymbolOptions | undefined = undefined): ScipSymbol {
const existing = this.rawGetLsifSymbol(node);
if (existing) {
return existing;
}
// not yet right, but good first approximation
// const scope = getScopeForNode(node)!;
// if (false && canBeLocal(node) && scope.type != ScopeType.Builtin) {
// // const newSymbol = LsifSymbol.local(this.counter.next());
// // this._symbols.set(node.id, newSymbol);
// // return newSymbol;
// }
let moduleName: string | undefined = undefined;
let pythonPackage: PythonPackage | undefined = undefined;
if (opts) {
moduleName = opts.moduleName;
pythonPackage = opts.pythonPackage;
}
if (moduleName === undefined) {
const nodeFileInfo = getFileInfo(node);
if (!nodeFileInfo) {
throw 'no file info';
}
moduleName = nodeFileInfo.moduleName;
if (moduleName == 'builtins') {
return this.emitBuiltinScipSymbol(node);
} else if (Hardcoded.stdlib_module_names.has(moduleName)) {
const symbol = this.makeScipSymbol(this.stdlibPackage, moduleName, node);
this.emitExternalSymbolInformation(node, symbol, []);
return symbol;
}
}
if (pythonPackage === undefined) {
pythonPackage = this.getPackageInfo(node, moduleName);
if (!pythonPackage) {
if (this.rawGetLsifSymbol(node)) {
return this.rawGetLsifSymbol(node)!;
}
// let newSymbol = this.makeLsifSymbol(this.projectPackage, "_", node);
const newSymbol = ScipSymbol.local(this.counter.next());
this.rawSetLsifSymbol(node, newSymbol, true);
this.emitSymbolInformationOnce(node, newSymbol);
return newSymbol;
}
}
let newSymbol = this.makeScipSymbol(pythonPackage, moduleName, node);
this.rawSetLsifSymbol(node, newSymbol, true);
return newSymbol;
}
// Intrinsics are things like:
// __name__
// __all__
//
// TODO: This isn't good anymore
private getIntrinsicSymbol(_node: ParseNode): ScipSymbol {
// return this.makeLsifSymbol(this._stdlibPackage, 'intrinsics', node);
// TODO: Should these not be locals?
return ScipSymbol.local(this.counter.next());
}
private emitBuiltinScipSymbol(
builtinNode: ParseNode,
builtinType: Type | undefined = undefined,
decl: Declaration | undefined = undefined
): ScipSymbol {
const node = builtinNode as NameNode;
if (builtinType === undefined) {
builtinType = this.evaluator.getBuiltInType(node, node.value);
}
if (!Types.isUnknown(builtinType)) {
switch (builtinType.category) {
case TypeCategory.Function: {
const symbol = this.getIntrinsicSymbol(node);
this.pushNewOccurrence(node, symbol);
const doc = builtinType.details.docString;
this.emitExternalSymbolInformation(node, symbol, doc ? [doc] : []);
return symbol;
}
case TypeCategory.OverloadedFunction: {
if (!decl) {
break;
}
const overloadedSymbol = this.getScipSymbol(decl.node);
this.pushNewOccurrence(node, overloadedSymbol);
const doc = builtinType.overloads.filter((overload) => overload.details.docString);
const docstring = [];
if (doc.length > 0 && doc[1].details.docString) {