Repository navigation
Expand file tree
/
Copy pathbuilder.rs
More file actions
6296 lines (5709 loc) · 271 KB
/
Copy pathbuilder.rs
File metadata and controls
6296 lines (5709 loc) · 271 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::hash::BuildHasher;
use std::sync::Arc;
use except_handlers::{ExceptionContextStackManager, ExceptionHandlers};
use itertools::Itertools;
use ruff_python_ast::helpers::{Truthiness, any_over_expr, is_dotted_name};
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
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, HasNodeIndex, NodeIndex, PySourceType, PythonVersion,
};
use ruff_python_parser::semantic_errors::{
LazyImportContext, SemanticSyntaxChecker, SemanticSyntaxContext, SemanticSyntaxError,
SemanticSyntaxErrorKind, YieldOutsideFunctionKind,
};
use ruff_text_size::{Ranged, TextRange};
use smallvec::SmallVec;
use ty_module_resolver::{
ImportingFile, ModuleName, ResolverEnvironment, resolve_module_for_import_from,
};
use crate::HasTrackedScope;
use crate::ProgramFile;
use crate::ast_ids::node_key::ExpressionNodeKey;
use crate::ast_ids::{AstIdsBuilder, ScopedUseId};
use crate::ast_node_ref::AstNodeRef;
use crate::definition::{
AnnotatedAssignmentDefinitionNodeRef, AssignmentDefinitionNodeRef, BindingsOwner,
ComprehensionDefinitionNodeRef, Definition, DefinitionCategory, DefinitionKind,
DefinitionNodeKey, DefinitionNodeRef, Definitions, DictKeyAssignmentNodeRef,
ExceptHandlerDefinitionNodeRef, ForStmtDefinitionNodeRef, ImportDefinitionNodeRef,
ImportFromDefinitionNodeRef, ImportFromSubmoduleDefinitionNodeRef,
LambdaParameterDefinitionNodeRef, LoopHeaderDefinitionNodeRef, LoopStmtRef,
MatchPatternDefinitionNodeRef, NestedBindingExecution, NestedBindingsDefinitionKind,
ParameterDefinitionNodeRef, StarImportDefinitionNodeRef, WithItemDefinitionNodeRef,
};
use crate::expression::{Expression, ExpressionContext, ExpressionKind};
use crate::frozen::{FrozenMap, FrozenSet};
use crate::member::MemberExprBuilder;
use crate::place::{
PlaceExpr, PlaceTable, PlaceTableBuilder, PossiblyNarrowedPlacesBuilder, ScopedPlaceId,
match_subject_place_expressions,
};
use crate::predicate::{
CallableAndCallExpr, ClassPatternKeywordPredicateKind, ClassPatternPredicateKind,
MappingPatternEntryPredicateKind, MappingPatternPredicateKind, PatternPredicate,
PatternPredicateKind, Predicate, PredicateNode, PredicateOrLiteral, ScopedPredicateId,
SequencePatternPredicateKind, StarImportPlaceholderPredicate, StatementCall,
SubjectElementPatternPredicate,
};
use crate::re_exports::exported_names;
use crate::reachability_constraints::{
ReachabilityConstraintsBuilder, ScopedReachabilityConstraintId,
};
use crate::scope::{
FileScopeId, NodeWithScopeKey, NodeWithScopeKind, NodeWithScopeRef, Scope, ScopeId, ScopeKind,
ScopeLaziness,
};
use crate::statement::StatementInner;
use crate::symbol::{ScopedSymbolId, Symbol};
use crate::unpack::{Unpack, UnpackKind, UnpackPosition, UnpackValue};
use crate::use_def::{
EnclosingSnapshotKey, FlowSnapshot, FutureDefinitions, ImportedQualifierAction, LiveBinding,
LiveBindingStatus, PreviousDefinitions, ScopedDefinitionId, ScopedEnclosingSnapshotId,
UseDefMapBuilder, UseDefMapInterner,
};
use crate::{Db, Statement, StatementNodeKey};
use crate::{
DefinitionsByNode, EvaluationMode, ExpressionsScopeMap, LoopHeader, LoopHeaderId,
NarrowingAliasPredicate, PossiblyNarrowedPlaces, SemanticIndex, VisibleAncestorsIter,
};
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>,
}
/// A narrowing alias: a variable whose RHS is a narrowing expression
/// (e.g., `is_none = x is None`).
#[derive(Clone, Debug)]
struct NarrowingAlias<'ast> {
/// The RHS expression (e.g., `x is None`).
expression: &'ast ast::Expr,
/// The scope whose place table should be used to resolve the aliased expression.
expression_scope: FileScopeId,
/// Places that, if reassigned, should invalidate this alias.
narrowed_places: PossiblyNarrowedPlaces,
}
struct ScopeInfo<'ast> {
file_scope_id: FileScopeId,
/// Current loop state; None if we are not currently visiting a loop
current_loop: Option<Loop>,
/// Saved narrowing aliases from the enclosing scope, restored on `pop_scope`.
narrowing_aliases: FxHashMap<Name, NarrowingAlias<'ast>>,
/// `global` and `nonlocal` declarations from scopes nested under this one. This is used for:
///
/// 1. Visibility of nested writes. A nested function that binds a variable might affect the
/// inferred type of that variable in an outer scope. After each nested scope is closed, we
/// install synthetic definitions to refer to visible nested writes, which we read from this
/// map. (Note that *which kind* of nested writes is visible isn't necessarily known at that
/// point; we stash both kinds and decide which one to use at inference time.)
/// 2. Semantic syntax errors for invalid `nonlocal` declarations. A `nonlocal` declaration is
/// required to resolve to a local variable, and that variable must not be declared `global`
/// or defined in the global scope. (This is why we track all `nonlocal` declarations, even
/// if there's no binding in their scope.)
///
/// When we're trying to figure out what scope a `nonlocal` declaration resolves to, we have to
/// remember that the definition of a local variable can come after a nested function that
/// mentions it. Similarly, when we're trying to figure out whether `global` bindings from a
/// nested scopes are visible in the current scope, we have to remember that a `global`
/// declaration can also come after nested function definitions. We build up these maps as we
/// encounter each `global` and `nonlocal` keyword, but we generally need to wait until scopes
/// are popped (or later, at inference time) to analyze them.
nested_global_or_nonlocal_declarations: NestedGlobalOrNonlocalDeclarations,
/// Text ranges for `global` and `nonlocal` declarations in this scope, which we use to
/// populate `nested_global_or_nonlocal_declarations` when we reach end of scope.
this_scope_global_or_nonlocal_declarations: FxHashMap<Name, TextRange>,
/// Free symbol uses from nested scopes that may resolve to this scope.
pending_captures: PendingCaptures,
}
type NestedGlobalOrNonlocalDeclarations = FxHashMap<Name, SmallVec<[NestedDeclaration; 1]>>;
/// Captures cannot be resolved until the enclosing scope is complete because a later binding can
/// make the name local. For example, `inner` captures `outer`'s local `value`, even though the
/// binding appears after `inner` is defined:
///
/// ```python
/// def outer():
/// def inner():
/// return value
///
/// value = 1
/// ```
///
/// Each pending capture remembers the bindings visible when the nested scope was created and, for
/// lazy scopes, any bindings added afterward.
type PendingCaptures = FxHashMap<Name, SmallVec<[PendingCapture; 1]>>;
#[derive(Debug)]
struct PendingCapture {
nested_scope: FileScopeId,
laziness: ScopeLaziness,
binding_definition_ids: SmallVec<[ScopedDefinitionId; 2]>,
}
#[derive(Debug)]
struct UnresolvedCapture {
/// The scope containing the free symbol use. Retaining this lets final resolution apply class
/// scope visibility rules correctly as the capture is propagated outward.
nested_scope: FileScopeId,
name: Name,
laziness: ScopeLaziness,
}
impl UnresolvedCapture {
fn through_scope(mut self, scope_laziness: ScopeLaziness) -> Self {
if scope_laziness.is_lazy() {
self.laziness = ScopeLaziness::Lazy;
}
self
}
}
#[derive(Copy, Clone, Debug, get_size2::GetSize)]
pub struct NestedDeclaration {
pub kind: GlobalOrNonlocal,
pub file_scope_id: FileScopeId,
pub range: TextRange,
pub is_bound: bool,
}
impl NestedDeclaration {
pub fn is_global(&self) -> bool {
matches!(self.kind, GlobalOrNonlocal::Global)
}
}
#[derive(Copy, Clone, Debug, get_size2::GetSize)]
pub enum GlobalOrNonlocal {
Global,
Nonlocal,
}
struct ConditionFlowSnapshots {
truthy: FlowSnapshot,
falsy: FlowSnapshot,
}
impl ConditionFlowSnapshots {
fn into_short_circuit_and_continuation(self, op: ast::BoolOp) -> (FlowSnapshot, FlowSnapshot) {
match op {
ast::BoolOp::And => (self.falsy, self.truthy),
ast::BoolOp::Or => (self.truthy, self.falsy),
}
}
}
enum ConditionFlowSnapshot {
Fallback,
Branches(ConditionFlowSnapshots),
}
impl ConditionFlowSnapshot {
fn into_truthy(self) -> Option<FlowSnapshot> {
match self {
Self::Fallback => None,
Self::Branches(snapshots) => Some(snapshots.truthy),
}
}
fn into_branches(self) -> Option<ConditionFlowSnapshots> {
match self {
Self::Fallback => None,
Self::Branches(snapshots) => Some(snapshots),
}
}
}
pub(super) struct SemanticIndexBuilder<'db, 'ast> {
// Builder state
db: &'db dyn Db,
file: ProgramFile<'db>,
source_type: PySourceType,
module: &'ast ParsedModuleRef,
scope_stack: Vec<ScopeInfo<'ast>>,
/// The assignments we're currently visiting, with
/// the most recent visit at the end of the Vec.
current_assignments: Vec<CurrentAssignment<'ast, 'db>>,
/// The statements we're currently visiting, with
/// the most recent visit at the end of the Vec.
current_statements: Vec<CurrentStatement<'ast, 'db>>,
/// The match case we're currently visiting.
current_match_case: Option<CurrentMatchCase<'ast, 'db>>,
/// The name of the first function parameter of the innermost function that we're currently visiting.
current_first_parameter_name: Option<&'ast str>,
/// The scope of a boolean test whose subexpressions we are currently visiting.
///
/// See [`Self::visit_boolean_test`] for details on how this field is used.
active_boolean_test_scope: Option<FileScopeId>,
/// Per-scope exception contexts for nested `try` and `with` statements.
exception_context_stack_manager: ExceptionContextStackManager,
/// 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
resolver_environment: ResolverEnvironment<'db>,
python_version: PythonVersion,
source_text: OnceCell<SourceText>,
semantic_checker: SemanticSyntaxChecker,
/// Whether the current statement is inside a `try` statement, including its `except`, `else`,
/// and `finally` suites. Used for semantic syntax checks independently of handler activity.
in_try_statement: 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>,
// Box to avoid copying large builders when this index grows.
use_def_maps: IndexVec<FileScopeId, Box<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>>,
unpacks_by_target: FxHashMap<ExpressionNodeKey, Unpack<'db>>,
condition_flow_snapshots_by_node: FxHashMap<ExpressionNodeKey, ConditionFlowSnapshots>,
statements_by_node: FxHashMap<StatementNodeKey, Statement<'db>>,
imported_modules: FxHashSet<ModuleName>,
seen_submodule_imports: FxHashSet<String>,
// A map from a lambda expression to its enclosing statement.
enclosing_lambda_statements: FxHashMap<ExpressionNodeKey, Statement<'db>>,
// A map from a constraining use of a collection initializer to its definition.
collections_by_use: FxHashMap<ExpressionNodeKey, Definition<'db>>,
// A map from a collection initializer definition to statements containing a constraining use.
uses_by_collection: FxHashMap<Definition<'db>, Vec<(Statement<'db>, ExpressionNodeKey)>>,
/// 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>,
/// Hashset of all [`FileScopeId`]s that correspond to asynchronous comprehensions.
async_comprehensions: FxHashSet<FileScopeId>,
/// Node indices of syntactic annotation roots.
annotations: Vec<NodeIndex>,
/// 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>>,
/// Maps alias variable names to their narrowing expressions (same-scope only).
/// TODO: cross-scope alias narrowing support
narrowing_aliases: FxHashMap<Name, NarrowingAlias<'ast>>,
/// Alias metadata for predicate leaf names in the current file.
alias_predicates: FxHashMap<ExpressionNodeKey, NarrowingAliasPredicate<'db>>,
}
impl<'db, 'ast> SemanticIndexBuilder<'db, 'ast> {
pub(super) fn new(
db: &'db dyn Db,
file: ProgramFile<'db>,
module_ref: &'ast ParsedModuleRef,
) -> Self {
let mut builder = Self {
db,
file,
source_type: file.file(db).source_type(db),
module: module_ref,
scope_stack: Vec::new(),
current_assignments: Vec::new(),
current_statements: Vec::new(),
current_match_case: None,
current_first_parameter_name: None,
active_boolean_test_scope: None,
exception_context_stack_manager: ExceptionContextStackManager::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(),
unpacks_by_target: FxHashMap::default(),
condition_flow_snapshots_by_node: FxHashMap::default(),
statements_by_node: FxHashMap::default(),
enclosing_lambda_statements: FxHashMap::default(),
collections_by_use: FxHashMap::default(),
uses_by_collection: FxHashMap::default(),
seen_submodule_imports: FxHashSet::default(),
imported_modules: FxHashSet::default(),
generator_functions: FxHashSet::default(),
async_comprehensions: FxHashSet::default(),
annotations: Vec::new(),
enclosing_snapshots: FxHashMap::default(),
resolver_environment: file.resolver_environment(db),
python_version: file.python_version(db),
source_text: OnceCell::new(),
semantic_checker: SemanticSyntaxChecker::default(),
in_try_statement: false,
semantic_syntax_errors: RefCell::default(),
narrowing_aliases: FxHashMap::default(),
alias_predicates: FxHashMap::default(),
};
builder.push_scope_with_parent(NodeWithScopeRef::Module, None);
builder
}
fn current_scope_info(&self) -> &ScopeInfo<'ast> {
self.scope_stack
.last()
.expect("SemanticIndexBuilder should have created a root scope")
}
fn current_scope_info_mut(&mut self) -> &mut ScopeInfo<'ast> {
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
}
fn current_scope_id(&self) -> ScopeId<'db> {
self.scope_ids_by_scope[self.current_scope()]
}
fn mark_current_comprehension_async(&mut self) {
let scope = self.current_scope();
if self.scopes[scope].kind() == ScopeKind::Comprehension {
self.async_comprehensions.insert(scope);
}
}
fn expect_single_definition(
&self,
definition_key: impl Into<DefinitionNodeKey> + std::fmt::Debug + Copy,
) -> Definition<'db> {
let definitions = &self.definitions_by_node[&definition_key.into()];
debug_assert_eq!(
definitions.len(),
1,
"Expected exactly one definition to be associated with AST node {definition_key:?} but found {}",
definitions.len()
);
definitions[0]
}
/// 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
}
/// 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) {
self.push_scope_with_parent(node, Some(self.current_scope()));
}
fn push_scope_with_parent(&mut self, node: NodeWithScopeRef, parent: Option<FileScopeId>) {
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);
let scope_kind = scope.kind();
self.exception_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(Box::new(UseDefMapBuilder::new(scope_kind)));
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);
// Save narrowing aliases. They will be restored with `pop_scope` after returning from inspecting the inner scope.
// TODO: Cross-scope alias narrowing is not supported yet.
let saved_aliases = std::mem::take(&mut self.narrowing_aliases);
self.scope_stack.push(ScopeInfo {
file_scope_id,
current_loop: None,
narrowing_aliases: saved_aliases,
nested_global_or_nonlocal_declarations: FxHashMap::default(),
this_scope_global_or_nonlocal_declarations: FxHashMap::default(),
pending_captures: FxHashMap::default(),
});
}
// 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)
})
}
fn register_pending_capture(&mut self, capture: UnresolvedCapture) {
let current_scope = self.current_scope();
let binding_definition_ids = self.place_tables[current_scope]
.symbol_id(&capture.name)
.into_iter()
.flat_map(|symbol| {
self.use_def_maps[current_scope].symbol_binding_definition_ids(symbol)
})
.collect();
let captures = self
.current_scope_info_mut()
.pending_captures
.entry(capture.name)
.or_default();
if let Some(pending) = captures
.iter_mut()
.find(|pending| pending.nested_scope == capture.nested_scope)
{
pending
.binding_definition_ids
.extend(binding_definition_ids);
if capture.laziness.is_lazy() {
pending.laziness = ScopeLaziness::Lazy;
}
} else {
captures.push(PendingCapture {
nested_scope: capture.nested_scope,
laziness: capture.laziness,
binding_definition_ids,
});
}
}
fn record_pending_capture_binding(
&mut self,
symbol: ScopedSymbolId,
definition_id: ScopedDefinitionId,
) {
let current_scope = self.current_scope();
let name = self.place_tables[current_scope]
.symbol(symbol)
.name()
.clone();
let Some(captures) = self
.current_scope_info_mut()
.pending_captures
.get_mut(&name)
else {
return;
};
for capture in captures {
if capture.laziness.is_lazy() {
capture.binding_definition_ids.push(definition_id);
}
}
}
fn finish_pending_captures(
&mut self,
popped_scope_id: FileScopeId,
popped_scope_laziness: ScopeLaziness,
pending_captures: PendingCaptures,
) -> Vec<UnresolvedCapture> {
let mut unresolved = Vec::new();
#[expect(
clippy::iter_over_hash_type,
reason = "capture resolution and usage marking are order-independent"
)]
for (name, captures) in pending_captures {
for capture in captures {
if self.resolve_nested_reference_scope(capture.nested_scope, &name)
== Some(popped_scope_id)
{
self.use_def_maps[popped_scope_id]
.mark_binding_definitions_used(capture.binding_definition_ids);
} else {
unresolved.push(
UnresolvedCapture {
nested_scope: capture.nested_scope,
name: name.clone(),
laziness: capture.laziness,
}
.through_scope(popped_scope_laziness),
);
}
}
}
for symbol in self.place_tables[popped_scope_id].symbols() {
if symbol.is_used() && !symbol.is_local() && !symbol.is_global() {
unresolved.push(UnresolvedCapture {
nested_scope: popped_scope_id,
name: symbol.name().clone(),
laziness: popped_scope_laziness,
});
}
}
unresolved
}
// 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, symbol: ScopedSymbolId) {
let current_scope = self.current_scope();
let current_place_table = &self.place_tables[current_scope];
let symbol = current_place_table.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;
}
#[expect(
clippy::iter_over_hash_type,
reason = "each matching snapshot is updated independently"
)]
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 == current_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) {
if self.enclosing_snapshots.is_empty() {
return;
}
// Only the last scope containing a bound nonlocal matters: a lazy snapshot must be
// discarded if such a scope occurs at or after its enclosing scope. Build this index once
// instead of searching all later scopes separately for every snapshot.
let mut last_nonlocal_binding = FxHashMap::default();
for (scope_id, place_table) in self.place_tables.iter_enumerated() {
for symbol in place_table.symbols() {
if symbol.is_nonlocal() && symbol.is_bound() {
last_nonlocal_binding.insert(symbol.name(), scope_id);
}
}
}
if last_nonlocal_binding.is_empty() {
return;
}
self.enclosing_snapshots.retain(|key, _| {
if key.nested_laziness.is_eager() {
return true;
}
let ScopedPlaceId::Symbol(symbol_id) = key.enclosing_place else {
return true;
};
let name = self.place_tables[key.enclosing_scope]
.symbol(symbol_id)
.name();
last_nonlocal_binding
.get(name)
.is_none_or(|scope| scope.index() < key.enclosing_scope.index())
});
}
/// 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)
})
}
/// Returns the `NestedGlobalOrNonlocalDeclarations` that are still visible to the enclosing
/// scope, including those contributed by `global` and `nonlocal` keywords in the popped scope,
/// but excluding nested `nonlocal`s that resolved to the popped scope.
fn pop_scope(&mut self) -> NestedGlobalOrNonlocalDeclarations {
self.exception_context_stack_manager.exit_scope();
let ScopeInfo {
file_scope_id: popped_scope_id,
narrowing_aliases,
mut nested_global_or_nonlocal_declarations,
this_scope_global_or_nonlocal_declarations,
pending_captures,
..
} = self
.scope_stack
.pop()
.expect("Root scope should be present");
self.narrowing_aliases = narrowing_aliases;
let children_end = self.scopes.next_index();
let popped_scope = &mut self.scopes[popped_scope_id];
popped_scope.extend_descendants(children_end);
let popped_scope_kind = popped_scope.kind();
let popped_scope_laziness = popped_scope.kind().laziness();
if popped_scope_laziness.is_eager() {
self.record_eager_snapshots(popped_scope_id);
} else {
self.record_lazy_snapshots(popped_scope_id);
}
let unresolved_captures =
self.finish_pending_captures(popped_scope_id, popped_scope_laziness, pending_captures);
if !self.scope_stack.is_empty() {
for capture in unresolved_captures {
self.register_pending_capture(capture);
}
}
// If we've popped the module scope, there is no enclosing scope that needs our nested
// bindings. Short-circuit here and return an empty map.
if popped_scope_kind.is_module() {
debug_assert!(self.scope_stack.is_empty());
return FxHashMap::default();
}
// In the common case where we don't have any nested `global` or `nonlocal` declarations at
// all, short-circuit so that we don't walk the place table for no reason.
if nested_global_or_nonlocal_declarations.is_empty()
&& this_scope_global_or_nonlocal_declarations.is_empty()
{
return FxHashMap::default();
}
// For each symbol in the (non-module) scope we just popped:
// 1. If the popped scope is function-like (not a class body), see whether it resolves any
// `nonlocal` declarations (legally or illegally) from further nested scopes.
// 2. See whether it contributes any nested `global` or `nonlocal` declarations to the
// enclosing scope.
for symbol in self.place_tables[popped_scope_id].symbols() {
// Filter out any nested `nonlocal` declaration that resolve in the popped scope.
// Typically these resolve to a defined (bound or declared) symbol, but they can also
// resolve (illegally) to an unbound `global` declaration. Remove any resolved
// declarations from the `nested_global_or_nonlocal_declarations` map, both so that we
// don't try to resolve them again, and so that synthetic nested binding definitions we
// install in enclosing scopes don't see them. (Note that this doesn't affect any
// synthetic nested binding definitions installed in the popped scope, which have
// already recorded these declarations.)
if popped_scope_kind.is_function_like()
&& (symbol.is_local() || symbol.is_global())
&& let Some(nested_declarations) =
nested_global_or_nonlocal_declarations.get_mut(symbol.name())
{
nested_declarations.retain(|declaration| {
if matches!(declaration.kind, GlobalOrNonlocal::Nonlocal) {