Repository navigation
Expand file tree
/
Copy pathuse_def.rs
More file actions
3116 lines (2823 loc) · 125 KB
/
Copy pathuse_def.rs
File metadata and controls
3116 lines (2823 loc) · 125 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
//! First, some terminology:
//!
//! * A "place" is semantically a location where a value can be read or written, and syntactically,
//! an expression that can be the target of an assignment, e.g. `x`, `x[0]`, `x.y`. (The term is
//! borrowed from Rust). In Python syntax, an expression like `f().x` is also allowed as the
//! target so it can be called a place, but we do not record declarations / bindings like `f().x:
//! int`, `f().x = ...`. Type checking itself can be done by recording only assignments to names,
//! but in order to perform type narrowing by attribute/subscript assignments, they must also be
//! recorded.
//!
//! * A "binding" gives a new value to a place. This includes many different Python statements
//! (assignment statements of course, but also imports, `def` and `class` statements, `as`
//! clauses in `with` and `except` statements, match patterns, and others) and even one
//! expression kind (named expressions). It notably does not include annotated assignment
//! statements without a right-hand side value; these do not assign any new value to the place.
//! We consider function parameters to be bindings as well, since (from the perspective of the
//! function's internal scope), a function parameter begins the scope bound to a value.
//!
//! * A "declaration" establishes an upper bound type for the values that a variable may be
//! permitted to take on. Annotated assignment statements (with or without an RHS value) are
//! declarations; annotated function parameters are also declarations. We consider `def` and
//! `class` statements to also be declarations, so as to prohibit accidentally shadowing them.
//!
//! Annotated assignments with a right-hand side, and annotated function parameters, are both
//! bindings and declarations.
//!
//! We use [`Definition`] as the universal term (and Salsa tracked struct) encompassing both
//! bindings and declarations. (This sacrifices a bit of type safety in exchange for improved
//! performance via fewer Salsa tracked structs and queries, since most declarations -- typed
//! parameters and annotated assignments with RHS -- are both bindings and declarations.)
//!
//! At any given use of a variable, we can ask about both its "declared type" and its "inferred
//! type". These may be different, but the inferred type must always be assignable to the declared
//! type; that is, the declared type is always wider, and the inferred type may be more precise. If
//! we see an invalid assignment, we emit a diagnostic and abandon our inferred type, deferring to
//! the declared type (this allows an explicit annotation to override bad inference, without a
//! cast), maintaining the invariant.
//!
//! The **inferred type** represents the most precise type we believe encompasses all possible
//! values for the variable at a given use. It is based on a union of the bindings which can reach
//! that use through some control flow path, and the narrowing constraints that control flow must
//! have passed through between the binding and the use. For example, in this code:
//!
//! ```python
//! x = 1 if flag else None
//! if x is not None:
//! use(x)
//! ```
//!
//! For the use of `x` on the third line, the inferred type should be `Literal[1]`. This is based
//! on the binding on the first line, which assigns the type `Literal[1] | None`, and the narrowing
//! constraint on the second line, which rules out the type `None`, since control flow must pass
//! through this constraint to reach the use in question.
//!
//! The **declared type** represents the code author's declaration (usually through a type
//! annotation) that a given variable should not be assigned any type outside the declared type. In
//! our model, declared types are also control-flow-sensitive; we allow the code author to
//! explicitly redeclare the same variable with a different type. So for a given binding of a
//! variable, we will want to ask which declarations of that variable can reach that binding, in
//! order to determine whether the binding is permitted, or should be a type error. For example:
//!
//! ```python
//! from pathlib import Path
//! def f(path: str):
//! path: Path = Path(path)
//! ```
//!
//! In this function, the initial declared type of `path` is `str`, meaning that the assignment
//! `path = Path(path)` would be a type error, since it assigns to `path` a value whose type is not
//! assignable to `str`. This is the purpose of declared types: they prevent accidental assignment
//! of the wrong type to a variable.
//!
//! But in some cases it is useful to "shadow" or "redeclare" a variable with a new type, and we
//! permit this, as long as it is done with an explicit re-annotation. So `path: Path =
//! Path(path)`, with the explicit `: Path` annotation, is permitted.
//!
//! The general rule is that whatever declaration(s) can reach a given binding determine the
//! validity of that binding. If there is a path in which the place is not declared, that is a
//! declaration of `Unknown`. If multiple declarations can reach a binding, we union them, but by
//! default we also issue a type error, since this implicit union of declared types may hide an
//! error.
//!
//! To support type inference, we build a map from each use of a place to the bindings live at
//! that use, and the type narrowing constraints that apply to each binding.
//!
//! Let's take this code sample:
//!
//! ```python
//! x = 1
//! x = 2
//! y = x
//! if flag:
//! x = 3
//! else:
//! x = 4
//! z = x
//! ```
//!
//! In this snippet, we have four bindings of `x` (the statements assigning `1`, `2`, `3`, and `4`
//! to it), and two uses of `x` (the `y = x` and `z = x` assignments). The first binding of `x`
//! does not reach any use, because it's immediately replaced by the second binding, before any use
//! happens. (A linter could thus flag the statement `x = 1` as likely superfluous.)
//!
//! The first use of `x` has one live binding: the assignment `x = 2`.
//!
//! Things get a bit more complex when we have branches. We will definitely take either the `if` or
//! the `else` branch. Thus, the second use of `x` has two live bindings: `x = 3` and `x = 4`. The
//! `x = 2` assignment is no longer visible, because it must be replaced by either `x = 3` or `x =
//! 4`, no matter which branch was taken. We don't know which branch was taken, so we must consider
//! both bindings as live, which means eventually we would (in type inference) look at these two
//! bindings and infer a type of `Literal[3, 4]` -- the union of `Literal[3]` and `Literal[4]` --
//! for the second use of `x`.
//!
//! So that's one question our use-def map needs to answer: given a specific use of a place, which
//! binding(s) can reach that use. In [`crate::ast_ids::AstIds`] we number
//! all uses (that means a `Name`/`ExprAttribute`/`ExprSubscript` node with `Load` context)
//! so we have a `ScopedUseId` to efficiently represent each use.
//!
//! We also need to know, for a given definition of a place, what type narrowing constraints apply
//! to it. For instance, in this code sample:
//!
//! ```python
//! x = 1 if flag else None
//! if x is not None:
//! use(x)
//! ```
//!
//! At the use of `x`, the live binding of `x` is `1 if flag else None`, which would infer as the
//! type `Literal[1] | None`. But the constraint `x is not None` dominates this use, which means we
//! can rule out the possibility that `x` is `None` here, which should give us the type
//! `Literal[1]` for this use.
//!
//! For declared types, we need to be able to answer the question "given a binding to a place,
//! which declarations of that place can reach the binding?" This allows us to emit a diagnostic
//! if the binding is attempting to bind a value of a type that is not assignable to the declared
//! type for that place, at that point in control flow.
//!
//! We also need to know, given a declaration of a place, what the inferred type of that place is
//! at that point. This allows us to emit a diagnostic in a case like `x = "foo"; x: int`. The
//! binding `x = "foo"` occurs before the declaration `x: int`, so according to our
//! control-flow-sensitive interpretation of declarations, the assignment is not an error. But the
//! declaration is an error, since it would violate the "inferred type must be assignable to
//! declared type" rule.
//!
//! Another case we need to handle is when a place is referenced from a different scope (for
//! example, an import or a nonlocal reference). We call this "public" use of a place. For public
//! use of a place, we prefer the declared type, if there are any declarations of that place; if
//! not, we fall back to the inferred type. So we also need to know which declarations and bindings
//! can reach the end of the scope.
//!
//! Technically, public use of a place could occur from any point in control flow of the scope
//! where the place is defined (via inline imports and import cycles, in the case of an import, or
//! via a function call partway through the local scope that ends up using a place from the scope
//! via a global or nonlocal reference.) But modeling this fully accurately requires whole-program
//! analysis that isn't tractable for an efficient analysis, since it means a given place could
//! have a different type every place it's referenced throughout the program, depending on the
//! shape of arbitrarily-sized call/import graphs. So we follow other Python type checkers in
//! making the simplifying assumption that usually the scope will finish execution before its
//! places are made visible to other scopes; for instance, most imports will import from a
//! complete module, not a partially-executed module. (We may want to get a little smarter than
//! this in the future for some closures, but for now this is where we start.)
//!
//! The data structure we build to answer these questions is the `UseDefMap`. It has a
//! `bindings_by_use` vector of [`InternedBindingsId`] indexed by [`ScopedUseId`]
//! (plus an interned bindings table), a
//! `definitions_by_definition` map of [`DefinitionsAtDefinition`], and `symbol_states` and
//! `member_states` vectors indexed by [`ScopedSymbolId`]/[`ScopedMemberId`]. The values are (in
//! principle) a list of live bindings at that use/definition, or at the end of the scope for that
//! place, with a list of the dominating constraints for each binding.
//!
//! In order to avoid vectors-of-vectors-of-vectors and all the allocations that would entail, we
//! don't actually store these "list of visible definitions" as a vector of [`Definition`].
//! Instead, [`Bindings`] and [`Declarations`] are structs which use bit-sets to track
//! definitions (and constraints, in the case of bindings) in terms of [`ScopedDefinitionId`] and
//! [`ScopedPredicateId`], which are indices into the `all_definitions` and `predicates`
//! indexvecs in the [`UseDefMap`].
//!
//! There is another special kind of possible "definition" for a place: there might be a path from
//! the scope entry to a given use in which the place is never bound. We model this with a special
//! "unbound/undeclared" definition at logical index zero. If that sentinel definition is present
//! in the live bindings at a given use, it means that there is a possible path through control
//! flow in which that place is unbound. Similarly, if that sentinel is present in the live
//! declarations, it means that the place is (possibly) undeclared.
//!
//! To build a [`UseDefMap`], the [`UseDefMapBuilder`] is notified of each new use, definition, and
//! constraint as they are encountered by the
//! [`crate::builder::SemanticIndexBuilder`] AST visit. For
//! each place, the builder tracks the `PlaceState` (`Bindings` and `Declarations`) for that place.
//! When we hit a use or definition of a place, we record the necessary parts of the current state
//! for that place that we need for that use or definition. When we reach the end of the scope, it
//! records the state for each place as the public definitions of that place.
//!
//! ```python
//! x = 1
//! x = 2
//! y = x
//! if flag:
//! x = 3
//! else:
//! x = 4
//! z = x
//! ```
//!
//! Let's walk through the above example. Initially we do not have any record of `x`. When we add
//! the new place (before we process the first binding), we create a new undefined `PlaceState`
//! which has a single live binding (the "unbound" definition) and a single live declaration (the
//! "undeclared" definition). When we see `x = 1`, we record that as the sole live binding of `x`.
//! The "unbound" binding is no longer visible. Then we see `x = 2`, and we replace `x = 1` as the
//! sole live binding of `x`. When we get to `y = x`, we record that the live bindings for that use
//! of `x` are just the `x = 2` definition.
//!
//! Then we hit the `if` branch. We visit the `test` node (`flag` in this case), since that will
//! happen regardless. Then we take a pre-branch snapshot of the current state for all places,
//! which we'll need later. Then we record `flag` as a possible constraint on the current binding
//! (`x = 2`), and go ahead and visit the `if` body. When we see `x = 3`, it replaces `x = 2`
//! (constrained by `flag`) as the sole live binding of `x`. At the end of the `if` body, we take
//! another snapshot of the current place state; we'll call this the post-if-body snapshot.
//!
//! Now we need to visit the `else` clause. The conditions when entering the `else` clause should
//! be the pre-if conditions; if we are entering the `else` clause, we know that the `if` test
//! failed and we didn't execute the `if` body. So we first reset the builder to the pre-if state,
//! using the snapshot we took previously (meaning we now have `x = 2` as the sole binding for `x`
//! again), and record a *negative* `flag` constraint for all live bindings (`x = 2`). We then
//! visit the `else` clause, where `x = 4` replaces `x = 2` as the sole live binding of `x`.
//!
//! Now we reach the end of the if/else, and want to visit the following code. The state here needs
//! to reflect that we might have gone through the `if` branch, or we might have gone through the
//! `else` branch, and we don't know which. So we need to "merge" our current builder state
//! (reflecting the end-of-else state, with `x = 4` as the only live binding) with our post-if-body
//! snapshot (which has `x = 3` as the only live binding). The result of this merge is that we now
//! have two live bindings of `x`: `x = 3` and `x = 4`.
//!
//! Another piece of information that the `UseDefMap` needs to provide are reachability constraints.
//! See `reachability_constraints.rs` for more details, in particular how they apply to bindings.
//!
//! The [`UseDefMapBuilder`] itself just exposes methods for taking a snapshot, resetting to a
//! snapshot, and merging a snapshot into the current state. The logic using these methods lives in
//! [`SemanticIndexBuilder`](crate::builder::SemanticIndexBuilder), e.g. where it
//! visits a `StmtIf` node.
use std::collections::hash_map::Entry;
use std::hash::{Hash as _, Hasher as _};
use std::ops::Index;
use std::rc::Rc;
use std::sync::LazyLock;
use ruff_index::{FrozenIndexVec, Idx, IndexVec, newtype_index};
use ruff_text_size::TextRange;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHasher};
use smallvec::SmallVec;
use thin_vec::ThinVec;
use crate::ast_ids::ScopedUseId;
use crate::definition::{Definition, DefinitionCategory, DefinitionState};
use crate::frozen::FrozenMap;
use crate::member::ScopedMemberId;
use crate::narrowing_constraints::{
ConstraintKey, NarrowingConstraints, NarrowingConstraintsBuilder, ScopedNarrowingConstraint,
};
use crate::place::{PlaceExprRef, ScopedPlaceId};
use crate::predicate::{PredicateOrLiteral, Predicates, PredicatesBuilder, ScopedPredicateId};
use crate::reachability_constraints::{
ReachabilityConstraints, ReachabilityConstraintsBuilder, ScopedReachabilityConstraintId,
};
use crate::scope::{FileScopeId, ScopeKind, ScopeLaziness};
use crate::symbol::ScopedSymbolId;
use crate::use_def::place_state::{
Bindings, Declarations, EnclosingSnapshot, LiveBindingsIterator, LiveDeclaration,
LiveDeclarationsIterator, PlaceState,
};
use crate::{
BoundnessAnalysis, EnclosingSnapshotResult, LoopHeader, PossiblyNarrowedPlaces, SemanticIndex,
};
mod exception_checkpoint;
mod place_state;
pub(super) use exception_checkpoint::ExceptionCheckpointKey;
use exception_checkpoint::{ExceptionCheckpointSnapshot, ExceptionCheckpointState};
pub use place_state::LiveBinding;
pub use place_state::ScopedDefinitionId;
pub(super) use place_state::{FutureDefinitions, PreviousDefinitions};
/// Summarizes whether the live control-flow paths leave a symbol bound.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(super) enum LiveBindingStatus {
/// No live path contains a binding.
Unbound,
/// Some live paths contain a binding and others leave the symbol unbound.
PossiblyBound,
/// Every live path contains a binding.
Bound,
}
/// Identifies a [`LoopHeader`] within a single scope's [`UseDefMap`].
#[newtype_index]
#[derive(get_size2::GetSize)]
pub struct LoopHeaderId;
/// Uniquely identifies an interned [`Bindings`] entry in [`UseDefMap::interned_bindings`].
#[newtype_index]
#[derive(get_size2::GetSize, salsa::SalsaValue)]
struct InternedBindingsId;
/// Uniquely identifies an interned [`Declarations`] entry in [`UseDefMap::interned_declarations`].
#[newtype_index]
#[derive(get_size2::GetSize, salsa::SalsaValue)]
struct InternedDeclarationsId;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, get_size2::GetSize)]
struct InternedPlaceStateId(InternedBindingsId, InternedDeclarationsId);
impl InternedPlaceStateId {
fn bindings_id(self) -> InternedBindingsId {
self.0
}
fn declarations_id(self) -> InternedDeclarationsId {
self.1
}
}
struct PlaceStateInterner {
interned_bindings: RetainedBindingsBuilder,
interned_ids_by_bindings: hashbrown::HashTable<InternedBindingsId>,
interned_declarations: RetainedDeclarationsBuilder,
interned_ids_by_declarations: FxHashMap<Declarations, InternedDeclarationsId>,
// Undeclared states are common and can be interned by their dense constraint IDs.
undeclared_declarations_by_constraint:
IndexVec<ScopedReachabilityConstraintId, Option<InternedDeclarationsId>>,
// These values are extremely common, so avoid repeatedly hashing their small vectors.
always_unbound_bindings: Option<InternedBindingsId>,
always_undeclared_declarations: Option<InternedDeclarationsId>,
}
impl PlaceStateInterner {
fn with_capacity(bindings: usize, declaration_map: usize, declarations: usize) -> Self {
Self {
interned_bindings: RetainedBindingsBuilder::with_capacity(bindings),
interned_ids_by_bindings: hashbrown::HashTable::with_capacity(bindings),
interned_declarations: RetainedDeclarationsBuilder::with_capacity(declarations),
interned_ids_by_declarations: FxHashMap::with_capacity_and_hasher(
declaration_map,
FxBuildHasher,
),
undeclared_declarations_by_constraint: IndexVec::new(),
always_unbound_bindings: None,
always_undeclared_declarations: None,
}
}
fn intern_bindings(&mut self, bindings: &Bindings) -> InternedBindingsId {
if bindings.is_always_unbound() {
if let Some(interned_id) = self.always_unbound_bindings {
return interned_id;
}
let interned_id = self.interned_bindings.push(bindings);
self.always_unbound_bindings = Some(interned_id);
return interned_id;
}
// The retained representation discards the unbound narrowing constraint, so it isn't
// part of the interned identity.
let hash = Self::hash_bindings(bindings.as_slice());
let interned_bindings = &mut self.interned_bindings;
let entry = self.interned_ids_by_bindings.entry(
hash,
|id| interned_bindings.get(*id) == bindings.as_slice(),
|id| Self::hash_bindings(interned_bindings.get(*id)),
);
match entry {
hashbrown::hash_table::Entry::Occupied(entry) => *entry.get(),
hashbrown::hash_table::Entry::Vacant(entry) => {
let interned_id = interned_bindings.push(bindings);
entry.insert(interned_id);
interned_id
}
}
}
fn hash_bindings(live_bindings: &[LiveBinding]) -> u64 {
let mut hasher = FxHasher::default();
live_bindings.hash(&mut hasher);
hasher.finish()
}
fn intern_declarations(&mut self, declarations: Declarations) -> InternedDeclarationsId {
if declarations.is_always_undeclared() {
if let Some(interned_id) = self.always_undeclared_declarations {
return interned_id;
}
let interned_id = self.interned_declarations.push(&declarations);
self.always_undeclared_declarations = Some(interned_id);
return interned_id;
}
if let Some(reachability_constraint) = declarations.undeclared_reachability_constraint()
&& !reachability_constraint.is_terminal()
{
let index = reachability_constraint.index();
let len = self.undeclared_declarations_by_constraint.len();
if index >= len {
self.undeclared_declarations_by_constraint
.resize(index + 1, None);
} else if let Some(interned_id) =
self.undeclared_declarations_by_constraint[reachability_constraint]
{
return interned_id;
}
let interned_id = self.interned_declarations.push(&declarations);
self.undeclared_declarations_by_constraint[reachability_constraint] = Some(interned_id);
return interned_id;
}
match self.interned_ids_by_declarations.entry(declarations) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
let interned_id = self.interned_declarations.push(entry.key());
entry.insert(interned_id);
interned_id
}
}
}
fn intern_place_state(
&mut self,
bindings: &Bindings,
declarations: Declarations,
) -> InternedPlaceStateId {
InternedPlaceStateId(
self.intern_bindings(bindings),
self.intern_declarations(declarations),
)
}
fn retain_place_state(
&mut self,
bindings: &Bindings,
declarations: Declarations,
) -> InternedPlaceStateId {
// Other retained declarations rarely repeat. Keep the compact IDs without hashing every
// declaration vector to find the occasional duplicate.
let declarations_id = if declarations.undeclared_reachability_constraint().is_some() {
self.intern_declarations(declarations)
} else {
self.interned_declarations.push(&declarations)
};
InternedPlaceStateId(self.intern_bindings(bindings), declarations_id)
}
}
/// Compact, retained representation of the interned binding vectors for a scope.
///
/// The builder needs a `SmallVec` and an optional unbound constraint while constructing each
/// binding state. Neither is needed after the semantic index is built, so the retained map stores
/// cumulative end offsets into one contiguous array instead.
#[derive(Debug, PartialEq, Eq, get_size2::GetSize)]
struct RetainedBindings {
ends: FrozenIndexVec<InternedBindingsId, u32>,
live_bindings: Box<[LiveBinding]>,
}
struct RetainedBindingsBuilder {
ends: IndexVec<InternedBindingsId, u32>,
live_bindings: Vec<LiveBinding>,
}
impl RetainedBindingsBuilder {
fn with_capacity(bindings: usize) -> Self {
Self {
ends: IndexVec::with_capacity(bindings),
live_bindings: Vec::with_capacity(bindings),
}
}
fn push(&mut self, bindings: &Bindings) -> InternedBindingsId {
// Definition IDs are also 32-bit and a single scope cannot practically approach this
// limit. Keeping one cumulative end offset per state halves the retained range metadata.
self.live_bindings.extend_from_slice(bindings.as_slice());
let end = u32::try_from(self.live_bindings.len())
.expect("Expected live-bindings length to fit into a u32");
self.ends.push(end)
}
fn get(&self, index: InternedBindingsId) -> &[LiveBinding] {
let end = self.ends[index];
let start = if index.index() == 0 {
0
} else {
self.ends[InternedBindingsId::new(index.index() - 1)]
};
&self.live_bindings[start as usize..end as usize]
}
fn finish(
self,
narrowing_constraints: &mut NarrowingConstraintsBuilder,
reachability_constraints: &mut ReachabilityConstraintsBuilder,
) -> RetainedBindings {
for binding in &self.live_bindings {
reachability_constraints.mark_used(binding.reachability_constraint());
narrowing_constraints.mark_used(binding.narrowing_constraint());
}
RetainedBindings {
ends: self.ends.into(),
live_bindings: self.live_bindings.into_boxed_slice(),
}
}
}
impl Index<InternedBindingsId> for RetainedBindings {
type Output = [LiveBinding];
fn index(&self, index: InternedBindingsId) -> &Self::Output {
let end = self.ends[index];
let start = if index.index() == 0 {
0
} else {
self.ends[InternedBindingsId::new(index.index() - 1)]
};
&self.live_bindings[start as usize..end as usize]
}
}
/// Compact, retained representation of the interned declaration vectors for a scope.
#[derive(Debug, PartialEq, Eq, get_size2::GetSize)]
struct RetainedDeclarations {
/// The exclusive end of each state in `live_declarations`; its start is the previous end.
ends: FrozenIndexVec<InternedDeclarationsId, u32>,
live_declarations: Box<[LiveDeclaration]>,
}
struct RetainedDeclarationsBuilder {
ends: IndexVec<InternedDeclarationsId, u32>,
live_declarations: Vec<LiveDeclaration>,
}
impl RetainedDeclarationsBuilder {
fn with_capacity(declarations: usize) -> Self {
Self {
ends: IndexVec::with_capacity(declarations),
live_declarations: Vec::with_capacity(declarations),
}
}
fn push(&mut self, declarations: &Declarations) -> InternedDeclarationsId {
self.live_declarations.extend(declarations.iter().cloned());
let end = u32::try_from(self.live_declarations.len())
.expect("Expected live-declarations length to fit into a u32");
self.ends.push(end)
}
fn finish(
self,
reachability_constraints: &mut ReachabilityConstraintsBuilder,
) -> RetainedDeclarations {
for declaration in &self.live_declarations {
reachability_constraints.mark_used(declaration.reachability_constraint);
}
RetainedDeclarations {
ends: self.ends.into(),
live_declarations: self.live_declarations.into_boxed_slice(),
}
}
}
impl Index<InternedDeclarationsId> for RetainedDeclarations {
type Output = [LiveDeclaration];
fn index(&self, index: InternedDeclarationsId) -> &Self::Output {
let end = self.ends[index];
let start = if index.index() == 0 {
0
} else {
self.ends[InternedDeclarationsId::new(index.index() - 1)]
};
&self.live_declarations[start as usize..end as usize]
}
}
#[derive(Clone, Debug, Eq, PartialEq, get_size2::GetSize)]
struct RetainedPlaceStates<T> {
end_of_scope: T,
reachable: T,
}
#[derive(Debug, PartialEq, Eq, get_size2::GetSize, salsa::SalsaValue)]
struct DefinitionsAtDefinition<B, D> {
bindings: B,
declarations: Option<D>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, get_size2::GetSize)]
enum InternedEnclosingSnapshotId {
Constraint(ScopedNarrowingConstraint),
Bindings(InternedBindingsId),
}
/// Lookup tables needed to evaluate reachability and narrowing constraints.
#[derive(Debug, PartialEq, Eq, get_size2::GetSize, salsa::SalsaValue)]
struct ConstraintTables<'db> {
predicates: Predicates<'db>,
predicate_narrowing_targets: PredicateNarrowingTargets,
reachability_constraints: ReachabilityConstraints,
narrowing_constraints: NarrowingConstraints,
}
/// Predicate-place pairs for which type narrowing may produce a constraint.
///
/// Reachability gates can contain predicates that are unrelated to the place being narrowed.
/// Keeping the conservative targets computed while building the semantic index lets type
/// inference skip constructing those predicates' full narrowing maps.
#[derive(Debug, Default, PartialEq, Eq, get_size2::GetSize, salsa::SalsaValue)]
pub struct PredicateNarrowingTargets(Box<[(ScopedPredicateId, ScopedPlaceId)]>);
impl PredicateNarrowingTargets {
fn from_entries(mut entries: Vec<(ScopedPredicateId, ScopedPlaceId)>) -> Self {
entries.sort_unstable_by_key(|&(predicate, place)| (place, predicate));
entries.dedup();
Self(entries.into_boxed_slice())
}
/// Returns whether `predicate` may narrow `place`.
pub fn contains(&self, predicate: ScopedPredicateId, place: ScopedPlaceId) -> bool {
self.0
.binary_search_by_key(&(place, predicate), |&(predicate, place)| {
(place, predicate)
})
.is_ok()
}
/// Returns whether any predicate may narrow `place`.
pub fn contains_place(&self, place: ScopedPlaceId) -> bool {
self.0
.binary_search_by_key(&place, |&(_, target)| target)
.is_ok()
}
}
/// Fields that are empty in most use-def maps.
///
/// These fields share an allocation to avoid storing five collection headers in every
/// [`UseDefMap`]. They are not otherwise semantically related.
#[derive(Debug, PartialEq, Eq, get_size2::GetSize)]
struct UseDefMapExtra {
/// [`Bindings`] reaching a [`ScopedUseId`].
bindings_by_use: FrozenIndexVec<ScopedUseId, InternedBindingsId>,
/// [`Bindings`] for each member reaching a [`ScopedUseId`].
///
/// This is only used for kwargs expressions, whose corresponding `bindings_by_use` entry
/// is empty.
multi_bindings_by_use: MultiBindingsByUse,
/// Retained [`PlaceState`] values for each member.
member_states: FrozenIndexVec<ScopedMemberId, RetainedPlaceStates<InternedPlaceStateId>>,
/// Snapshots of bindings used to resolve references from nested scopes.
enclosing_snapshots: FrozenIndexVec<ScopedEnclosingSnapshotId, InternedEnclosingSnapshotId>,
/// Completed loop headers in this scope.
loop_headers: FrozenIndexVec<LoopHeaderId, LoopHeader>,
}
static EMPTY_CONSTRAINT_TABLES: LazyLock<ConstraintTables<'static>> =
LazyLock::new(|| ConstraintTables {
predicates: IndexVec::new().into(),
predicate_narrowing_targets: PredicateNarrowingTargets::default(),
reachability_constraints: ReachabilityConstraintsBuilder::default().build(),
narrowing_constraints: NarrowingConstraintsBuilder::default().build(),
});
static ALWAYS_UNBOUND_BINDINGS: LazyLock<Bindings> =
LazyLock::new(|| Bindings::unbound(ScopedReachabilityConstraintId::ALWAYS_TRUE));
static ALWAYS_UNDECLARED_DECLARATIONS: LazyLock<Declarations> =
LazyLock::new(|| Declarations::undeclared(ScopedReachabilityConstraintId::ALWAYS_TRUE));
/// One event in a scope's use-def history.
#[derive(Clone, Copy, Debug, PartialEq, Eq, get_size2::GetSize, salsa::SalsaValue)]
enum DefinitionEntry<'db> {
/// The early declaration of a combined definition whose binding is recorded separately.
/// It participates in declaration lookup, but not in binding-usage analysis.
DeclarationPart(Definition<'db>),
/// A binding or standalone declaration with no recorded use.
Unused(Definition<'db>),
Used(Definition<'db>),
Undefined,
Deleted,
}
impl<'db> DefinitionEntry<'db> {
fn state(self) -> DefinitionState<'db> {
match self {
Self::DeclarationPart(definition)
| Self::Unused(definition)
| Self::Used(definition) => DefinitionState::Defined(definition),
Self::Undefined => DefinitionState::Undefined,
Self::Deleted => DefinitionState::Deleted,
}
}
}
static_assertions::assert_eq_size!(DefinitionEntry<'static>, DefinitionState<'static>);
/// Retained definition states, excluding the implicit unbound definition at index zero.
#[derive(Debug, PartialEq, Eq, get_size2::GetSize, salsa::SalsaValue)]
struct RetainedDefinitions<'db> {
states: Box<[DefinitionEntry<'db>]>,
}
impl<'db> RetainedDefinitions<'db> {
fn new(states: IndexVec<ScopedDefinitionId, DefinitionEntry<'db>>) -> Self {
let mut states = states.into_iter();
let unbound_state = states.next();
debug_assert_eq!(unbound_state, Some(DefinitionEntry::Undefined));
Self {
states: states.collect(),
}
}
#[inline]
fn get(&self, id: ScopedDefinitionId) -> DefinitionEntry<'db> {
let index = id.index();
if index == 0 {
DefinitionEntry::Undefined
} else {
self.states[index - 1]
}
}
fn iter_enumerated(
&self,
) -> impl Iterator<Item = (ScopedDefinitionId, DefinitionEntry<'db>)> + '_ {
self.states
.iter()
.copied()
.enumerate()
.map(|(index, entry)| (ScopedDefinitionId::new(index + 1), entry))
}
}
/// Applicable definitions and constraints for every use of a name.
#[derive(Debug, PartialEq, Eq, get_size2::GetSize, salsa::SalsaValue)]
pub struct UseDefMap<'db> {
/// Definition states in this scope, plus an implicit "unbound"/"undeclared" definition at
/// index zero.
all_definitions: RetainedDefinitions<'db>,
/// Constraint lookup tables, absent when all retained constraints are built-in terminal
/// values that require no table lookup.
constraint_tables: Option<Box<ConstraintTables<'db>>>,
/// Interned [`Bindings`] values.
interned_bindings: RetainedBindings,
/// Interned [`Declarations`] values.
interned_declarations: RetainedDeclarations,
/// Tracks the reachability constraint for statements and certain sub-expressions
/// (e.g. ternary branches, boolean operator operands), keyed by their text range.
/// Used to suppress diagnostics in unreachable code.
range_reachability: Box<[(TextRange, RangeInfo)]>,
/// If the definition is a binding (only) -- `x = 1` for example -- then we need
/// [`Declarations`] to know whether this binding is permitted by the live declarations.
///
/// If the definition is both a declaration and a binding -- `x: int = 1` for example -- then
/// we don't actually need anything here, all we'll need to validate is that our own RHS is a
/// valid assignment to our own annotation.
///
/// If the definition is a declaration (only) -- `x: int` for example -- then we need
/// [`Bindings`] to know whether this declaration is consistent with the previously
/// inferred type.
///
/// If we see a binding to a `Final`-qualified symbol, we also need the bindings to find
/// previous bindings to that symbol. If there are any, the assignment is invalid.
///
/// Entries whose prior state is the start-of-scope default (always unbound and, if present,
/// always undeclared) are omitted. Lookups use [`ALWAYS_UNBOUND_BINDINGS`] and
/// [`ALWAYS_UNDECLARED_DECLARATIONS`], which are initialized lazily and shared by every map.
definitions_by_definition: FrozenMap<
Definition<'db>,
DefinitionsAtDefinition<InternedBindingsId, InternedDeclarationsId>,
>,
/// Retained [`PlaceState`] values for each symbol.
symbol_states: FrozenIndexVec<ScopedSymbolId, RetainedPlaceStates<InternedPlaceStateId>>,
/// Collection fields omitted when they would all be empty.
extra: Option<Box<UseDefMapExtra>>,
/// Whether or not the end of the scope is reachable.
///
/// This is used to check if the function can implicitly return `None`.
/// For example:
/// ```py
/// def f(cond: bool) -> int | None:
/// if cond:
/// return 1
///
/// def g() -> int:
/// if True:
/// return 1
/// ```
///
/// Function `f` may implicitly return `None`, but `g` cannot.
///
/// This is used by `can_implicitly_return_none` in the `ty_python_semantic` crate.
end_of_scope_reachability: ScopedReachabilityConstraintId,
}
/// Information about a given range of source code.
#[derive(Debug, Copy, Clone, PartialEq, Eq, get_size2::GetSize)]
struct RangeInfo {
reachability: ScopedReachabilityConstraintId,
in_type_checking_block: bool,
}
impl Default for RangeInfo {
fn default() -> Self {
Self {
reachability: ScopedReachabilityConstraintId::ALWAYS_TRUE,
in_type_checking_block: false,
}
}
}
#[derive(Debug, PartialEq, Eq, get_size2::GetSize)]
struct MultiBindingsByUse(ThinVec<(ScopedUseId, Box<[Bindings]>)>);
impl MultiBindingsByUse {
fn from_map(map: FxHashMap<ScopedUseId, Vec<Bindings>>) -> Self {
let mut entries = map
.into_iter()
.map(|(use_id, bindings)| (use_id, bindings.into_boxed_slice()))
.collect::<Vec<_>>();
entries.sort_unstable_by_key(|(use_id, _)| *use_id);
Self(entries.into_iter().collect())
}
fn get(&self, use_id: ScopedUseId) -> Option<&[Bindings]> {
self.0
.binary_search_by_key(&use_id, |(candidate, _)| *candidate)
.ok()
.map(|index| self.0[index].1.as_ref())
}
}
pub enum ApplicableConstraints<'map, 'db> {
UnboundBinding(NarrowingEvaluator<'map, 'db>),
ConstrainedBindings(BindingWithConstraintsIterator<'map, 'db>),
}
impl<'db> UseDefMap<'db> {
fn constraint_tables(&self) -> &ConstraintTables<'db> {
self.constraint_tables
.as_deref()
.map_or(&EMPTY_CONSTRAINT_TABLES, |tables| tables)
}
fn extra(&self) -> &UseDefMapExtra {
self.extra
.as_deref()
.expect("extra use-def data should have been retained")
}
pub fn loop_header(&self, id: LoopHeaderId) -> &LoopHeader {
&self.extra().loop_headers[id]
}
pub fn reachability_constraints(&self) -> &ReachabilityConstraints {
&self.constraint_tables().reachability_constraints
}
pub fn predicates(&self) -> &Predicates<'db> {
&self.constraint_tables().predicates
}
pub fn range_reachability(
&self,
) -> impl Iterator<Item = (TextRange, ScopedReachabilityConstraintId)> + '_ {
self.range_reachability
.iter()
.map(|&(range, RangeInfo { reachability, .. })| (range, reachability))
}
pub fn end_of_scope_reachability(&self) -> ScopedReachabilityConstraintId {
self.end_of_scope_reachability
}
/// Definitions relevant to usage analysis, including standalone declarations.
///
/// The early declaration part of a combined definition is omitted: its later binding entry
/// carries the usage information for that definition.
pub fn definitions_with_usage(
&self,
) -> impl Iterator<Item = (ScopedDefinitionId, Definition<'db>, bool)> + '_ {
self.all_definitions
.iter_enumerated()
.filter_map(|(id, entry)| match entry {
DefinitionEntry::Unused(definition) => Some((id, definition, false)),
DefinitionEntry::Used(definition) => Some((id, definition, true)),
DefinitionEntry::DeclarationPart(_)
| DefinitionEntry::Undefined
| DefinitionEntry::Deleted => None,
})
}
pub fn bindings_at_use(&self, use_id: ScopedUseId) -> BindingWithConstraintsIterator<'_, 'db> {
let bindings_id = self.extra().bindings_by_use[use_id];
self.bindings_iterator(
&self.interned_bindings[bindings_id],
BoundnessAnalysis::BasedOnUnboundVisibility,
)
}
pub fn multi_bindings_at_use(
&self,
use_id: ScopedUseId,
) -> impl Iterator<Item = BindingWithConstraintsIterator<'_, 'db>> {
self.extra
.as_deref()
.and_then(|extra| extra.multi_bindings_by_use.get(use_id))
.map(|member_bindings| {
member_bindings.iter().map(|bindings| {
self.bindings_iterator(
bindings.as_slice(),
BoundnessAnalysis::BasedOnUnboundVisibility,
)
})
})
.into_iter()
.flatten()
}
pub fn applicable_constraints(
&self,
constraint_key: ConstraintKey,
enclosing_scope: FileScopeId,
expr: PlaceExprRef,
index: &'db SemanticIndex,
) -> ApplicableConstraints<'_, 'db> {
match constraint_key {
ConstraintKey::NarrowingConstraint(constraint) => {
ApplicableConstraints::UnboundBinding(NarrowingEvaluator {
constraint,
constraint_tables: self.constraint_tables(),
})
}
ConstraintKey::NestedScope(nested_scope) => {
let EnclosingSnapshotResult::FoundBindings(bindings) =
index.enclosing_snapshot(enclosing_scope, expr, nested_scope)
else {
unreachable!(
"The result of `SemanticIndex::eager_snapshot` must be `FoundBindings`"
)
};
ApplicableConstraints::ConstrainedBindings(bindings)
}
ConstraintKey::UseId(use_id) => {
ApplicableConstraints::ConstrainedBindings(self.bindings_at_use(use_id))
}
}
}
pub fn definition(&self, id: ScopedDefinitionId) -> DefinitionState<'db> {
self.all_definitions.get(id).state()
}
pub fn narrowing_evaluator(
&self,
constraint: ScopedNarrowingConstraint,
) -> NarrowingEvaluator<'_, 'db> {
NarrowingEvaluator {
constraint,
constraint_tables: self.constraint_tables(),
}
}
pub(crate) fn is_range_in_type_checking_block(&self, range: TextRange) -> bool {
self.range_reachability
.iter()
.take_while(|(entry_range, _)| entry_range.start() <= range.start())
.any(|&(entry_range, block)| {
block.in_type_checking_block && entry_range.contains_range(range)
})
}
pub fn end_of_scope_bindings(
&self,
place: ScopedPlaceId,
) -> BindingWithConstraintsIterator<'_, 'db> {
match place {
ScopedPlaceId::Symbol(symbol) => self.end_of_scope_symbol_bindings(symbol),
ScopedPlaceId::Member(member) => self.end_of_scope_member_bindings(member),