Repository navigation
Expand file tree
/
Copy pathdefinition.rs
More file actions
1871 lines (1668 loc) · 66.7 KB
/
Copy pathdefinition.rs
File metadata and controls
1871 lines (1668 loc) · 66.7 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
use std::ops::Deref;
use ruff_db::PythonFile;
use ruff_db::files::{File, FileRange};
use ruff_db::parsed::{ParsedModuleRef, parsed_module};
use ruff_python_ast::find_node::covering_node;
use ruff_python_ast::name::Name;
use ruff_python_ast::traversal::suite;
use ruff_python_ast::{self as ast, AnyNodeRef, Expr};
use ruff_text_size::{Ranged, TextRange, TextSize};
use smallvec::SmallVec;
use crate::LoopHeaderId;
use crate::ProgramFile;
use crate::ast_node_ref::AstNodeRef;
use crate::member::ScopedMemberId;
use crate::node_key::NodeKey;
use crate::place::ScopedPlaceId;
use crate::predicate::PatternPredicate;
use crate::scope::{FileScopeId, ScopeId};
use crate::symbol::ScopedSymbolId;
use crate::unpack::{Unpack, UnpackPosition};
use crate::use_def::BindingWithConstraintsIterator;
use crate::{Db, Program, SemanticIndex};
/// A definition of a place.
///
/// ## ID stability
/// The `Definition`'s ID is stable when the only field that change is its `kind` (AST node).
///
/// The `Definition` changes when the `file`, `scope`, or `place` change. This can be
/// because a new scope gets inserted before the `Definition` or a new place is inserted
/// before this `Definition`. However, the ID can be considered stable and it is okay to use
/// `Definition` in cross-module` salsa queries or as a field on other salsa tracked structs.
#[salsa::tracked(
debug,
constructor = new_internal,
heap_size = ruff_memory_usage::heap_size
)]
#[derive(Ord, PartialOrd)]
pub struct Definition<'db> {
/// The scope in which the definition occurs.
///
/// Storing the interned scope avoids retaining the file and file-local scope separately, at
/// the cost of database lookups when either of those values is needed.
#[returns(copy)]
pub scope_id: ScopeId<'db>,
/// The place ID and re-export state of the definition.
#[returns(copy)]
place_info: DefinitionPlace,
/// WARNING: Only access this field when doing type inference for the same
/// file as where `Definition` is defined to avoid cross-file query dependencies.
#[no_eq]
#[returns(ref)]
#[tracked]
pub kind: DefinitionKind<'db>,
}
// The Salsa heap is tracked separately.
impl get_size2::GetSize for Definition<'_> {}
impl<'db> Definition<'db> {
pub(crate) fn new(
db: &'db dyn Db,
scope_id: ScopeId<'db>,
place: ScopedPlaceId,
kind: DefinitionKind<'db>,
is_reexported: bool,
) -> Self {
Self::new_internal(
db,
scope_id,
DefinitionPlace::new(place, is_reexported),
kind,
)
}
pub fn scope(self, db: &'db dyn Db) -> ScopeId<'db> {
self.scope_id(db)
}
pub fn file(self, db: &'db dyn Db) -> File {
self.scope_id(db).file(db)
}
pub fn python_file(self, db: &'db dyn Db) -> PythonFile<'db> {
self.scope_id(db).python_file(db)
}
pub fn program_file(self, db: &'db dyn Db) -> ProgramFile<'db> {
self.scope_id(db).program_file(db)
}
pub fn program(self, db: &'db dyn Db) -> Program<'db> {
self.scope_id(db).program(db)
}
pub fn file_scope(self, db: &'db dyn Db) -> FileScopeId {
self.scope_id(db).file_scope_id(db)
}
pub fn place(self, db: &'db dyn Db) -> ScopedPlaceId {
self.place_info(db).place()
}
pub fn is_reexported(self, db: &'db dyn Db) -> bool {
self.place_info(db).is_reexported()
}
pub fn full_range(self, db: &'db dyn Db, module: &ParsedModuleRef) -> FileRange {
FileRange::new(self.file(db), self.kind(db).full_range(module))
}
pub fn focus_range(self, db: &'db dyn Db, module: &ParsedModuleRef) -> FileRange {
FileRange::new(self.file(db), self.kind(db).target_range(module))
}
/// Returns the name of the item being defined, if applicable.
pub fn name(self, db: &'db dyn Db) -> Option<String> {
let module = parsed_module(db, self.python_file(db)).load(db);
let kind = self.kind(db);
match kind {
DefinitionKind::Function(def) => {
let node = def.node(&module);
Some(node.name.as_str().to_string())
}
DefinitionKind::Class(def) => {
let node = def.node(&module);
Some(node.name.as_str().to_string())
}
DefinitionKind::TypeAlias(def) => {
let node = def.node(&module);
Some(
node.name
.as_name_expr()
.expect("type alias name should be a NameExpr")
.id
.as_str()
.to_string(),
)
}
DefinitionKind::Assignment(assignment) => {
let target_node = assignment.target.node(&module);
target_node
.as_name_expr()
.map(|name_expr| name_expr.id.as_str().to_string())
}
_ => None,
}
}
/// Extract a docstring from this definition, if applicable.
/// This method returns a docstring for function, class, and attribute definitions.
/// The docstring is extracted from the first statement in the body if it's a string literal.
pub fn docstring(self, db: &'db dyn Db) -> Option<String> {
let module = parsed_module(db, self.python_file(db)).load(db);
let kind = self.kind(db);
match kind {
DefinitionKind::Assignment(assign_def) => {
let assign_node = assign_def.target(&module);
attribute_docstring(&module, assign_node)
.map(|docstring_expr| docstring_expr.value.to_str().to_owned())
}
DefinitionKind::AnnotatedAssignment(assign_def) => {
let assign_node = assign_def.target(&module);
attribute_docstring(&module, assign_node)
.map(|docstring_expr| docstring_expr.value.to_str().to_owned())
}
DefinitionKind::Function(function_def) => {
let function_node = function_def.node(&module);
docstring_from_body(&function_node.body)
.map(|docstring_expr| docstring_expr.value.to_str().to_owned())
}
DefinitionKind::Class(class_def) => {
let class_node = class_def.node(&module);
docstring_from_body(&class_node.body)
.map(|docstring_expr| docstring_expr.value.to_str().to_owned())
}
_ => None,
}
}
}
/// The identity of the place defined by a [`Definition`] and whether it is re-exported.
///
/// Keeping the re-export state in the enum lets it share the place ID's otherwise-unused
/// representation space. Storing it as a separate field on [`Definition`] would add padding to
/// every tracked definition.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, get_size2::GetSize)]
pub enum DefinitionPlace {
Symbol {
id: ScopedSymbolId,
is_reexported: bool,
},
Member {
id: ScopedMemberId,
is_reexported: bool,
},
}
impl DefinitionPlace {
fn new(place: ScopedPlaceId, is_reexported: bool) -> Self {
match place {
ScopedPlaceId::Symbol(id) => Self::Symbol { id, is_reexported },
ScopedPlaceId::Member(id) => Self::Member { id, is_reexported },
}
}
fn place(self) -> ScopedPlaceId {
match self {
Self::Symbol { id, .. } => ScopedPlaceId::Symbol(id),
Self::Member { id, .. } => ScopedPlaceId::Member(id),
}
}
fn is_reexported(self) -> bool {
match self {
Self::Symbol { is_reexported, .. } | Self::Member { is_reexported, .. } => {
is_reexported
}
}
}
}
/// Extract a docstring from a function, module, or class body.
pub fn docstring_from_body(body: &[ast::Stmt]) -> Option<&ast::ExprStringLiteral> {
let stmt = body.first()?;
// Require the docstring to be a standalone expression.
let ast::StmtExpr {
value,
range: _,
node_index: _,
} = stmt.as_expr_stmt()?;
// Only match string literals.
value.as_string_literal_expr()
}
/// Extract a docstring from an attribute.
///
/// This is a non-standardized but popular-and-supported-by-sphinx kind of docstring
/// where you just place the docstring underneath an assignment to an attribute and
/// that counts as docs.
///
/// This is annoying to extract because we have a reference to (part of) an assignment statement
/// and we need to find the statement *after it*, which is easy to say but not something the
/// AST wants to encourage.
fn attribute_docstring<'a>(
module: &'a ParsedModuleRef,
assign_lvalue: &Expr,
) -> Option<&'a ast::ExprStringLiteral> {
// Find all the ancestors of the assign lvalue
let covering_node = covering_node(module.syntax().into(), assign_lvalue.range());
// The assignment is the closest parent statement
let assign = covering_node.find_first(AnyNodeRef::is_statement).ok()?;
let parent = assign.parent()?;
let assign_node = assign.node();
// The docs must be the next statement
let parent_body = suite(assign_node, parent)?;
let next_stmt = parent_body.next_sibling()?;
// Require the docstring to be a standalone expression.
let ast::Stmt::Expr(ast::StmtExpr {
value,
range: _,
node_index: _,
}) = next_stmt
else {
return None;
};
// Only match string literals.
value.as_string_literal_expr()
}
/// One or more [`Definition`]s.
#[derive(Debug, Default, PartialEq, Eq, get_size2::GetSize)]
pub struct Definitions<'db> {
definitions: smallvec::SmallVec<[Definition<'db>; 1]>,
}
impl<'db> Definitions<'db> {
pub(crate) fn push(&mut self, definition: Definition<'db>) {
self.definitions.push(definition);
}
pub(crate) fn into_boxed_slice(self) -> Box<[Definition<'db>]> {
self.definitions.into_vec().into_boxed_slice()
}
}
impl<'db> Deref for Definitions<'db> {
type Target = [Definition<'db>];
fn deref(&self) -> &Self::Target {
&self.definitions
}
}
impl<'a, 'db> IntoIterator for &'a Definitions<'db> {
type Item = &'a Definition<'db>;
type IntoIter = std::slice::Iter<'a, Definition<'db>>;
fn into_iter(self) -> Self::IntoIter {
self.definitions.iter()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, get_size2::GetSize)]
pub enum DefinitionState<'db> {
Defined(Definition<'db>),
/// Represents the implicit "unbound"/"undeclared" definition of every place.
Undefined,
/// Represents a definition that has been deleted.
/// This used when an attribute/subscript definition (such as `x.y = ...`, `x[0] = ...`) becomes obsolete due to a reassignment of the root place.
Deleted,
}
impl<'db> DefinitionState<'db> {
pub fn is_defined_and(self, f: impl Fn(Definition<'db>) -> bool) -> bool {
matches!(self, DefinitionState::Defined(def) if f(def))
}
pub fn is_undefined_or(self, f: impl Fn(Definition<'db>) -> bool) -> bool {
matches!(self, DefinitionState::Undefined)
|| matches!(self, DefinitionState::Defined(def) if f(def))
}
#[allow(unused)]
pub fn definition(self) -> Option<Definition<'db>> {
match self {
DefinitionState::Defined(def) => Some(def),
DefinitionState::Deleted | DefinitionState::Undefined => None,
}
}
}
#[derive(Copy, Clone, Debug)]
pub(crate) enum DefinitionNodeRef<'ast, 'db> {
Import(ImportDefinitionNodeRef<'ast>),
ImportFrom(ImportFromDefinitionNodeRef<'ast>),
ImportFromSubmodule(ImportFromSubmoduleDefinitionNodeRef<'ast>),
ImportStar(StarImportDefinitionNodeRef<'ast>),
For(ForStmtDefinitionNodeRef<'ast, 'db>),
Function(&'ast ast::StmtFunctionDef),
Class(&'ast ast::StmtClassDef),
TypeAlias(&'ast ast::StmtTypeAlias),
NamedExpression(&'ast ast::ExprNamed),
Assignment(AssignmentDefinitionNodeRef<'ast, 'db>),
AnnotatedAssignment(AnnotatedAssignmentDefinitionNodeRef<'ast>),
AugmentedAssignment(&'ast ast::StmtAugAssign),
DictKeyAssignment(DictKeyAssignmentNodeRef<'ast, 'db>),
Comprehension(ComprehensionDefinitionNodeRef<'ast, 'db>),
Parameter(ParameterDefinitionNodeRef<'ast>),
LambdaParameter(LambdaParameterDefinitionNodeRef<'ast>),
WithItem(WithItemDefinitionNodeRef<'ast, 'db>),
MatchPattern(MatchPatternDefinitionNodeRef<'ast, 'db>),
ExceptHandler(ExceptHandlerDefinitionNodeRef<'ast>),
TypeVar(&'ast ast::TypeParamTypeVar),
ParamSpec(&'ast ast::TypeParamParamSpec),
TypeVarTuple(&'ast ast::TypeParamTypeVarTuple),
LoopHeader(LoopHeaderDefinitionNodeRef<'ast>),
}
impl<'ast> From<&'ast ast::StmtFunctionDef> for DefinitionNodeRef<'ast, '_> {
fn from(node: &'ast ast::StmtFunctionDef) -> Self {
Self::Function(node)
}
}
impl<'ast> From<&'ast ast::StmtClassDef> for DefinitionNodeRef<'ast, '_> {
fn from(node: &'ast ast::StmtClassDef) -> Self {
Self::Class(node)
}
}
impl<'ast> From<&'ast ast::StmtTypeAlias> for DefinitionNodeRef<'ast, '_> {
fn from(node: &'ast ast::StmtTypeAlias) -> Self {
Self::TypeAlias(node)
}
}
impl<'ast> From<&'ast ast::ExprNamed> for DefinitionNodeRef<'ast, '_> {
fn from(node: &'ast ast::ExprNamed) -> Self {
Self::NamedExpression(node)
}
}
impl<'ast> From<&'ast ast::StmtAugAssign> for DefinitionNodeRef<'ast, '_> {
fn from(node: &'ast ast::StmtAugAssign) -> Self {
Self::AugmentedAssignment(node)
}
}
impl<'ast> From<&'ast ast::TypeParamTypeVar> for DefinitionNodeRef<'ast, '_> {
fn from(value: &'ast ast::TypeParamTypeVar) -> Self {
Self::TypeVar(value)
}
}
impl<'ast> From<&'ast ast::TypeParamParamSpec> for DefinitionNodeRef<'ast, '_> {
fn from(value: &'ast ast::TypeParamParamSpec) -> Self {
Self::ParamSpec(value)
}
}
impl<'ast> From<&'ast ast::TypeParamTypeVarTuple> for DefinitionNodeRef<'ast, '_> {
fn from(value: &'ast ast::TypeParamTypeVarTuple) -> Self {
Self::TypeVarTuple(value)
}
}
impl<'ast> From<LoopHeaderDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> {
fn from(value: LoopHeaderDefinitionNodeRef<'ast>) -> Self {
Self::LoopHeader(value)
}
}
impl<'ast> From<ImportDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> {
fn from(node_ref: ImportDefinitionNodeRef<'ast>) -> Self {
Self::Import(node_ref)
}
}
impl<'ast> From<ImportFromDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> {
fn from(node_ref: ImportFromDefinitionNodeRef<'ast>) -> Self {
Self::ImportFrom(node_ref)
}
}
impl<'ast> From<ImportFromSubmoduleDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> {
fn from(node_ref: ImportFromSubmoduleDefinitionNodeRef<'ast>) -> Self {
Self::ImportFromSubmodule(node_ref)
}
}
impl<'ast, 'db> From<ForStmtDefinitionNodeRef<'ast, 'db>> for DefinitionNodeRef<'ast, 'db> {
fn from(value: ForStmtDefinitionNodeRef<'ast, 'db>) -> Self {
Self::For(value)
}
}
impl<'ast, 'db> From<AssignmentDefinitionNodeRef<'ast, 'db>> for DefinitionNodeRef<'ast, 'db> {
fn from(node_ref: AssignmentDefinitionNodeRef<'ast, 'db>) -> Self {
Self::Assignment(node_ref)
}
}
impl<'ast> From<AnnotatedAssignmentDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> {
fn from(node_ref: AnnotatedAssignmentDefinitionNodeRef<'ast>) -> Self {
Self::AnnotatedAssignment(node_ref)
}
}
impl<'ast, 'db> From<DictKeyAssignmentNodeRef<'ast, 'db>> for DefinitionNodeRef<'ast, 'db> {
fn from(node_ref: DictKeyAssignmentNodeRef<'ast, 'db>) -> Self {
Self::DictKeyAssignment(node_ref)
}
}
impl<'ast, 'db> From<WithItemDefinitionNodeRef<'ast, 'db>> for DefinitionNodeRef<'ast, 'db> {
fn from(node_ref: WithItemDefinitionNodeRef<'ast, 'db>) -> Self {
Self::WithItem(node_ref)
}
}
impl<'ast, 'db> From<ComprehensionDefinitionNodeRef<'ast, 'db>> for DefinitionNodeRef<'ast, 'db> {
fn from(node: ComprehensionDefinitionNodeRef<'ast, 'db>) -> Self {
Self::Comprehension(node)
}
}
impl<'ast> From<ParameterDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> {
fn from(node: ParameterDefinitionNodeRef<'ast>) -> Self {
Self::Parameter(node)
}
}
impl<'ast> From<LambdaParameterDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> {
fn from(node: LambdaParameterDefinitionNodeRef<'ast>) -> Self {
Self::LambdaParameter(node)
}
}
impl<'ast, 'db> From<MatchPatternDefinitionNodeRef<'ast, 'db>> for DefinitionNodeRef<'ast, 'db> {
fn from(node: MatchPatternDefinitionNodeRef<'ast, 'db>) -> Self {
Self::MatchPattern(node)
}
}
impl<'ast> From<StarImportDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> {
fn from(node: StarImportDefinitionNodeRef<'ast>) -> Self {
Self::ImportStar(node)
}
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct ImportDefinitionNodeRef<'ast> {
pub(crate) node: &'ast ast::StmtImport,
pub(crate) alias_index: usize,
pub(crate) is_reexported: bool,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct StarImportDefinitionNodeRef<'ast> {
pub(crate) node: &'ast ast::StmtImportFrom,
pub(crate) symbol_id: ScopedSymbolId,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct ImportFromDefinitionNodeRef<'ast> {
pub(crate) node: &'ast ast::StmtImportFrom,
pub(crate) alias_index: usize,
pub(crate) is_reexported: bool,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct ImportFromSubmoduleDefinitionNodeRef<'ast> {
pub(crate) node: &'ast ast::StmtImportFrom,
pub(crate) module_index: usize,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct AssignmentDefinitionNodeRef<'ast, 'db> {
pub(crate) unpack: Option<Unpack<'db>>,
pub(crate) value: &'ast ast::Expr,
pub(crate) target: &'ast ast::Expr,
pub(crate) owner: BindingsOwner,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct AnnotatedAssignmentDefinitionNodeRef<'ast> {
pub(crate) node: &'ast ast::StmtAnnAssign,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct DictKeyAssignmentNodeRef<'ast, 'db> {
pub(crate) key: &'ast ast::Expr,
pub(crate) value: &'ast ast::Expr,
pub(crate) assignment: Definition<'db>,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct WithItemDefinitionNodeRef<'ast, 'db> {
pub(crate) unpack: Option<(UnpackPosition, Unpack<'db>)>,
pub(crate) item: &'ast ast::WithItem,
pub(crate) target: &'ast ast::Expr,
pub(crate) is_async: bool,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct ForStmtDefinitionNodeRef<'ast, 'db> {
pub(crate) unpack: Option<(UnpackPosition, Unpack<'db>)>,
pub(crate) node: &'ast ast::StmtFor,
pub(crate) target: &'ast ast::Expr,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct ExceptHandlerDefinitionNodeRef<'ast> {
pub(crate) handler: &'ast ast::ExceptHandlerExceptHandler,
pub(crate) is_star: bool,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct LoopHeaderDefinitionNodeRef<'ast> {
pub(crate) loop_stmt: LoopStmtRef<'ast>,
pub(crate) place: ScopedPlaceId,
pub(crate) loop_header_id: LoopHeaderId,
}
#[derive(Copy, Clone, Debug)]
pub(crate) enum LoopStmtRef<'ast> {
While(&'ast ast::StmtWhile),
For(&'ast ast::StmtFor),
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct ComprehensionDefinitionNodeRef<'ast, 'db> {
pub(crate) unpack: Option<(UnpackPosition, Unpack<'db>)>,
pub(crate) node: &'ast ast::Comprehension,
pub(crate) target: &'ast ast::Expr,
pub(crate) first: bool,
}
#[derive(Copy, Clone, Debug)]
pub(crate) enum ParameterDefinitionNodeRef<'ast> {
VariadicPositionalParameter(&'ast ast::Parameter),
VariadicKeywordParameter(&'ast ast::Parameter),
Parameter(&'ast ast::ParameterWithDefault),
}
impl ParameterDefinitionNodeRef<'_> {
fn into_owned(self, parsed: &ParsedModuleRef) -> ParameterDefinitionNodeKind {
match self {
Self::VariadicPositionalParameter(parameter) => {
ParameterDefinitionNodeKind::VariadicPositionalParameter(AstNodeRef::new(
parsed, parameter,
))
}
Self::VariadicKeywordParameter(parameter) => {
ParameterDefinitionNodeKind::VariadicKeywordParameter(AstNodeRef::new(
parsed, parameter,
))
}
Self::Parameter(parameter) => {
ParameterDefinitionNodeKind::Parameter(AstNodeRef::new(parsed, parameter))
}
}
}
fn key(self) -> DefinitionNodeKey {
match self {
Self::VariadicPositionalParameter(node) => node.into(),
Self::VariadicKeywordParameter(node) => node.into(),
Self::Parameter(node) => (&node.parameter).into(),
}
}
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct LambdaParameterDefinitionNodeRef<'ast> {
pub(crate) index: usize,
pub(crate) parameter: ParameterDefinitionNodeRef<'ast>,
pub(crate) lambda: &'ast ast::ExprLambda,
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct MatchPatternDefinitionNodeRef<'ast, 'db> {
/// The outermost pattern node in which the identifier being defined occurs.
pub(crate) pattern: &'ast ast::Pattern,
/// The identifier being defined.
pub(crate) identifier: &'ast ast::Identifier,
/// The predicate for the complete match case containing this binding.
pub(crate) predicate: PatternPredicate<'db>,
}
impl<'db> DefinitionNodeRef<'_, 'db> {
pub(super) fn into_owned(self, parsed: &ParsedModuleRef) -> DefinitionKind<'db> {
match self {
DefinitionNodeRef::Import(ImportDefinitionNodeRef {
node,
alias_index,
is_reexported,
}) => DefinitionKind::Import(ImportDefinitionKind {
node: AstNodeRef::new(parsed, node),
alias_index: alias_index
.try_into()
.expect("import alias index should fit in u32"),
is_reexported,
}),
DefinitionNodeRef::ImportFrom(ImportFromDefinitionNodeRef {
node,
alias_index,
is_reexported,
}) => DefinitionKind::ImportFrom(ImportFromDefinitionKind {
node: AstNodeRef::new(parsed, node),
alias_index: alias_index
.try_into()
.expect("import-from alias index should fit in u32"),
is_reexported,
}),
DefinitionNodeRef::ImportFromSubmodule(ImportFromSubmoduleDefinitionNodeRef {
node,
module_index,
}) => DefinitionKind::ImportFromSubmodule(ImportFromSubmoduleDefinitionKind {
node: AstNodeRef::new(parsed, node),
module_index: module_index
.try_into()
.expect("import-from submodule index should fit in u32"),
}),
DefinitionNodeRef::ImportStar(star_import) => {
let StarImportDefinitionNodeRef { node, symbol_id } = star_import;
DefinitionKind::StarImport(StarImportDefinitionKind {
node: AstNodeRef::new(parsed, node),
symbol_id,
})
}
DefinitionNodeRef::Function(function) => {
DefinitionKind::Function(AstNodeRef::new(parsed, function))
}
DefinitionNodeRef::Class(class) => {
DefinitionKind::Class(AstNodeRef::new(parsed, class))
}
DefinitionNodeRef::TypeAlias(type_alias) => {
DefinitionKind::TypeAlias(AstNodeRef::new(parsed, type_alias))
}
DefinitionNodeRef::NamedExpression(named) => {
DefinitionKind::NamedExpression(AstNodeRef::new(parsed, named))
}
DefinitionNodeRef::Assignment(AssignmentDefinitionNodeRef {
unpack,
value,
target,
owner,
}) => DefinitionKind::Assignment(AssignmentDefinitionKind {
unpack,
value: AstNodeRef::new(parsed, value),
target: AstNodeRef::new(parsed, target),
owner,
}),
DefinitionNodeRef::AnnotatedAssignment(AnnotatedAssignmentDefinitionNodeRef {
node,
}) => DefinitionKind::AnnotatedAssignment(AnnotatedAssignmentDefinitionKind {
node: AstNodeRef::new(parsed, node),
has_value: node.value.is_some(),
}),
DefinitionNodeRef::AugmentedAssignment(augmented_assignment) => {
DefinitionKind::AugmentedAssignment(AstNodeRef::new(parsed, augmented_assignment))
}
DefinitionNodeRef::DictKeyAssignment(DictKeyAssignmentNodeRef {
key,
value,
assignment,
}) => DefinitionKind::DictKeyAssignment(DictKeyAssignmentKind {
key: AstNodeRef::new(parsed, key),
value: AstNodeRef::new(parsed, value),
assignment,
}),
DefinitionNodeRef::For(ForStmtDefinitionNodeRef {
unpack,
node,
target,
}) => DefinitionKind::For(ForStmtDefinitionKind {
unpack: unpack.map(|(_, unpack)| unpack),
unpack_position: unpack.map_or(UnpackPosition::First, |(position, _)| position),
node: AstNodeRef::new(parsed, node),
target: AstNodeRef::new(parsed, target),
is_async: node.is_async,
}),
DefinitionNodeRef::Comprehension(ComprehensionDefinitionNodeRef {
unpack,
node,
target,
first,
}) => DefinitionKind::Comprehension(ComprehensionDefinitionKind {
unpack: unpack.map(|(_, unpack)| unpack),
unpack_position: unpack.map_or(UnpackPosition::First, |(position, _)| position),
node: AstNodeRef::new(parsed, node),
target: AstNodeRef::new(parsed, target),
first,
is_async: node.is_async,
}),
DefinitionNodeRef::Parameter(parameter) => {
DefinitionKind::Parameter(parameter.into_owned(parsed))
}
DefinitionNodeRef::LambdaParameter(LambdaParameterDefinitionNodeRef {
index,
parameter,
lambda,
}) => DefinitionKind::LambdaParameter(LambdaParameterDefinitionNodeKind {
index: index
.try_into()
.expect("lambda parameter index should fit in u32"),
parameter: parameter.into_owned(parsed),
lambda: AstNodeRef::new(parsed, lambda),
}),
DefinitionNodeRef::WithItem(WithItemDefinitionNodeRef {
unpack,
item,
target,
is_async,
}) => DefinitionKind::WithItem(WithItemDefinitionKind {
unpack: unpack.map(|(_, unpack)| unpack),
unpack_position: unpack.map_or(UnpackPosition::First, |(position, _)| position),
item: AstNodeRef::new(parsed, item),
target: AstNodeRef::new(parsed, target),
is_async,
}),
DefinitionNodeRef::MatchPattern(MatchPatternDefinitionNodeRef {
pattern,
identifier,
predicate,
}) => DefinitionKind::MatchPattern(MatchPatternDefinitionKind {
pattern: AstNodeRef::new(parsed, pattern),
identifier: AstNodeRef::new(parsed, identifier),
predicate,
}),
DefinitionNodeRef::ExceptHandler(ExceptHandlerDefinitionNodeRef {
handler,
is_star,
}) => DefinitionKind::ExceptHandler(ExceptHandlerDefinitionKind {
handler: AstNodeRef::new(parsed, handler),
is_star,
}),
DefinitionNodeRef::TypeVar(node) => {
DefinitionKind::TypeVar(AstNodeRef::new(parsed, node))
}
DefinitionNodeRef::ParamSpec(node) => {
DefinitionKind::ParamSpec(AstNodeRef::new(parsed, node))
}
DefinitionNodeRef::TypeVarTuple(node) => {
DefinitionKind::TypeVarTuple(AstNodeRef::new(parsed, node))
}
DefinitionNodeRef::LoopHeader(LoopHeaderDefinitionNodeRef {
loop_stmt,
place,
loop_header_id,
}) => DefinitionKind::LoopHeader(LoopHeaderDefinitionKind {
loop_header_id,
loop_stmt: match loop_stmt {
LoopStmtRef::While(stmt) => LoopStmtKind::While(AstNodeRef::new(parsed, stmt)),
LoopStmtRef::For(stmt) => LoopStmtKind::For(AstNodeRef::new(parsed, stmt)),
},
place,
}),
}
}
pub(super) fn key(self) -> DefinitionNodeKey {
match self {
Self::Import(ImportDefinitionNodeRef {
node,
alias_index,
is_reexported: _,
}) => (&node.names[alias_index]).into(),
Self::ImportFrom(ImportFromDefinitionNodeRef {
node,
alias_index,
is_reexported: _,
}) => (&node.names[alias_index]).into(),
Self::ImportFromSubmodule(ImportFromSubmoduleDefinitionNodeRef { node, .. }) => {
node.into()
}
// INVARIANT: for an invalid-syntax statement such as `from foo import *, bar, *`,
// we only create a `StarImportDefinitionKind` for the *first* `*` alias in the names list.
Self::ImportStar(StarImportDefinitionNodeRef { node, symbol_id: _ }) => node
.names
.iter()
.find(|alias| &alias.name == "*")
.expect(
"The `StmtImportFrom` node of a `StarImportDefinitionKind` instance \
should always have at least one `alias` with the name `*`.",
)
.into(),
Self::Function(node) => node.into(),
Self::Class(node) => node.into(),
Self::TypeAlias(node) => node.into(),
Self::NamedExpression(node) => node.into(),
Self::Assignment(AssignmentDefinitionNodeRef {
value: _,
unpack: _,
target,
owner: _,
}) => DefinitionNodeKey(NodeKey::from_node(target)),
Self::AnnotatedAssignment(ann_assign) => ann_assign.node.into(),
Self::AugmentedAssignment(node) => node.into(),
Self::DictKeyAssignment(node) => DefinitionNodeKey(NodeKey::from_node(node.key)),
Self::For(ForStmtDefinitionNodeRef {
target,
node: _,
unpack: _,
}) => DefinitionNodeKey(NodeKey::from_node(target)),
Self::Comprehension(ComprehensionDefinitionNodeRef { target, .. }) => {
DefinitionNodeKey(NodeKey::from_node(target))
}
Self::LambdaParameter(LambdaParameterDefinitionNodeRef { parameter, .. }) => {
parameter.key()
}
Self::Parameter(parameter) => parameter.key(),
Self::WithItem(WithItemDefinitionNodeRef {
item: _,
unpack: _,
is_async: _,
target,
}) => DefinitionNodeKey(NodeKey::from_node(target)),
Self::MatchPattern(MatchPatternDefinitionNodeRef { identifier, .. }) => {
identifier.into()
}
Self::ExceptHandler(ExceptHandlerDefinitionNodeRef { handler, .. }) => handler.into(),
Self::TypeVar(node) => node.into(),
Self::ParamSpec(node) => node.into(),
Self::TypeVarTuple(node) => node.into(),
Self::LoopHeader(LoopHeaderDefinitionNodeRef { loop_stmt, .. }) => match loop_stmt {
LoopStmtRef::While(stmt) => stmt.into(),
LoopStmtRef::For(stmt) => stmt.into(),
},
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum DefinitionCategory {
/// A Definition which binds a value to a name (e.g. `x = 1`).
Binding,
/// A Definition which declares the upper-bound of acceptable types for this name (`x: int`).
Declaration,
/// A Definition which both declares a type and binds a value (e.g. `x: int = 1`).
DeclarationAndBinding,
}
impl DefinitionCategory {
/// True if this definition establishes a "declared type" for the place.
///
/// If so, any assignments reached by this definition are in error if they assign a value of a
/// type not assignable to the declared type.
///
/// Annotations establish a declared type. So do function and class definitions, and imports.
pub fn is_declaration(self) -> bool {
matches!(
self,
DefinitionCategory::Declaration | DefinitionCategory::DeclarationAndBinding
)
}
/// True if this definition assigns a value to the place.
///
/// False only for annotated assignments without a RHS.
pub fn is_binding(self) -> bool {
matches!(
self,
DefinitionCategory::Binding | DefinitionCategory::DeclarationAndBinding
)
}
}
/// The kind of a definition.
///
/// ## Usage in salsa tracked structs
///
/// [`DefinitionKind`] fields in salsa tracked structs should be tracked (attributed with `#[tracked]`)
/// because the kind is a thin wrapper around [`AstNodeRef`]. See the [`AstNodeRef`] documentation
/// for an in-depth explanation of why this is necessary.
#[derive(Clone, Debug, get_size2::GetSize, salsa::SalsaValue)]
pub enum DefinitionKind<'db> {
Import(ImportDefinitionKind),
ImportFrom(ImportFromDefinitionKind),
ImportFromSubmodule(ImportFromSubmoduleDefinitionKind),
StarImport(StarImportDefinitionKind),
Function(AstNodeRef<ast::StmtFunctionDef>),
Class(AstNodeRef<ast::StmtClassDef>),
TypeAlias(AstNodeRef<ast::StmtTypeAlias>),
NamedExpression(AstNodeRef<ast::ExprNamed>),
Assignment(AssignmentDefinitionKind<'db>),
AnnotatedAssignment(AnnotatedAssignmentDefinitionKind),
AugmentedAssignment(AstNodeRef<ast::StmtAugAssign>),
DictKeyAssignment(DictKeyAssignmentKind<'db>),
For(ForStmtDefinitionKind<'db>),
Comprehension(ComprehensionDefinitionKind<'db>),
Parameter(ParameterDefinitionNodeKind),
LambdaParameter(LambdaParameterDefinitionNodeKind),
WithItem(WithItemDefinitionKind<'db>),
MatchPattern(MatchPatternDefinitionKind<'db>),
ExceptHandler(ExceptHandlerDefinitionKind),
TypeVar(AstNodeRef<ast::TypeParamTypeVar>),
ParamSpec(AstNodeRef<ast::TypeParamParamSpec>),
TypeVarTuple(AstNodeRef<ast::TypeParamTypeVarTuple>),
LoopHeader(LoopHeaderDefinitionKind),
// Boxing here helps avoid growing the memory footprint of this enum.
NestedBindings(Box<NestedBindingsDefinitionKind>),
}
impl<'db> DefinitionKind<'db> {
pub(crate) fn is_reexported(&self) -> bool {
match self {
DefinitionKind::Import(import) => import.is_reexported(),
DefinitionKind::ImportFrom(import) => import.is_reexported(),
DefinitionKind::ImportFromSubmodule(_) => true,
_ => true,
}
}
pub const fn as_star_import(&self) -> Option<&StarImportDefinitionKind> {
match self {
DefinitionKind::StarImport(import) => Some(import),
_ => None,
}
}
pub const fn as_class(&self) -> Option<&AstNodeRef<ast::StmtClassDef>> {
match self {
DefinitionKind::Class(class) => Some(class),
_ => None,
}
}
pub fn is_import(&self) -> bool {
matches!(
self,
DefinitionKind::Import(_)
| DefinitionKind::ImportFrom(_)
| DefinitionKind::StarImport(_)
| DefinitionKind::ImportFromSubmodule(_)
)
}
pub const fn is_unannotated_assignment(&self) -> bool {
matches!(self, DefinitionKind::Assignment(_))
}
pub(crate) fn as_unannotated_assignment(&self) -> Option<AssignmentDefinitionKind<'db>> {
match self {
DefinitionKind::Assignment(assignment) => Some(assignment.clone()),
_ => None,
}
}