-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathbuilder.rs
More file actions
3864 lines (3452 loc) · 163 KB
/
builder.rs
File metadata and controls
3864 lines (3452 loc) · 163 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::cell::{OnceCell, RefCell};
use std::sync::Arc;
use except_handlers::TryNodeContextStackManager;
use itertools::Itertools;
use ruff_python_ast::helpers::is_dotted_name;
use rustc_hash::{FxHashMap, FxHashSet};
use ruff_db::files::File;
use ruff_db::parsed::ParsedModuleRef;
use ruff_db::source::{SourceText, source_text};
use ruff_index::IndexVec;
use ruff_python_ast::name::Name;
use ruff_python_ast::visitor::{Visitor, walk_expr, walk_keyword, walk_pattern, walk_stmt};
use ruff_python_ast::{self as ast, AtomicNodeIndex, NodeIndex, PySourceType, PythonVersion};
use ruff_python_parser::semantic_errors::{
LazyImportContext, SemanticSyntaxChecker, SemanticSyntaxContext, SemanticSyntaxError,
SemanticSyntaxErrorKind, YieldOutsideFunctionKind,
};
use ruff_text_size::{Ranged, TextRange};
use ty_module_resolver::{ModuleName, resolve_module};
use crate::ast_node_ref::AstNodeRef;
use crate::semantic_index::ast_ids::AstIdsBuilder;
use crate::semantic_index::ast_ids::node_key::ExpressionNodeKey;
use crate::semantic_index::definition::{
AnnotatedAssignmentDefinitionNodeRef, AssignmentDefinitionNodeRef,
ComprehensionDefinitionNodeRef, Definition, DefinitionCategory, DefinitionNodeKey,
DefinitionNodeRef, Definitions, DictKeyAssignmentNodeRef, ExceptHandlerDefinitionNodeRef,
ForStmtDefinitionNodeRef, ImportDefinitionNodeRef, ImportFromDefinitionNodeRef,
ImportFromSubmoduleDefinitionNodeRef, LoopHeaderDefinitionNodeRef, LoopStmtRef,
MatchPatternDefinitionNodeRef, StarImportDefinitionNodeRef, WithItemDefinitionNodeRef,
};
use crate::semantic_index::expression::{Expression, ExpressionKind};
use crate::semantic_index::member::MemberExprBuilder;
use crate::semantic_index::place::{PlaceExpr, PlaceTableBuilder, ScopedPlaceId};
use crate::semantic_index::predicate::{
CallableAndCallExpr, ClassPatternKind, PatternPredicate, PatternPredicateKind, Predicate,
PredicateNode, PredicateOrLiteral, ScopedPredicateId, StarImportPlaceholderPredicate,
};
use crate::semantic_index::re_exports::exported_names;
use crate::semantic_index::reachability_constraints::{
ReachabilityConstraintsBuilder, ScopedReachabilityConstraintId,
};
use crate::semantic_index::scope::{
FileScopeId, NodeWithScopeKey, NodeWithScopeKind, NodeWithScopeRef,
};
use crate::semantic_index::scope::{Scope, ScopeId, ScopeKind, ScopeLaziness};
use crate::semantic_index::symbol::{ScopedSymbolId, Symbol};
use crate::semantic_index::use_def::{
EnclosingSnapshotKey, FlowSnapshot, PreviousDefinitions, ScopedDefinitionId,
ScopedEnclosingSnapshotId, UseDefMapBuilder,
};
use crate::semantic_index::{
ExpressionsScopeMap, LoopHeader, LoopToken, SemanticIndex, VisibleAncestorsIter,
get_loop_header,
};
use crate::semantic_model::HasTrackedScope;
use crate::types::{EvaluationMode, PossiblyNarrowedPlaces};
use crate::unpack::{Unpack, UnpackKind, UnpackPosition, UnpackValue};
use crate::{Db, Program};
use super::place::PlaceExprRef;
mod except_handlers;
mod loop_bindings_visitor;
#[derive(Clone, Debug, Default)]
struct Loop {
/// Flow states at each `break` in the current loop.
break_states: Vec<FlowSnapshot>,
/// Flow states at each `continue` in the current loop.
continue_states: Vec<FlowSnapshot>,
}
impl Loop {
fn push_break(&mut self, state: FlowSnapshot) {
self.break_states.push(state);
}
fn push_continue(&mut self, state: FlowSnapshot) {
self.continue_states.push(state);
}
}
struct ScopeInfo {
file_scope_id: FileScopeId,
/// Current loop state; None if we are not currently visiting a loop
current_loop: Option<Loop>,
}
pub(super) struct SemanticIndexBuilder<'db, 'ast> {
// Builder state
db: &'db dyn Db,
file: File,
source_type: PySourceType,
module: &'ast ParsedModuleRef,
scope_stack: Vec<ScopeInfo>,
/// The assignments we're currently visiting, with
/// the most recent visit at the end of the Vec
current_assignments: Vec<CurrentAssignment<'ast, 'db>>,
/// The match case we're currently visiting.
current_match_case: Option<CurrentMatchCase<'ast>>,
/// The name of the first function parameter of the innermost function that we're currently visiting.
current_first_parameter_name: Option<&'ast str>,
/// Per-scope contexts regarding nested `try`/`except` statements
try_node_context_stack_manager: TryNodeContextStackManager,
/// Flags about the file's global scope
has_future_annotations: bool,
/// Whether we are currently visiting an `if TYPE_CHECKING` block.
in_type_checking_block: bool,
// Used for checking semantic syntax errors
python_version: PythonVersion,
source_text: OnceCell<SourceText>,
semantic_checker: SemanticSyntaxChecker,
in_try: bool,
// Semantic Index fields
scopes: IndexVec<FileScopeId, Scope>,
scope_ids_by_scope: IndexVec<FileScopeId, ScopeId<'db>>,
place_tables: IndexVec<FileScopeId, PlaceTableBuilder>,
ast_ids: IndexVec<FileScopeId, AstIdsBuilder>,
use_def_maps: IndexVec<FileScopeId, UseDefMapBuilder<'db>>,
scopes_by_node: FxHashMap<NodeWithScopeKey, FileScopeId>,
scopes_by_expression: ExpressionsScopeMapBuilder,
definitions_by_node: FxHashMap<DefinitionNodeKey, Definitions<'db>>,
expressions_by_node: FxHashMap<ExpressionNodeKey, Expression<'db>>,
imported_modules: FxHashSet<ModuleName>,
seen_submodule_imports: FxHashSet<String>,
/// Hashset of all [`FileScopeId`]s that correspond to [generator functions].
///
/// [generator functions]: https://docs.python.org/3/glossary.html#term-generator
generator_functions: FxHashSet<FileScopeId>,
/// Snapshots of enclosing-scope place states visible from nested scopes.
enclosing_snapshots: FxHashMap<EnclosingSnapshotKey, ScopedEnclosingSnapshotId>,
/// Errors collected by the `semantic_checker`.
semantic_syntax_errors: RefCell<Vec<SemanticSyntaxError>>,
}
impl<'db, 'ast> SemanticIndexBuilder<'db, 'ast> {
pub(super) fn new(db: &'db dyn Db, file: File, module_ref: &'ast ParsedModuleRef) -> Self {
let mut builder = Self {
db,
file,
source_type: file.source_type(db),
module: module_ref,
scope_stack: Vec::new(),
current_assignments: vec![],
current_match_case: None,
current_first_parameter_name: None,
try_node_context_stack_manager: TryNodeContextStackManager::default(),
has_future_annotations: false,
in_type_checking_block: false,
scopes: IndexVec::new(),
place_tables: IndexVec::new(),
ast_ids: IndexVec::new(),
scope_ids_by_scope: IndexVec::new(),
use_def_maps: IndexVec::new(),
scopes_by_expression: ExpressionsScopeMapBuilder::new(),
scopes_by_node: FxHashMap::default(),
definitions_by_node: FxHashMap::default(),
expressions_by_node: FxHashMap::default(),
seen_submodule_imports: FxHashSet::default(),
imported_modules: FxHashSet::default(),
generator_functions: FxHashSet::default(),
enclosing_snapshots: FxHashMap::default(),
python_version: Program::get(db).python_version(db),
source_text: OnceCell::new(),
semantic_checker: SemanticSyntaxChecker::default(),
in_try: false,
semantic_syntax_errors: RefCell::default(),
};
builder.push_scope_with_parent(
NodeWithScopeRef::Module,
None,
ScopedReachabilityConstraintId::ALWAYS_TRUE,
);
builder
}
fn current_scope_info(&self) -> &ScopeInfo {
self.scope_stack
.last()
.expect("SemanticIndexBuilder should have created a root scope")
}
fn current_scope_info_mut(&mut self) -> &mut ScopeInfo {
self.scope_stack
.last_mut()
.expect("SemanticIndexBuilder should have created a root scope")
}
fn current_scope(&self) -> FileScopeId {
self.current_scope_info().file_scope_id
}
/// Returns an iterator over ancestors of `scope` that are visible for name resolution,
/// starting with `scope` itself. This follows Python's lexical scoping rules where
/// class scopes are skipped during name resolution (except for the starting scope
/// if it happens to be a class scope).
///
/// For example, in this code:
/// ```python
/// x = 1
/// class A:
/// x = 2
/// def method(self):
/// print(x) # Refers to global x=1, not class x=2
/// ```
/// The `method` function can see the global scope but not the class scope.
fn visible_ancestor_scopes(&self, scope: FileScopeId) -> VisibleAncestorsIter<'_> {
VisibleAncestorsIter::new(&self.scopes, scope)
}
/// Returns the scope ID of the current scope if the current scope
/// is a method inside a class body or an eagerly executed scope inside a method.
/// Returns `None` otherwise, e.g. if the current scope is a function body outside of a class, or if the current scope is not a
/// function body.
fn is_method_or_eagerly_executed_in_method(&self) -> Option<FileScopeId> {
let mut scopes_rev = self
.scope_stack
.iter()
.rev()
.skip_while(|scope| self.scopes[scope.file_scope_id].is_eager());
let current = scopes_rev.next()?;
if self.scopes[current.file_scope_id].kind() != ScopeKind::Function {
return None;
}
let maybe_method = current.file_scope_id;
let parent = scopes_rev.next()?;
match self.scopes[parent.file_scope_id].kind() {
ScopeKind::Class => Some(maybe_method),
ScopeKind::TypeParams => {
// If the function is generic, the parent scope is an annotation scope.
// In this case, we need to go up one level higher to find the class scope.
let grandparent = scopes_rev.next()?;
if self.scopes[grandparent.file_scope_id].kind() == ScopeKind::Class {
Some(maybe_method)
} else {
None
}
}
_ => None,
}
}
/// Checks if a symbol name is bound in any intermediate eager scopes
/// between the current scope and the specified method scope.
///
fn is_symbol_bound_in_intermediate_eager_scopes(
&self,
symbol_name: &str,
method_scope_id: FileScopeId,
) -> bool {
for scope_info in self.scope_stack.iter().rev() {
let scope_id = scope_info.file_scope_id;
if scope_id == method_scope_id {
break;
}
if let Some(symbol_id) = self.place_tables[scope_id].symbol_id(symbol_name) {
let symbol = self.place_tables[scope_id].symbol(symbol_id);
if symbol.is_bound() {
return true;
}
}
}
false
}
/// Returns the enclosing non-comprehension scope for walrus operator targets,
/// per [PEP 572]. Named expressions in comprehensions bind in the first
/// enclosing scope that is *not* a comprehension.
///
/// Returns `None` if the current scope is not a comprehension.
///
/// [PEP 572]: https://peps.python.org/pep-0572/#scope-of-the-target
fn enclosing_scope_for_walrus(&self) -> Option<(FileScopeId, usize)> {
if self.scopes[self.current_scope()].kind() != ScopeKind::Comprehension {
return None;
}
self.scope_stack
.iter()
.enumerate()
.rev()
.skip(1)
.find_map(|(index, info)| {
(self.scopes[info.file_scope_id].kind() != ScopeKind::Comprehension)
.then_some((info.file_scope_id, index))
})
}
/// Push a new loop, returning the outer loop, if any.
fn push_loop(&mut self) -> Option<Loop> {
self.current_scope_info_mut()
.current_loop
.replace(Loop::default())
}
/// Pop a loop, replacing with the previous saved outer loop, if any.
fn pop_loop(&mut self, outer_loop: Option<Loop>) -> Loop {
std::mem::replace(&mut self.current_scope_info_mut().current_loop, outer_loop)
.expect("pop_loop() should not be called without a prior push_loop()")
}
fn current_loop_mut(&mut self) -> Option<&mut Loop> {
self.current_scope_info_mut().current_loop.as_mut()
}
fn push_scope(&mut self, node: NodeWithScopeRef) {
let parent = self.current_scope();
let reachability = self.current_use_def_map().reachability;
self.push_scope_with_parent(node, Some(parent), reachability);
}
fn push_scope_with_parent(
&mut self,
node: NodeWithScopeRef,
parent: Option<FileScopeId>,
reachability: ScopedReachabilityConstraintId,
) {
let children_start = self.scopes.next_index() + 1;
// Note `node` is guaranteed to be a child of `self.module`
let node_with_kind = node.to_kind(self.module);
let scope = Scope::new(
parent,
node_with_kind,
children_start..children_start,
reachability,
self.in_type_checking_block,
);
let is_class_scope = scope.kind().is_class();
self.try_node_context_stack_manager.enter_nested_scope();
let file_scope_id = self.scopes.push(scope);
self.place_tables.push(PlaceTableBuilder::default());
self.use_def_maps
.push(UseDefMapBuilder::new(is_class_scope));
let ast_id_scope = self.ast_ids.push(AstIdsBuilder::default());
let scope_id = ScopeId::new(self.db, self.file, file_scope_id);
self.scope_ids_by_scope.push(scope_id);
let previous = self.scopes_by_node.insert(node.node_key(), file_scope_id);
debug_assert_eq!(previous, None);
debug_assert_eq!(ast_id_scope, file_scope_id);
self.scope_stack.push(ScopeInfo {
file_scope_id,
current_loop: None,
});
}
// Records snapshots of the place states visible from the current eager scope.
fn record_eager_snapshots(&mut self, popped_scope_id: FileScopeId) {
let popped_scope = &self.scopes[popped_scope_id];
let popped_scope_is_annotation_scope = popped_scope.kind().is_annotation();
// If the scope that we just popped off is an eager scope, we need to "lock" our view of
// which bindings reach each of the uses in the scope. Loop through each enclosing scope,
// looking for any that bind each place.
// TODO: Bindings in eager nested scopes also need to be recorded. For example:
// ```python
// class C:
// x: int | None = None
// c = C()
// class _:
// c.x = 1
// reveal_type(c.x) # revealed: Literal[1]
// ```
for enclosing_scope_info in self.scope_stack.iter().rev() {
let enclosing_scope_id = enclosing_scope_info.file_scope_id;
let is_immediately_enclosing_scope = popped_scope.parent() == Some(enclosing_scope_id);
let enclosing_scope_kind = self.scopes[enclosing_scope_id].kind();
let enclosing_place_table = &self.place_tables[enclosing_scope_id];
for nested_place in self.place_tables[popped_scope_id].iter() {
// Skip this place if this enclosing scope doesn't contain any bindings for it.
// Note that even if this place is bound in the popped scope,
// it may refer to the enclosing scope bindings
// so we also need to snapshot the bindings of the enclosing scope.
let Some(enclosing_place_id) = enclosing_place_table.place_id(nested_place) else {
continue;
};
let enclosing_place = enclosing_place_table.place(enclosing_place_id);
// Snapshot the state of this place that are visible at this point in this
// enclosing scope.
let key = EnclosingSnapshotKey {
enclosing_scope: enclosing_scope_id,
enclosing_place: enclosing_place_id,
nested_scope: popped_scope_id,
nested_laziness: ScopeLaziness::Eager,
};
let eager_snapshot = self.use_def_maps[enclosing_scope_id]
.snapshot_enclosing_state(
enclosing_place_id,
enclosing_scope_kind,
enclosing_place,
popped_scope_is_annotation_scope && is_immediately_enclosing_scope,
);
self.enclosing_snapshots.insert(key, eager_snapshot);
}
// Lazy scopes are "sticky": once we see a lazy scope we stop doing lookups
// eagerly, even if we would encounter another eager enclosing scope later on.
if !enclosing_scope_kind.is_eager() {
break;
}
}
}
fn bound_scope(&self, enclosing_scope: FileScopeId, symbol: &Symbol) -> Option<FileScopeId> {
self.scope_stack
.iter()
.rev()
.skip_while(|scope| scope.file_scope_id != enclosing_scope)
.find_map(|scope_info| {
let scope_id = scope_info.file_scope_id;
let place_table = &self.place_tables[scope_id];
let place_id = place_table.symbol_id(symbol.name())?;
place_table.place(place_id).is_bound().then_some(scope_id)
})
}
// Records snapshots of the place states visible from the current lazy scope.
fn record_lazy_snapshots(&mut self, popped_scope_id: FileScopeId) {
for enclosing_scope_info in self.scope_stack.iter().rev() {
let enclosing_scope_id = enclosing_scope_info.file_scope_id;
let enclosing_scope_kind = self.scopes[enclosing_scope_id].kind();
let enclosing_place_table = &self.place_tables[enclosing_scope_id];
// We don't record lazy snapshots of attributes or subscripts, because these are difficult to track as they modify.
for nested_symbol in self.place_tables[popped_scope_id].symbols() {
// For the same reason, we don't snapshot bindings owned by `global`/`nonlocal`
// forwarding declarations here; `snapshot_enclosing_state` stores only a
// constraint for those symbols. Also, if the enclosing scope allows its members to
// be modified from elsewhere, the snapshot will not be recorded.
// (In the case of class scopes, class variables can be modified from elsewhere, but this has no effect in nested scopes,
// as class variables are not visible to them)
if self.scopes[enclosing_scope_id].kind().is_module() {
continue;
}
// Skip this place if this enclosing scope doesn't contain any bindings for it.
// Note that even if this place is bound in the popped scope,
// it may refer to the enclosing scope bindings
// so we also need to snapshot the bindings of the enclosing scope.
let Some(enclosed_symbol_id) =
enclosing_place_table.symbol_id(nested_symbol.name())
else {
continue;
};
let enclosing_place = enclosing_place_table.symbol(enclosed_symbol_id);
if !enclosing_place.is_bound() {
// If the bound scope of a place can be modified from elsewhere, the snapshot will not be recorded.
if self
.bound_scope(enclosing_scope_id, nested_symbol)
.is_none_or(|scope| self.scopes[scope].visibility().is_public())
{
continue;
}
}
// Snapshot the state of this place that are visible at this point in this
// enclosing scope (this may later be invalidated and swept away).
let key = EnclosingSnapshotKey {
enclosing_scope: enclosing_scope_id,
enclosing_place: enclosed_symbol_id.into(),
nested_scope: popped_scope_id,
nested_laziness: ScopeLaziness::Lazy,
};
let lazy_snapshot = self.use_def_maps[enclosing_scope_id].snapshot_enclosing_state(
enclosed_symbol_id.into(),
enclosing_scope_kind,
enclosing_place.into(),
false,
);
self.enclosing_snapshots.insert(key, lazy_snapshot);
}
}
}
/// Any lazy snapshots of the place that have been reassigned are obsolete, so update them.
/// ```py
/// def outer() -> None:
/// x = None
///
/// def inner2() -> None:
/// # `inner` can be referenced before its definition,
/// # but `inner2` must still be called after the definition of `inner` for this call to be valid.
/// inner()
///
/// # In this scope, `x` may refer to `x = None` or `x = 1`.
/// reveal_type(x) # revealed: None | Literal[1]
///
/// # Reassignment of `x` after the definition of `inner2`.
/// # Update lazy snapshots of `x` for `inner2`.
/// x = 1
///
/// def inner() -> None:
/// # In this scope, `x = None` appears as being shadowed by `x = 1`.
/// reveal_type(x) # revealed: Literal[1]
///
/// # No reassignment of `x` after the definition of `inner`, so we can safely use a lazy snapshot for `inner` as is.
/// inner()
/// inner2()
/// ```
fn update_lazy_snapshots(&mut self, scope: FileScopeId, symbol: ScopedSymbolId) {
let symbol = self.place_tables[scope].symbol(symbol);
// Optimization: if this is the first binding of the symbol we've seen, there can't be any
// lazy snapshots of it to update.
if !symbol.is_reassigned() {
return;
}
for (key, snapshot_id) in &self.enclosing_snapshots {
if let Some(enclosing_symbol) = key.enclosing_place.as_symbol() {
let name = self.place_tables[key.enclosing_scope]
.symbol(enclosing_symbol)
.name();
let is_reassignment_of_snapshotted_symbol = || {
for (ancestor, _) in self.visible_ancestor_scopes(key.enclosing_scope) {
if ancestor == scope {
return true;
}
let ancestor_table = &self.place_tables[ancestor];
// If there is a symbol binding in an ancestor scope,
// then a reassignment in the current scope is not relevant to the snapshot.
if ancestor_table
.symbol_id(name)
.is_some_and(|id| ancestor_table.symbol(id).is_bound())
{
return false;
}
}
false
};
if key.nested_laziness.is_lazy()
&& symbol.name() == name
&& is_reassignment_of_snapshotted_symbol()
{
self.use_def_maps[key.enclosing_scope]
.update_enclosing_snapshot(*snapshot_id, enclosing_symbol);
}
}
}
}
fn sweep_nonlocal_lazy_snapshots(&mut self) {
self.enclosing_snapshots.retain(|key, _| {
let place_table = &self.place_tables[key.enclosing_scope];
let is_bound_and_non_local = || -> bool {
let ScopedPlaceId::Symbol(symbol_id) = key.enclosing_place else {
return false;
};
let symbol = place_table.symbol(symbol_id);
self.scopes
.iter_enumerated()
.skip_while(|(scope_id, _)| *scope_id != key.enclosing_scope)
.any(|(scope_id, _)| {
let other_scope_place_table = &self.place_tables[scope_id];
let Some(symbol_id) = other_scope_place_table.symbol_id(symbol.name())
else {
return false;
};
let symbol = other_scope_place_table.symbol(symbol_id);
symbol.is_nonlocal() && symbol.is_bound()
})
};
key.nested_laziness.is_eager() || !is_bound_and_non_local()
});
}
/// Finds the nearest visible ancestor scope that actually owns a local binding for `name`.
fn resolve_nested_reference_scope(
&self,
nested_scope: FileScopeId,
name: &str,
) -> Option<FileScopeId> {
self.visible_ancestor_scopes(nested_scope)
.skip(1)
.find_map(|(scope_id, _)| {
let place_table = &self.place_tables[scope_id];
let symbol_id = place_table.symbol_id(name)?;
let symbol = place_table.symbol(symbol_id);
// Only a true local binding in an ancestor scope can be the resolution target.
// `global`/`nonlocal` here are forwarding declarations, not owning bindings.
symbol.is_local().then_some(scope_id)
})
}
/// Marks bindings in enclosing scopes as used when a nested scope resolves a reference to them.
///
/// This reuses enclosing-snapshot data so lazy scopes account for later reassignments that can
/// also reach the nested reference.
fn mark_captured_bindings_used(&mut self) {
let mut resolved_scopes_by_nested_symbol =
FxHashMap::<(FileScopeId, ScopedSymbolId), Option<FileScopeId>>::default();
let mut snapshots_to_mark = Vec::new();
for (&key, &snapshot_id) in &self.enclosing_snapshots {
let ScopedPlaceId::Symbol(enclosing_symbol_id) = key.enclosing_place else {
continue;
};
let enclosing_symbol =
self.place_tables[key.enclosing_scope].symbol(enclosing_symbol_id);
let nested_place_table = &self.place_tables[key.nested_scope];
let Some(nested_symbol_id) =
nested_place_table.symbol_id(enclosing_symbol.name().as_str())
else {
continue;
};
let nested_symbol = nested_place_table.symbol(nested_symbol_id);
if !nested_symbol.is_used() || nested_symbol.is_local() || nested_symbol.is_global() {
continue;
}
let resolved_scope = *resolved_scopes_by_nested_symbol
.entry((key.nested_scope, nested_symbol_id))
.or_insert_with(|| {
self.resolve_nested_reference_scope(
key.nested_scope,
enclosing_symbol.name().as_str(),
)
});
if resolved_scope == Some(key.enclosing_scope) {
snapshots_to_mark.push((key.enclosing_scope, snapshot_id));
}
}
for (scope_id, snapshot_id) in snapshots_to_mark {
self.use_def_maps[scope_id].mark_enclosing_snapshot_bindings_used(snapshot_id);
}
}
fn pop_scope(&mut self) -> FileScopeId {
self.try_node_context_stack_manager.exit_scope();
let ScopeInfo {
file_scope_id: popped_scope_id,
..
} = self
.scope_stack
.pop()
.expect("Root scope should be present");
let children_end = self.scopes.next_index();
let popped_scope = &mut self.scopes[popped_scope_id];
popped_scope.extend_descendants(children_end);
if popped_scope.is_eager() {
self.record_eager_snapshots(popped_scope_id);
} else {
self.record_lazy_snapshots(popped_scope_id);
}
popped_scope_id
}
fn current_place_table(&self) -> &PlaceTableBuilder {
let scope_id = self.current_scope();
&self.place_tables[scope_id]
}
fn current_place_table_mut(&mut self) -> &mut PlaceTableBuilder {
let scope_id = self.current_scope();
&mut self.place_tables[scope_id]
}
fn current_use_def_map_mut(&mut self) -> &mut UseDefMapBuilder<'db> {
let scope_id = self.current_scope();
&mut self.use_def_maps[scope_id]
}
fn current_use_def_map(&self) -> &UseDefMapBuilder<'db> {
let scope_id = self.current_scope();
&self.use_def_maps[scope_id]
}
fn current_reachability_constraints_mut(&mut self) -> &mut ReachabilityConstraintsBuilder {
let scope_id = self.current_scope();
&mut self.use_def_maps[scope_id].reachability_constraints
}
fn current_ast_ids(&mut self) -> &mut AstIdsBuilder {
let scope_id = self.current_scope();
&mut self.ast_ids[scope_id]
}
fn flow_snapshot(&self) -> FlowSnapshot {
self.current_use_def_map().snapshot()
}
fn flow_restore(&mut self, state: FlowSnapshot) {
self.current_use_def_map_mut().restore(state);
}
fn flow_merge(&mut self, state: FlowSnapshot) {
self.current_use_def_map_mut().merge(state);
}
/// Add a symbol to the place table and the use-def map.
/// Return the [`ScopedPlaceId`] that uniquely identifies the symbol in both.
fn add_symbol(&mut self, name: Name) -> ScopedSymbolId {
let (symbol_id, added) = self.current_place_table_mut().add_symbol(Symbol::new(name));
if added {
self.current_use_def_map_mut().add_place(symbol_id.into());
}
symbol_id
}
/// Add a place to the place table and the use-def map.
/// Return the [`ScopedPlaceId`] that uniquely identifies the place in both.
fn add_place(&mut self, place_expr: PlaceExpr) -> ScopedPlaceId {
let (place_id, added) = self.current_place_table_mut().add_place(place_expr);
if added {
self.current_use_def_map_mut().add_place(place_id);
}
place_id
}
#[track_caller]
fn mark_place_bound(&mut self, id: ScopedPlaceId) {
self.current_place_table_mut().mark_bound(id);
}
#[track_caller]
fn mark_place_declared(&mut self, id: ScopedPlaceId) {
self.current_place_table_mut().mark_declared(id);
}
#[track_caller]
fn mark_symbol_used(&mut self, id: ScopedSymbolId) {
self.current_place_table_mut().symbol_mut(id).mark_used();
}
fn record_place_use(&mut self, place_id: ScopedPlaceId, expr: &'ast ast::Expr) {
if let ScopedPlaceId::Symbol(symbol_id) = place_id {
self.mark_symbol_used(symbol_id);
}
let use_id = self.current_ast_ids().record_use(expr);
self.current_use_def_map_mut().record_use(place_id, use_id);
}
fn record_place_definition(&mut self, place_id: ScopedPlaceId, expr: &'ast ast::Expr) {
match self.current_assignment() {
Some(CurrentAssignment::Assign { node, unpack }) => {
let assignment = self.add_definition(
place_id,
AssignmentDefinitionNodeRef {
unpack,
value: &node.value,
target: expr,
},
);
self.add_dict_key_assignment_definitions(&node.targets, &node.value, assignment);
}
Some(CurrentAssignment::AnnAssign(ann_assign)) => {
self.add_standalone_type_expression(&ann_assign.annotation);
let assignment = self.add_definition(
place_id,
AnnotatedAssignmentDefinitionNodeRef {
node: ann_assign,
annotation: &ann_assign.annotation,
value: ann_assign.value.as_deref(),
target: expr,
},
);
if let Some(value) = ann_assign.value.as_deref() {
self.add_dict_key_assignment_definitions(
[&*ann_assign.target],
value,
assignment,
);
}
}
Some(CurrentAssignment::AugAssign(aug_assign)) => {
self.add_definition(place_id, aug_assign);
}
Some(CurrentAssignment::For { node, unpack }) => {
self.add_definition(
place_id,
ForStmtDefinitionNodeRef {
unpack,
iterable: &node.iter,
target: expr,
is_async: node.is_async,
},
);
}
Some(CurrentAssignment::Named(named)) => {
if let Some((enclosing_scope, scope_index)) = self.enclosing_scope_for_walrus() {
// PEP 572: walrus in comprehension binds in enclosing scope.
let target_name = named
.target
.as_name_expr()
.expect("target should be a Name expression")
.id
.clone();
let (symbol_id, added) =
self.place_tables[enclosing_scope].add_symbol(Symbol::new(target_name));
if added {
self.use_def_maps[enclosing_scope].add_place(symbol_id.into());
}
self.push_additional_definition_in_scope(
enclosing_scope,
scope_index,
symbol_id.into(),
named,
);
} else {
self.add_definition(place_id, named);
}
}
Some(CurrentAssignment::Comprehension {
unpack,
node,
first,
}) => {
self.add_definition(
place_id,
ComprehensionDefinitionNodeRef {
unpack,
iterable: &node.iter,
target: expr,
first,
is_async: node.is_async,
},
);
}
Some(CurrentAssignment::WithItem {
item,
is_async,
unpack,
}) => {
self.add_definition(
place_id,
WithItemDefinitionNodeRef {
unpack,
context_expr: &item.context_expr,
target: expr,
is_async,
},
);
}
None => {}
}
}
fn add_entry_for_definition_key(&mut self, key: DefinitionNodeKey) -> &mut Definitions<'db> {
self.definitions_by_node.entry(key).or_default()
}
/// Add a [`Definition`] associated with the `definition_node` AST node.
///
/// ## Panics
///
/// This method panics if `debug_assertions` are enabled and the `definition_node` AST node
/// already has a [`Definition`] associated with it. This is an important invariant to maintain
/// for all nodes *except* [`ast::Alias`] nodes representing `*` imports.
fn add_definition(
&mut self,
place: ScopedPlaceId,
definition_node: impl Into<DefinitionNodeRef<'ast, 'db>> + std::fmt::Debug + Copy,
) -> Definition<'db> {
let (definition, num_definitions) = self.push_additional_definition(place, definition_node);
debug_assert_eq!(
num_definitions, 1,
"Attempted to create multiple `Definition`s associated with AST node {definition_node:?}"
);
definition
}
fn delete_associated_bindings_in_scope(&mut self, scope: FileScopeId, place: ScopedPlaceId) {
// Don't delete associated bindings if the scope is a class scope & place is a name (it's never visible to nested scopes)
if self.scopes[scope].kind() == ScopeKind::Class && place.is_symbol() {
return;
}
for associated_place in self.place_tables[scope]
.associated_place_ids(place)
.iter()
.copied()
{
self.use_def_maps[scope].delete_binding(associated_place.into());
}
}
fn delete_binding(&mut self, place: ScopedPlaceId) {
self.current_use_def_map_mut().delete_binding(place);
}
/// Create a [`Definition`] for `definition_node` in the given `scope`, recording it in
/// that scope's place table and use-def map.
///
/// Returns a 3-element tuple: the newly created [`Definition`], the total number of
/// definitions now associated with the AST node, and the [`DefinitionCategory`].
///
/// This is the low-level helper; callers that add definitions to the **current** scope
/// should normally use [`Self::push_additional_definition`] or [`Self::add_definition`],
/// which also update lazy snapshots and the try-node context stack.
fn add_definition_in_scope(
&mut self,
scope: FileScopeId,
place: ScopedPlaceId,
definition_node: impl Into<DefinitionNodeRef<'ast, 'db>>,
) -> (Definition<'db>, usize, DefinitionCategory) {
let definition_node: DefinitionNodeRef<'ast, 'db> = definition_node.into();
// Note `definition_node` is guaranteed to be a child of `self.module`
let kind = definition_node.into_owned(self.module);
let is_loop_header = kind.is_loop_header();
let category = kind.category(self.source_type.is_stub(), self.module);
let is_reexported = kind.is_reexported();
let definition: Definition<'db> =
Definition::new(self.db, self.file, scope, place, kind, is_reexported);
let num_definitions = {
let definitions = self.add_entry_for_definition_key(definition_node.key());
definitions.push(definition);
definitions.len()
};
// We need to avoid marking places as bound as soon as we encounter a loop header
// definition for them, because that would lead to false-positive semantic syntax errors in
// cases like this:
// ```py
// while True:
// global x # [invalid-syntax] if `x` is already used or bound
// x = 1
// ```
if category.is_binding() && !is_loop_header {
self.place_tables[scope].mark_bound(place);
}
if category.is_declaration() {
self.place_tables[scope].mark_declared(place);
}
match category {
DefinitionCategory::DeclarationAndBinding => {
self.use_def_maps[scope].record_declaration_and_binding(place, definition);
self.delete_associated_bindings_in_scope(scope, place);
}
DefinitionCategory::Declaration => {
self.use_def_maps[scope].record_declaration(place, definition);
}
DefinitionCategory::Binding => {
// Loop-header bindings don't shadow prior bindings.
let previous_definitions = if is_loop_header {
PreviousDefinitions::AreKept
} else {
PreviousDefinitions::AreShadowed
};
self.use_def_maps[scope].record_binding(place, definition, previous_definitions);
if !is_loop_header {
self.delete_associated_bindings_in_scope(scope, place);
}
}
}
(definition, num_definitions, category)
}
/// Push a new [`Definition`] onto the list of definitions
/// associated with the `definition_node` AST node in the **current** scope.