Repository navigation
Expand file tree
/
Copy pathplace.rs
More file actions
2696 lines (2478 loc) · 105 KB
/
Copy pathplace.rs
File metadata and controls
2696 lines (2478 loc) · 105 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
pub(crate) mod definitions;
use crate::ProgramEnvironment;
use itertools::Either;
use ruff_index::IndexSlice;
use ruff_python_ast::PythonVersion;
use ty_module_resolver::{
KnownModule, Module, ModuleName, file_to_module, resolve_module_confident,
};
use crate::dunder_all::dunder_all_names;
use crate::reachability::{
ReachabilityEvaluationCache, evaluate_reachability, evaluate_reachability_with_cache,
};
use crate::types::narrow::NarrowingEvaluatorExtension;
use crate::types::{
DynamicType, KnownClass, MemberLookupPolicy, Type, TypeAndQualifiers, TypeQualifiers,
UnionBuilder, UnionType, binding_type, exists_at_runtime, inferred_declaration,
is_discarded_dict_key_assignment,
};
use crate::{Db, FxIndexSet, FxOrderSet};
use ty_python_core::definition::{Definition, DefinitionKind, DefinitionState};
use ty_python_core::narrowing_constraints::ScopedNarrowingConstraint;
use ty_python_core::place::ScopedPlaceId;
use ty_python_core::predicate::{Predicate, ScopedPredicateId};
use ty_python_core::reachability_constraints::{
ReachabilityConstraints, ScopedReachabilityConstraintId,
};
use ty_python_core::scope::ScopeId;
use ty_python_core::{
BindingWithConstraints, BindingWithConstraintsIterator, BoundnessAnalysis,
DeclarationWithConstraint, DeclarationsIterator, ProgramFile, Truthiness, global_scope,
place_table, use_def_map,
};
pub(crate) use implicit_globals::{
module_type_implicit_global_declaration, module_type_implicit_global_symbol,
};
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, get_size2::GetSize)]
pub(crate) enum Definedness {
AlwaysDefined,
PossiblyUndefined,
}
impl Definedness {
pub(crate) const fn max(self, other: Self) -> Self {
match (self, other) {
(Definedness::AlwaysDefined, _) | (_, Definedness::AlwaysDefined) => {
Definedness::AlwaysDefined
}
(Definedness::PossiblyUndefined, Definedness::PossiblyUndefined) => {
Definedness::PossiblyUndefined
}
}
}
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, get_size2::GetSize)]
pub(crate) enum TypeOrigin {
Declared,
Inferred,
}
impl TypeOrigin {
pub(crate) const fn is_declared(self) -> bool {
matches!(self, TypeOrigin::Declared)
}
pub(crate) const fn merge(self, other: Self) -> Self {
match (self, other) {
(TypeOrigin::Declared, TypeOrigin::Declared) => TypeOrigin::Declared,
_ => TypeOrigin::Inferred,
}
}
}
/// How a place's raw type should be adjusted when accessed publicly.
///
/// For undeclared public symbols (e.g., class attributes without type annotations),
/// we store the raw inferred type and lazily apply the public-type policy when
/// converting the place into a public lookup result.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Default, get_size2::GetSize)]
pub(crate) enum PublicTypePolicy {
/// Public lookup should expose the raw stored type.
#[default]
Raw,
/// Public lookup should expose the promoted stored type.
Promote,
}
impl PublicTypePolicy {
/// Apply the public-type policy to the raw type.
fn apply_if_needed<'db>(
self,
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
ty: Type<'db>,
) -> Type<'db> {
match self {
Self::Raw => ty,
Self::Promote => ty.promote(db, env).promote_singletons(db, env),
}
}
}
/// The source definition provenance for a place.
#[derive(
Debug, Clone, Copy, Default, Hash, PartialEq, Eq, get_size2::GetSize, salsa::SalsaValue,
)]
pub(crate) enum Provenance<'db> {
/// No source definition is known.
#[default]
Unknown,
/// Exactly one source definition is known.
SingleDefinition(Definition<'db>),
/// Multiple distinct source definitions contribute to the place. Instead of storing all of
/// them, or selecting one arbitrarily, we currently discard provenance information in this
/// case.
MultipleDefinitions,
}
impl<'db> Provenance<'db> {
pub(crate) fn from_definition(definition: Option<Definition<'db>>) -> Self {
definition.map_or(Self::Unknown, Self::SingleDefinition)
}
/// Merge the provenance from two places.
pub(crate) fn or(self, other: Self) -> Self {
match (self, other) {
(Self::Unknown, provenance) | (provenance, Self::Unknown) => provenance,
(Self::MultipleDefinitions, _) | (_, Self::MultipleDefinitions) => {
Self::MultipleDefinitions
}
(Self::SingleDefinition(left), Self::SingleDefinition(right)) if left == right => self,
(Self::SingleDefinition(_), Self::SingleDefinition(_)) => Self::MultipleDefinitions,
}
}
pub(crate) fn definition(self) -> Option<Definition<'db>> {
match self {
Self::SingleDefinition(definition) => Some(definition),
Self::Unknown | Self::MultipleDefinitions => None,
}
}
}
/// A defined place with its raw type, origin, definedness, public-type policy, and provenance.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, get_size2::GetSize, salsa::SalsaValue)]
pub(crate) struct DefinedPlace<'db> {
pub(crate) ty: Type<'db>,
pub(crate) origin: TypeOrigin,
pub(crate) definedness: Definedness,
pub(crate) public_type_policy: PublicTypePolicy,
pub(crate) provenance: Provenance<'db>,
}
impl<'db> DefinedPlace<'db> {
fn new(ty: Type<'db>) -> Self {
Self {
ty,
origin: TypeOrigin::Inferred,
definedness: Definedness::AlwaysDefined,
public_type_policy: PublicTypePolicy::Raw,
provenance: Provenance::Unknown,
}
}
fn with_origin(mut self, origin: TypeOrigin) -> Self {
self.origin = origin;
self
}
pub(crate) fn with_definedness(mut self, definedness: Definedness) -> Self {
self.definedness = definedness;
self
}
fn with_public_type_policy(mut self, public_type_policy: PublicTypePolicy) -> Self {
self.public_type_policy = public_type_policy;
self
}
fn with_definition(mut self, definition: Definition<'db>) -> Self {
self.provenance = Provenance::SingleDefinition(definition);
self
}
fn with_provenance(mut self, provenance: Provenance<'db>) -> Self {
self.provenance = provenance;
self
}
pub(crate) const fn is_definitely_defined(&self) -> bool {
matches!(self.definedness, Definedness::AlwaysDefined)
}
}
/// The result of a place lookup, which can either be a (possibly undefined) type
/// or a completely undefined place.
///
/// If a place has both a binding and a declaration, the result of the binding is used.
///
/// Consider this example:
/// ```py
/// bound = 1
/// declared: int
///
/// if flag:
/// possibly_unbound = 2
/// possibly_undeclared: int
///
/// if flag:
/// bound_or_declared = 1
/// else:
/// bound_or_declared: int
/// ```
///
/// If we look up places in this scope, we would get the following results:
/// ```rs
/// bound: Place::Defined(DefinedPlace { ty: Literal[1], origin: TypeOrigin::Inferred, definedness: Definedness::AlwaysDefined, .. }),
/// declared: Place::Defined(DefinedPlace { ty: int, origin: TypeOrigin::Declared, definedness: Definedness::AlwaysDefined, .. }),
/// possibly_unbound: Place::Defined(DefinedPlace { ty: Literal[2], origin: TypeOrigin::Inferred, definedness: Definedness::PossiblyUndefined, .. }),
/// possibly_undeclared: Place::Defined(DefinedPlace { ty: int, origin: TypeOrigin::Declared, definedness: Definedness::PossiblyUndefined, .. }),
/// bound_or_declared: Place::Defined(DefinedPlace { ty: Literal[1], origin: TypeOrigin::Inferred, definedness: Definedness::PossiblyUndefined, .. }),
/// non_existent: Place::Undefined,
/// ```
#[derive(
Debug, Clone, Copy, Default, Hash, PartialEq, Eq, get_size2::GetSize, salsa::SalsaValue,
)]
pub(crate) enum Place<'db> {
Defined(DefinedPlace<'db>),
#[default]
Undefined,
}
impl<'db> Place<'db> {
/// Constructor that creates a [`Place`] with type origin [`TypeOrigin::Inferred`] and definedness [`Definedness::AlwaysDefined`].
pub(crate) fn bound(ty: impl Into<Type<'db>>) -> Self {
Place::Defined(DefinedPlace::new(ty.into()))
}
/// Constructor that creates a [`Place`] with type origin [`TypeOrigin::Declared`] and definedness [`Definedness::AlwaysDefined`].
pub(crate) fn declared(ty: impl Into<Type<'db>>) -> Self {
Place::Defined(DefinedPlace::new(ty.into()).with_origin(TypeOrigin::Declared))
}
/// Returns this place with the given definition attached. A no-op for [`Place::Undefined`].
#[must_use]
pub(crate) fn with_definition(self, definition: Definition<'db>) -> Self {
match self {
Place::Defined(defined) => Place::Defined(defined.with_definition(definition)),
Place::Undefined => Place::Undefined,
}
}
/// Returns this place with the given provenance attached. A no-op for [`Place::Undefined`].
#[must_use]
pub(crate) fn with_provenance(self, provenance: Provenance<'db>) -> Self {
match self {
Place::Defined(defined) => Place::Defined(defined.with_provenance(provenance)),
Place::Undefined => Place::Undefined,
}
}
pub(crate) fn is_equal_ignoring_provenance(self, other: Self) -> bool {
match (self, other) {
(Place::Defined(left), Place::Defined(right)) => {
left.ty == right.ty
&& left.origin == right.origin
&& left.definedness == right.definedness
&& left.public_type_policy == right.public_type_policy
}
(Place::Undefined, Place::Undefined) => true,
_ => false,
}
}
pub(crate) fn is_undefined(&self) -> bool {
matches!(self, Place::Undefined)
}
/// Returns the type of the place, ignoring possible undefinedness.
///
/// If the place is *definitely* undefined, this function will return `None`. Otherwise,
/// if there is at least one control-flow path where the place is defined, return the type.
pub(crate) fn ignore_possibly_undefined(&self) -> Option<Type<'db>> {
match self {
Place::Defined(defined) => Some(defined.ty),
Place::Undefined => None,
}
}
/// Returns the raw stored type of the place.
///
/// Any public-type adjustment is applied lazily when converting to `LookupResult`.
pub(crate) fn raw_type(&self) -> Option<Type<'db>> {
match self {
Place::Defined(defined) => Some(defined.ty),
Place::Undefined => None,
}
}
#[cfg(test)]
#[track_caller]
pub(crate) fn expect_type(self) -> Type<'db> {
self.ignore_possibly_undefined()
.expect("Expected a (possibly undefined) type, not an undefined place")
}
#[must_use]
fn map_type(self, f: impl FnOnce(Type<'db>) -> Type<'db>) -> Place<'db> {
match self {
Place::Defined(defined) => Place::Defined(DefinedPlace {
ty: f(defined.ty),
..defined
}),
Place::Undefined => Place::Undefined,
}
}
/// Set the public-type policy for this place.
#[must_use]
fn with_public_type_policy(self, new_public_type_policy: PublicTypePolicy) -> Place<'db> {
match self {
Place::Defined(defined) => {
Place::Defined(defined.with_public_type_policy(new_public_type_policy))
}
Place::Undefined => Place::Undefined,
}
}
#[must_use]
pub(crate) fn with_qualifiers(self, qualifiers: TypeQualifiers) -> PlaceAndQualifiers<'db> {
PlaceAndQualifiers {
place: self,
qualifiers,
}
}
/// Try to call `__get__(None, owner)` on the type of this place (not on the meta type).
/// If it succeeds, return the `__get__` return type. Otherwise, returns the original place.
/// This is used to resolve (potential) descriptor attributes.
pub(crate) fn try_call_dunder_get(
self,
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
owner: Type<'db>,
) -> Place<'db> {
match self {
Place::Defined(
place @ DefinedPlace {
ty: Type::Union(union),
..
},
) => union.map_with_boundness(db, env, |elem| {
Place::Defined(DefinedPlace { ty: *elem, ..place })
.try_call_dunder_get(db, env, owner)
}),
Place::Defined(
place @ DefinedPlace {
ty: Type::Intersection(intersection),
..
},
) => intersection.map_with_boundness(db, env, |elem| {
Place::Defined(DefinedPlace { ty: *elem, ..place })
.try_call_dunder_get(db, env, owner)
}),
Place::Defined(defined) => {
let result = defined
.ty
.try_call_dunder_get(db, env, None, owner)
.unwrap_or_else(|error| Some(error.fallback()));
if let Some(result) = result {
Place::Defined(DefinedPlace {
ty: result.return_type,
provenance: Provenance::Unknown,
..defined
})
} else {
self
}
}
Place::Undefined => Place::Undefined,
}
}
pub(crate) const fn is_definitely_bound(&self) -> bool {
matches!(
self,
Place::Defined(DefinedPlace {
definedness: Definedness::AlwaysDefined,
..
})
)
}
}
impl<'db> From<LookupResult<'db>> for PlaceAndQualifiers<'db> {
fn from(value: LookupResult<'db>) -> Self {
match value {
Ok(type_and_qualifiers) => Place::Defined(
DefinedPlace::new(type_and_qualifiers.inner_type())
.with_origin(type_and_qualifiers.origin())
.with_provenance(type_and_qualifiers.provenance()),
)
.with_qualifiers(type_and_qualifiers.qualifiers()),
Err(LookupError::Undefined(qualifiers)) => Place::Undefined.with_qualifiers(qualifiers),
Err(LookupError::PossiblyUndefined(type_and_qualifiers)) => Place::Defined(
DefinedPlace::new(type_and_qualifiers.inner_type())
.with_origin(type_and_qualifiers.origin())
.with_definedness(Definedness::PossiblyUndefined)
.with_provenance(type_and_qualifiers.provenance()),
)
.with_qualifiers(type_and_qualifiers.qualifiers()),
}
}
}
/// Possible ways in which a place lookup can (possibly or definitely) fail.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum LookupError<'db> {
Undefined(TypeQualifiers),
PossiblyUndefined(TypeAndQualifiers<'db>),
}
impl<'db> LookupError<'db> {
/// Fallback (wholly or partially) to `fallback` to create a new [`LookupResult`].
pub(crate) fn or_fall_back_to(
self,
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
fallback: PlaceAndQualifiers<'db>,
) -> LookupResult<'db> {
let fallback = fallback.into_lookup_result(db, env);
match (&self, &fallback) {
(LookupError::Undefined(_), _) => fallback,
(LookupError::PossiblyUndefined { .. }, Err(LookupError::Undefined(_))) => Err(self),
(LookupError::PossiblyUndefined(ty), Ok(ty2)) => Ok(TypeAndQualifiers::new(
UnionType::from_two_elements(db, env, ty.inner_type(), ty2.inner_type()),
ty.origin().merge(ty2.origin()),
ty.qualifiers().union(ty2.qualifiers()),
)
.with_provenance(ty.provenance().or(ty2.provenance()))),
(LookupError::PossiblyUndefined(ty), Err(LookupError::PossiblyUndefined(ty2))) => {
Err(LookupError::PossiblyUndefined(
TypeAndQualifiers::new(
UnionType::from_two_elements(db, env, ty.inner_type(), ty2.inner_type()),
ty.origin().merge(ty2.origin()),
ty.qualifiers().union(ty2.qualifiers()),
)
.with_provenance(ty.provenance().or(ty2.provenance())),
))
}
}
}
}
/// A [`Result`] type in which the `Ok` variant represents a definitely bound place
/// and the `Err` variant represents a place that is either definitely or possibly unbound.
///
/// Note that this type is exactly isomorphic to [`Place`].
/// In the future, we could possibly consider removing `Place` and using this type everywhere instead.
pub(crate) type LookupResult<'db> = Result<TypeAndQualifiers<'db>, LookupError<'db>>;
/// Infer the public type of a symbol (its type as seen from outside its scope) in the given
/// `scope`.
#[allow(unused)]
pub(crate) fn symbol<'db>(
db: &'db dyn Db,
scope: ScopeId<'db>,
name: &str,
considered_definitions: ConsideredDefinitions,
) -> PlaceAndQualifiers<'db> {
symbol_impl(
db,
scope,
name,
RequiresExplicitReExport::No,
considered_definitions,
)
}
/// Infers the public type of an explicit module-global symbol as seen from within the same file.
///
/// Note that all global scopes also include various "implicit globals" such as `__name__`,
/// `__doc__` and `__file__`. This function **does not** consider those symbols; it will return
/// `Place::Undefined` for them. Use the (currently test-only) `global_symbol` query to also include
/// those additional symbols.
///
/// Use [`imported_symbol`] to perform the lookup as seen from outside the file (e.g. via imports).
pub(crate) fn explicit_global_symbol<'db>(
db: &'db dyn Db,
file: ProgramFile<'db>,
name: &str,
) -> PlaceAndQualifiers<'db> {
symbol_impl(
db,
global_scope(db, file),
name,
RequiresExplicitReExport::No,
ConsideredDefinitions::AllReachable,
)
}
/// Infers the public type of an explicit module-global symbol as seen from within the same file.
///
/// Unlike [`explicit_global_symbol`], this function also considers various "implicit globals"
/// such as `__name__`, `__doc__` and `__file__`. These are looked up as attributes on `types.ModuleType`
/// rather than being looked up as symbols explicitly defined/declared in the global scope.
///
/// Use [`imported_symbol`] to perform the lookup as seen from outside the file (e.g. via imports).
#[allow(unused)]
pub(crate) fn global_symbol<'db>(
db: &'db dyn Db,
file: ProgramFile<'db>,
name: &str,
) -> PlaceAndQualifiers<'db> {
let env = ProgramEnvironment::from_file(file);
explicit_global_symbol(db, file, name).or_fall_back_to(db, &env, || {
module_type_implicit_global_symbol(db, file, name)
})
}
/// Infers the public type of an imported symbol.
///
/// If `requires_explicit_reexport` is [`None`], it will be inferred from the file's source type.
/// For stub files, explicit re-export will be required, while for non-stub files, it will not.
///
/// `None` should be passed for the `file` parameter if looking up a symbol on a namespace package.
pub(crate) fn imported_symbol<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
file: Option<ProgramFile<'db>>,
name: &str,
requires_explicit_reexport: Option<RequiresExplicitReExport>,
) -> PlaceAndQualifiers<'db> {
if let Some(file) = file {
debug_assert_eq!(file.program(db), env.program(db));
}
// If it's not found in the global scope, check if it's present as an instance on
// `types.ModuleType` or `builtins.object`.
//
// We do a more limited version of this in `module_type_implicit_global_symbol`,
// but there are two crucial differences here:
// - If a member is looked up as an attribute, `__init__` is also available on the module, but
// it isn't available as a global from inside the module
// - If a member is looked up as an attribute, members on `builtins.object` are also available
// (because `types.ModuleType` inherits from `object`); these attributes are also not
// available as globals from inside the module.
//
// The same way as in `module_type_implicit_global_symbol`, however, we need to be careful to
// ignore `__getattr__`. Typeshed has a fake `__getattr__` on `types.ModuleType` to help out with
// dynamic imports; we shouldn't use it for `ModuleLiteral` types where we know exactly which
// module we're dealing with.
file.map(|file| {
let requires_explicit_reexport = requires_explicit_reexport.unwrap_or_else(|| {
if file.file(db).is_stub(db) {
RequiresExplicitReExport::Yes
} else {
RequiresExplicitReExport::No
}
});
symbol_impl(
db,
global_scope(db, file),
name,
requires_explicit_reexport,
ConsideredDefinitions::EndOfScope,
)
})
.unwrap_or_default()
.or_fall_back_to(db, env, || {
match name {
"__file__" => {
// We special-case `__file__` here because we know that for a successfully imported
// non-namespace-package Python module, that hasn't been explicitly overridden it
// is always a string, even though typeshed says `str | None`. For a namespace package,
// meanwhile, it will always be `None`.
//
// Note that C-extension modules (stdlib examples include `sys`, `itertools`, etc.)
// may not have a `__file__` attribute at runtime at all, but that doesn't really
// affect the *type* of the attribute, just the *boundness*. There's no way for us
// to know right now whether a stub represents a C extension or not, so for now we
// do not attempt to detect this; we just infer `str` still. This matches the
// behaviour of other major type checkers.
if file.is_some() {
Place::bound(KnownClass::Str.to_instance(db, env)).into()
} else {
Place::bound(Type::none(db, env)).into()
}
}
"__getattr__" => Place::Undefined.into(),
"__builtins__" => Place::bound(Type::any()).into(),
_ => KnownClass::ModuleType
.to_instance(db, env)
.member_lookup_with_policy(db, env, name, MemberLookupPolicy::NO_GETATTR_LOOKUP),
}
})
}
/// Lookup the type of `symbol` in the builtins namespace.
///
/// Returns `Place::Undefined` if the `builtins` module isn't available for some reason.
///
/// Note that this function is only intended for use in the context of the builtins *namespace*
/// and should not be used when a symbol is being explicitly imported from the `builtins` module
/// (e.g. `from builtins import int`).
pub(crate) fn builtins_symbol<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
symbol: &str,
) -> PlaceAndQualifiers<'db> {
builtins_symbol_impl(db, env, symbol, BuiltinVisibility::All)
.map(|(_, symbol)| symbol)
.unwrap_or_default()
}
/// Looks up `symbol` for implicit builtin fallback.
///
/// Private type-checking-only definitions are implementation details, but private runtime
/// definitions from either the standard or project-level builtins remain available.
///
/// ```python
/// # builtins.pyi
/// _T = TypeVar("_T") # Not available as an implicit builtin.
///
/// # __builtins__.pyi
/// _custom: int # Available as an implicit builtin.
/// ```
pub(crate) fn implicit_builtins_symbol<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
symbol: &str,
) -> PlaceAndQualifiers<'db> {
builtins_symbol_impl(db, env, symbol, BuiltinVisibility::RuntimeOnly)
.map(|(_, symbol)| symbol)
.unwrap_or_default()
}
/// Returns the module scope that supplies `symbol` through implicit builtin fallback.
///
/// Uses the same visibility rules as [`implicit_builtins_symbol`] so IDE definition lookup cannot
/// resolve a private typing-only helper that type inference considers undefined.
pub(crate) fn implicit_builtins_symbol_scope<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
symbol: &str,
) -> Option<ScopeId<'db>> {
builtins_symbol_impl(db, env, symbol, BuiltinVisibility::RuntimeOnly).map(|(scope, _)| scope)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum BuiltinVisibility {
All,
RuntimeOnly,
}
/// Resolves project-level builtins before standard builtins and optionally hides typing-only names.
///
/// Returns the supplying module's scope together with the symbol so inference and IDE lookups can
/// share the same resolution and visibility policy.
fn builtins_symbol_impl<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
symbol: &str,
visibility: BuiltinVisibility,
) -> Option<(ScopeId<'db>, PlaceAndQualifiers<'db>)> {
let program = env.program(db);
let resolver_environment = program.resolver_environment(db);
let resolver = |module: Module<'db>| {
let file = ProgramFile::new(db, module.file(db)?, program);
let scope = global_scope(db, file);
let found_symbol = symbol_impl(
db,
scope,
symbol,
RequiresExplicitReExport::Yes,
ConsideredDefinitions::EndOfScope,
)
.or_fall_back_to(db, env, || {
// We're looking up in the builtins namespace and not the module, so we should
// do the normal lookup in `types.ModuleType` and not the special one as in
// `imported_symbol`.
module_type_implicit_global_symbol(db, file, symbol)
});
found_symbol.ignore_possibly_undefined()?;
if matches!(visibility, BuiltinVisibility::RuntimeOnly)
&& let Place::Defined(defined) = found_symbol.place
&& let Some(definition) = defined.provenance.definition()
&& !exists_at_runtime(db, definition)
{
return None;
}
Some((scope, found_symbol))
};
// If this symbol is not present in project-level builtins, search in the default ones.
resolve_module_confident(
db,
resolver_environment,
&ModuleName::new_static("__builtins__").unwrap(),
)
.and_then(&resolver)
.or_else(|| {
resolve_module_confident(db, resolver_environment, &KnownModule::Builtins.name())
.and_then(resolver)
})
}
/// Lookup the type of `symbol` in a given known module.
///
/// Returns `Place::Undefined` if the given known module cannot be resolved for some reason.
pub(crate) fn known_module_symbol<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
known_module: KnownModule,
symbol: &str,
) -> PlaceAndQualifiers<'db> {
resolve_module_confident(db, env.resolver_environment(db), &known_module.name())
.and_then(|module| {
let file = ProgramFile::new(db, module.file(db)?, env.program(db));
Some(imported_symbol(db, env, Some(file), symbol, None))
})
.unwrap_or_default()
}
/// Lookup the type of `symbol` in the `typing` module namespace.
///
/// Returns `Place::Undefined` if the `typing` module isn't available for some reason.
#[inline]
#[cfg(test)]
pub(crate) fn typing_symbol<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
symbol: &str,
) -> PlaceAndQualifiers<'db> {
known_module_symbol(db, env, KnownModule::Typing, symbol)
}
/// Lookup the type of `symbol` in the `typing_extensions` module namespace.
///
/// Returns `Place::Undefined` if the `typing_extensions` module isn't available for some reason.
#[inline]
pub(crate) fn typing_extensions_symbol<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
symbol: &str,
) -> PlaceAndQualifiers<'db> {
known_module_symbol(db, env, KnownModule::TypingExtensions, symbol)
}
/// Get the `builtins` module scope.
///
/// Can return `None` if a custom typeshed is used that is missing `builtins.pyi`.
pub(crate) fn builtins_module_scope<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
) -> Option<ScopeId<'db>> {
core_module_scope(db, env, KnownModule::Builtins)
}
/// Get the scope of a core stdlib module.
///
/// Can return `None` if a custom typeshed is used that is missing the core module in question.
fn core_module_scope<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
core_module: KnownModule,
) -> Option<ScopeId<'db>> {
let program = env.program(db);
let module = resolve_module_confident(db, env.resolver_environment(db), &core_module.name())?;
Some(global_scope(
db,
ProgramFile::new(db, module.file(db)?, program),
))
}
/// Infer the combined type from an iterator of bindings, and return it
/// together with boundness information in a [`Place`].
///
/// The type will be a union if there are multiple bindings with different types.
pub(super) fn place_from_bindings<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
bindings_with_constraints: BindingWithConstraintsIterator<'_, 'db>,
) -> PlaceWithDefinition<'db> {
place_from_bindings_impl(
db,
env,
bindings_with_constraints,
RequiresExplicitReExport::No,
None,
)
}
pub(super) fn place_from_bindings_with_reachability_cache<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
bindings_with_constraints: BindingWithConstraintsIterator<'_, 'db>,
reachability_cache: &ReachabilityEvaluationCache<'db>,
) -> PlaceWithDefinition<'db> {
place_from_bindings_impl(
db,
env,
bindings_with_constraints,
RequiresExplicitReExport::No,
Some(reachability_cache),
)
}
/// Build a declared type from a [`DeclarationsIterator`].
///
/// If there is only one declaration, or all declarations declare the same type, returns
/// `Ok(..)`. If there are conflicting declarations, returns an `Err(..)` variant with
/// a union of the declared types as well as a list of all conflicting types.
///
/// This function also returns declaredness information (see [`Place`]) and a set of
/// [`TypeQualifiers`] that have been specified on the declaration(s).
pub(crate) fn place_from_declarations<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
declarations: DeclarationsIterator<'_, 'db>,
) -> PlaceFromDeclarationsResult<'db> {
place_from_declarations_impl(db, env, declarations, RequiresExplicitReExport::No, None)
}
pub(crate) fn place_from_declarations_with_reachability_cache<'db>(
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
declarations: DeclarationsIterator<'_, 'db>,
reachability_cache: &ReachabilityEvaluationCache<'db>,
) -> PlaceFromDeclarationsResult<'db> {
place_from_declarations_impl(
db,
env,
declarations,
RequiresExplicitReExport::No,
Some(reachability_cache),
)
}
type DeclaredTypeAndConflictingTypes<'db> = (
TypeAndQualifiers<'db>,
Option<Box<indexmap::set::Slice<Type<'db>>>>,
);
/// The result of looking up a declared type from declarations; see [`place_from_declarations`].
#[derive(Debug, Default)]
pub(crate) struct PlaceFromDeclarationsResult<'db> {
place_and_quals: PlaceAndQualifiers<'db>,
conflicting_types: Option<Box<indexmap::set::Slice<Type<'db>>>>,
/// Contains the first reachable declaration for this place, if any.
/// This field is used for backreferences in diagnostics.
pub(crate) first_declaration: Option<Definition<'db>>,
}
impl<'db> PlaceFromDeclarationsResult<'db> {
fn conflict(
place_and_quals: PlaceAndQualifiers<'db>,
conflicting_types: Box<indexmap::set::Slice<Type<'db>>>,
first_declaration: Option<Definition<'db>>,
) -> Self {
PlaceFromDeclarationsResult {
place_and_quals,
conflicting_types: Some(conflicting_types),
first_declaration,
}
}
pub(crate) fn ignore_conflicting_declarations(self) -> PlaceAndQualifiers<'db> {
self.place_and_quals
}
pub(crate) fn into_place_and_conflicting_declarations(
self,
) -> (
PlaceAndQualifiers<'db>,
Option<Box<indexmap::set::Slice<Type<'db>>>>,
) {
(self.place_and_quals, self.conflicting_types)
}
}
/// A type with declaredness information, and a set of type qualifiers.
///
/// This is used to represent the result of looking up the declared type. Consider this
/// example:
/// ```py
/// class C:
/// if flag:
/// variable: ClassVar[int]
/// ```
/// If we look up the declared type of `variable` in the scope of class `C`, we will get
/// the type `int`, a "declaredness" of [`Definedness::PossiblyUndefined`], and the information
/// that this comes with a [`CLASS_VAR`] type qualifier.
///
/// [`CLASS_VAR`]: crate::types::TypeQualifiers::CLASS_VAR
#[derive(
Debug, Clone, Default, Copy, Hash, PartialEq, Eq, get_size2::GetSize, salsa::SalsaValue,
)]
pub(crate) struct PlaceAndQualifiers<'db> {
pub(crate) place: Place<'db>,
pub(crate) qualifiers: TypeQualifiers,
}
impl<'db> PlaceAndQualifiers<'db> {
pub(crate) fn unbound() -> Self {
Self::default()
}
pub(crate) fn is_undefined(&self) -> bool {
self.place.is_undefined()
}
pub(crate) fn ignore_possibly_undefined(&self) -> Option<Type<'db>> {
self.place.ignore_possibly_undefined()
}
/// Returns `true` if the place has a `ClassVar` type qualifier.
pub(crate) fn is_class_var(&self) -> bool {
self.qualifiers.contains(TypeQualifiers::CLASS_VAR)
}
/// Returns `true` if the place has a `InitVar` type qualifier.
pub(crate) fn is_init_var(&self) -> bool {
self.qualifiers.contains(TypeQualifiers::INIT_VAR)
}
/// Returns `true` if the place has a `Required` type qualifier.
pub(crate) fn is_required(&self) -> bool {
self.qualifiers.contains(TypeQualifiers::REQUIRED)
}
/// Returns `true` if the place has a `NotRequired` type qualifier.
pub(crate) fn is_not_required(&self) -> bool {
self.qualifiers.contains(TypeQualifiers::NOT_REQUIRED)
}
/// Returns `true` if the place has a `ReadOnly` type qualifier.
pub(crate) fn is_read_only(&self) -> bool {
self.qualifiers.contains(TypeQualifiers::READ_ONLY)
}
/// Returns `Some(…)` if the place is qualified with `typing.Final` without a specified type.
pub(crate) fn is_bare_final(&self) -> Option<TypeQualifiers> {
match self {
PlaceAndQualifiers { place, qualifiers }
if (qualifiers.contains(TypeQualifiers::FINAL)
&& place
.ignore_possibly_undefined()
.is_some_and(|ty| ty.is_unknown())) =>
{
Some(*qualifiers)
}
_ => None,
}
}
#[must_use]
pub(crate) fn map_type(
self,
f: impl FnOnce(Type<'db>) -> Type<'db>,
) -> PlaceAndQualifiers<'db> {
PlaceAndQualifiers {
place: self.place.map_type(f),
qualifiers: self.qualifiers,
}
}
/// Transform place and qualifiers into a [`LookupResult`],
/// a [`Result`] type in which the `Ok` variant represents a definitely defined place
/// and the `Err` variant represents a place that is either definitely or possibly undefined.
///
/// For places whose public type differs from their raw stored type, this applies the
/// public-type policy lazily during lookup.
pub(crate) fn into_lookup_result(
self,
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
) -> LookupResult<'db> {
match self {
PlaceAndQualifiers {
place: Place::Defined(place),
qualifiers,
} => {
let ty = place.public_type_policy.apply_if_needed(db, env, place.ty);
let type_and_qualifiers = TypeAndQualifiers::new(ty, place.origin, qualifiers)
.with_provenance(place.provenance);
match place.definedness {
Definedness::AlwaysDefined => Ok(type_and_qualifiers),
Definedness::PossiblyUndefined => {
Err(LookupError::PossiblyUndefined(type_and_qualifiers))
}