[ty] Solve validity type context through constraint sets (#28909)

We currently flatten all type context into a single `Type` instance,
which can lose important information about a given type context
constraint. Eventually, we would like `TypeContext` to store a
`ConstraintSet` directly (see
https://github.com/astral-sh/ty/issues/3933 for details), but this PR
takes a small step towards that by adding an addition bit of information
about the origin of a given type context constraint.

Type context originating from a concrete declared type is stored as
`TypeContextKind::Declared`, while type context originating from the
declared upper bound of an outer type variable is stored as
`TypeContext::Validity`, and solved as a validity constraint through the
constraint solver. This slightly changes our heuristics around using
these constraints during generic call inference. In particular, it means
that we don't necessarily prefer the declared type specialization if it
originated from a validity constraint, as opposed to a declared
constraint.

```py
def singleton[T](value: T) -> Sequence[T]:
    return [value]

def bounded[T: Sequence[int]](value: T) -> T:
    return value

def _(value: Any):
    x: Sequence[int] = reveal_type(singleton(value))  # revealed: Sequence[int]
    
    # TODO: This should be `Sequence[Any & int]`
    reveal_type(bounded(singleton(value))))  # revealed: Sequence[Any]
```

This PR also improves our generic call inference in various places due
to partially migrating to the new solver, e.g.,

```py
def bounded[T: list[int]](value: T) -> T:
    return value

def from_callback[T](f: Callable[[T], None]) -> list[T]:
    return []

def _(f: Callable[[object], None]):
    reveal_type(bounded(from_callback(f)))  # main: Unknown, now: list[int]
```

The full migration for all type context will be completed by
https://github.com/astral-sh/ruff/pull/26680.
This commit is contained in:
Ibraheem Ahmed
2026-10-06 14:05:42 -04:00
committed by GitHub
parent d843705f90
commit 9afd56f70a
15 changed files with 331 additions and 94 deletions
@@ -769,6 +769,149 @@ def forwarded[T](x: T, cond: bool) -> T | list[T]:
return x if cond else [x]
```
## Upper-bound type context
The declared upper bound of a type variable provides type context for a nested generic call:
```py
def singleton[T](value: T) -> list[T]:
return [value]
def bounded[T: list[int]](value: T) -> T:
return value
reveal_type(singleton(True)) # revealed: list[bool]
reveal_type(bounded(singleton(True))) # revealed: list[int]
```
Declared upper bounds also restrict the range of an inferred gradual solution:
```py
from collections.abc import Callable, Sequence
from typing import Any
def singleton_sequence[T](value: T) -> Sequence[T]:
return [value]
def bounded_sequence[T: Sequence[int]](value: T) -> T:
return value
def consumer[T](value: T) -> Callable[[T], None]:
return lambda _: None
def bounded_consumer[T: Callable[[int], None]](value: T) -> T:
return value
def _(value: Any):
# TODO: This should be `Sequence[Any & int]`.
reveal_type(bounded_sequence(singleton_sequence(value))) # revealed: Sequence[Any]
# TODO: This should be `list[int]`.
reveal_type(bounded(singleton(value))) # revealed: list[Any | int]
reveal_type(bounded_consumer(consumer(value))) # revealed: (Any | int, /) -> None
```
The argument of a callable is narrowed based on outer type context:
```py
def from_callback[T](f: Callable[[T], None]) -> list[T]:
return []
def _(f: Callable[[object], None]):
reveal_type(from_callback(f)) # revealed: list[object]
reveal_type(bounded(from_callback(f))) # revealed: list[int]
```
Upper bounds also provide context for `TypedDict` and lambda parameters:
```py
from typing import TypedDict
class Payload(TypedDict):
value: int
def payload[T: Payload](value: T) -> T:
return value
def callback[T: Callable[[int], list[int]]](value: T) -> T:
return value
reveal_type(payload({"value": 1})) # revealed: Payload
reveal_type(callback(lambda value: [value])) # revealed: (value: int) -> list[int]
```
As well as propagate through lambda bodies:
```py
def _(value: Any):
f = callback(lambda _: singleton(value))
reveal_type(f(1)) # revealed: list[Any | int]
```
## Upper-bound context without inference evidence
If there are no inferred or declared constraints for a given type variable, it remains unsolved,
despite lower and upper validity bounds:
```py
def empty[T]() -> T:
raise NotImplementedError
def bounded[T: int](value: T) -> T:
return value
reveal_type(bounded(empty())) # revealed: Unknown
def empty_list[T]() -> list[T]:
return []
def bounded_list[T: list[int]](value: T) -> T:
return value
reveal_type(bounded_list(empty_list())) # revealed: list[Unknown]
```
The type variable remains unsolved when the upper-bound context passes through another generic call:
```py
def identity[T](value: T) -> T:
return value
reveal_type(bounded_list(identity(empty_list()))) # revealed: list[Unknown]
```
If an explicit default is provided, it is instead used as the fallback value:
```py
def empty_with_default[T = bool]() -> T:
raise NotImplementedError
reveal_type(bounded(empty_with_default())) # revealed: bool
```
## Upper-bound context with constrained type variables
The solution to a constrained type variable is chosen to satisfy outer validity constraints:
```py
def make[T: (int, str)]() -> T:
raise NotImplementedError
def number[U: int](value: U) -> U:
return value
reveal_type(number(make())) # revealed: int
```
A default is only used when the type variable remains unsolved:
```py
def make_with_default[T: (int, str) = str]() -> T:
raise NotImplementedError
reveal_type(make_with_default()) # revealed: str
reveal_type(number(make_with_default())) # revealed: int
```
## Generic constructors
The same applies to constructors of generic classes:
@@ -501,7 +501,7 @@ impl<'db> CallArgumentTypes<'db> {
fn iter(&self) -> impl Iterator<Item = (TypeContext<'db>, Type<'db>)> {
self.types
.iter()
.map(|(tcx, ty)| (TypeContext::new(Some(*tcx)), *ty))
.map(|(tcx, ty)| (TypeContext::declared(Some(*tcx)), *ty))
.chain(self.fallback_type.map(|ty| (TypeContext::default(), ty)))
}
}
@@ -6007,10 +6007,29 @@ impl<'db> CallInference<'_, 'db> {
};
};
let return_with_tcx = Some(self.return_ty).zip(self.call_expression_tcx.annotation);
let mut builder = SpecializationBuilder::new(db, self.env, constraints, generic_context);
// TODO: ParamSpec and TypeVarTuple inference still uses legacy type mappings, which
// cannot distinguish validity constraints from inference evidence.
let use_legacy_solver = self.call_expression_tcx.is_declared()
|| generic_context
.variables(db)
.any(|typevar| typevar.is_paramspec(db) || typevar.is_typevartuple(db));
let declared_return_context = match self.call_expression_tcx.annotation {
Some(tcx) if !use_legacy_solver => {
let validity = self.return_ty.when_constraint_set_assignable_to(
db,
self.env,
tcx,
constraints,
);
builder.intersect_validity_constraints(validity);
None
}
tcx => tcx,
};
// Type variables for which we inferred a declared type based on a partially specialized
// type from an outer generic context. For these type variables, we may infer types that
// are not assignable to the concrete subset of the declared type, as they may be assignable
@@ -6036,8 +6055,8 @@ impl<'db> CallInference<'_, 'db> {
// tension between type context preferences and argument constraints. If the combined set
// is unsatisfiable, we will fall back to argument constraints alone (which the current
// code does via `assignable_to_declared_type`).
let (preferred_type_mappings, preferred_solutions_incomplete) = return_with_tcx
.and_then(|(return_ty, tcx)| {
let (preferred_type_mappings, preferred_solutions_incomplete) = declared_return_context
.and_then(|tcx| {
if !tcx
.filter_union(db, self.env, |ty| ty.may_prefer_declared_type(db, self.env))
.may_prefer_declared_type(db, self.env)
@@ -6045,7 +6064,8 @@ impl<'db> CallInference<'_, 'db> {
return None;
}
let return_ty = return_ty
let return_ty = self
.return_ty
.discard_disjoint_union_elements(db, self.env, tcx, self.inferable_typevars)
.or_never();
let tcx = tcx
@@ -7354,9 +7374,8 @@ pub(crate) enum ArgumentTypeContext<'db> {
Standard {
/// The raw parameter type from the overload signature.
raw_parameter_type: Type<'db>,
/// The parameter type to use as context, possibly specialized from the call expression's
/// declared type.
parameter_type: Type<'db>,
/// The expected parameter type, possibly specialized from the call expression's context.
context: TypeContext<'db>,
},
ParamSpec {
@@ -7370,12 +7389,12 @@ pub(crate) enum ArgumentTypeContext<'db> {
impl<'db> ArgumentTypeContext<'db> {
/// Creates a context for ordinary parameter annotations.
///
/// `raw_parameter_type` is the lookup key used by later type checking. `parameter_type` is the
/// `raw_parameter_type` is the lookup key used by later type checking. `context` is the
/// possibly-specialized context used to infer the argument expression.
fn standard(raw_parameter_type: Type<'db>, parameter_type: Type<'db>) -> Self {
fn standard(raw_parameter_type: Type<'db>, context: TypeContext<'db>) -> Self {
Self::Standard {
raw_parameter_type,
parameter_type,
context,
}
}
@@ -7394,11 +7413,8 @@ impl<'db> ArgumentTypeContext<'db> {
/// Returns the type context used for inferring the argument expression.
pub(crate) fn type_context(self) -> TypeContext<'db> {
match self {
Self::Standard { parameter_type, .. }
| Self::ParamSpec {
declared_type: parameter_type,
..
} => TypeContext::new(Some(parameter_type)),
Self::Standard { context, .. } => context,
Self::ParamSpec { declared_type, .. } => TypeContext::declared(Some(declared_type)),
}
}
@@ -7408,12 +7424,13 @@ impl<'db> ArgumentTypeContext<'db> {
/// for that type. `ParamSpec` arguments are cached by the concrete forwarded parameter type,
/// but still inserted through their full context so the original `P.args` or `P.kwargs` lookup
/// key is populated too.
pub(crate) fn inference_cache_key(self) -> Type<'db> {
pub(crate) fn inference_cache_key(self) -> TypeContext<'db> {
match self {
Self::Standard {
raw_parameter_type, ..
} => raw_parameter_type,
Self::ParamSpec { declared_type, .. } => declared_type,
raw_parameter_type,
context,
} => context.with_annotation(Some(raw_parameter_type)),
Self::ParamSpec { declared_type, .. } => TypeContext::declared(Some(declared_type)),
}
}
@@ -7948,7 +7965,7 @@ impl<'db> Binding<'db> {
{
return Some(ArgumentTypeContext::standard(
original_parameter_type,
bound,
TypeContext::validity(bound),
));
}
@@ -8001,9 +8018,18 @@ impl<'db> Binding<'db> {
}
}
// A parameter specialized using the declared type of an outer type variable should remain
// as validity type context.
let context =
if !call_expression_tcx.is_declared() && parameter_type != original_parameter_type {
TypeContext::validity(parameter_type)
} else {
TypeContext::declared(Some(parameter_type))
};
Some(ArgumentTypeContext::standard(
original_parameter_type,
parameter_type,
context,
))
}
@@ -770,6 +770,19 @@ impl<'db, 'c> ConstraintSet<'db, 'c> {
Self::from_node(builder, node, source_order)
}
/// Recursively marks the constraint set as providing validity constraints.
pub(crate) fn with_validity_bounds(
self,
db: &'db dyn Db,
env: &ProgramEnvironment<'db>,
) -> Self {
self.map_constraints(|constraint| {
constraint
.with_provenance(ConstraintProvenance::Validity)
.new_node(db, env, &mut self.builder.storage.borrow_mut())
})
}
/// Applies a type mapping to every constraint in this constraint set.
pub(crate) fn apply_type_mapping_impl(
self,
@@ -777,6 +790,15 @@ impl<'db, 'c> ConstraintSet<'db, 'c> {
type_mapping: &TypeMapping<'_, 'db>,
tcx: TypeContext<'db>,
visitor: &ApplyTypeMappingVisitor<'_, 'db>,
) -> Self {
self.map_constraints(|constraint| {
constraint.apply_type_mapping_impl(db, self.builder, type_mapping, tcx, visitor)
})
}
fn map_constraints(
self,
mut map: impl FnMut(Constraint<'db>) -> (NodeId, Option<SourceOrderId>),
) -> Self {
fn rebuild_node(
storage: &mut ConstraintSetStorage<'_>,
@@ -817,8 +839,7 @@ impl<'db, 'c> ConstraintSet<'db, 'c> {
}
// We have to collect this into a temporary vec since we can't hold an open borrow on the
// storage during the apply_type_mapping calls below, since they also need to borrow the
// storage.
// storage during the map calls below, since they also need to borrow the storage.
let storage = self.builder.storage.borrow();
let mut constraints = SmallVec::<[_; 8]>::new();
self.node
@@ -834,12 +855,7 @@ impl<'db, 'c> ConstraintSet<'db, 'c> {
let mut mapped_constraints = FxHashMap::default();
for (constraint_id, constraint) in constraints {
if mapped_constraints.contains_key(&constraint_id) {
continue;
}
let mapped =
constraint.apply_type_mapping_impl(db, self.builder, type_mapping, tcx, visitor);
mapped_constraints.insert(constraint_id, mapped);
mapped_constraints.insert(constraint_id, map(constraint));
}
let mut storage = self.builder.storage.borrow_mut();
@@ -1420,7 +1420,7 @@ impl<'db> Specialization<'db> {
let mut new_materialization_kind = self.materialization_kind(db);
let types = self.map_types(db, |i, typevar, ty| {
let tcx = TypeContext::new(tcx.get(i).copied());
let tcx = TypeContext::declared(tcx.get(i).copied());
if type_mapping.is_structural() {
return ty.apply_type_mapping_impl(db, type_mapping, tcx, visitor);
}
@@ -2772,6 +2772,12 @@ impl<'db, 'c> SpecializationBuilder<'db, 'c> {
self.infer_from_constraint_set(set)
}
/// Adds the provided constraint set as a validity constraint to the generic call.
pub(crate) fn intersect_validity_constraints(&mut self, set: ConstraintSet<'db, 'c>) {
let set = set.with_validity_bounds(self.db, self.env);
self.record_constraint_set(set);
}
/// Build a merged specialization, using a caller-provided hook to select the solution for
/// each typevar. This compatibility API discards correlations and solving completeness.
///
+40 -7
View File
@@ -809,7 +809,23 @@ impl<'db> InferScope<'db> {
}
}
/// The type context for a given expression, namely the type annotation
/// The kind of type context constraint being provided.
#[derive(
Default, Copy, Clone, Debug, PartialEq, Eq, Hash, get_size2::GetSize, salsa::SalsaValue,
)]
enum TypeContextKind {
/// A direct declared type annotation.
#[default]
Declared,
/// The declared upper bound of a type variable.
///
/// Note that unlike a declared type, the upper bound of a type variable acts only as a validity
/// constraint, and does not provide a preferred specialization during generic call inference.
Validity,
}
/// The type context for a given expression, e.g., the type annotation
/// in an annotated assignment.
///
/// Knowing the outer type context when inferring an expression can enable
@@ -819,11 +835,26 @@ impl<'db> InferScope<'db> {
)]
pub(crate) struct TypeContext<'db> {
pub(crate) annotation: Option<Type<'db>>,
kind: TypeContextKind,
}
impl<'db> TypeContext<'db> {
pub(crate) fn new(annotation: Option<Type<'db>>) -> Self {
Self { annotation }
pub(crate) fn declared(annotation: Option<Type<'db>>) -> Self {
Self {
annotation,
kind: TypeContextKind::Declared,
}
}
pub(crate) fn validity(annotation: Type<'db>) -> Self {
Self {
annotation: Some(annotation),
kind: TypeContextKind::Validity,
}
}
pub(crate) fn is_declared(self) -> bool {
matches!(self.kind, TypeContextKind::Declared)
}
/// If the type annotation is a specialized instance of the given `KnownClass`, returns the
@@ -839,9 +870,11 @@ impl<'db> TypeContext<'db> {
}
fn map(self, f: impl FnOnce(Type<'db>) -> Type<'db>) -> Self {
Self {
annotation: self.annotation.map(f),
}
self.with_annotation(self.annotation.map(f))
}
pub(crate) fn with_annotation(self, annotation: Option<Type<'db>>) -> Self {
Self { annotation, ..self }
}
fn is_typealias(&self) -> bool {
@@ -877,7 +910,7 @@ impl<'db> TypeContext<'db> {
impl<'db> From<Type<'db>> for TypeContext<'db> {
fn from(annotation: Type<'db>) -> Self {
Self::new(Some(annotation))
Self::declared(Some(annotation))
}
}
@@ -4423,7 +4423,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
let value_ty = value.as_ref().map(|value| {
self.infer_maybe_standalone_expression(
value,
TypeContext::new(Some(annotated.inner_type())),
TypeContext::declared(Some(annotated.inner_type())),
)
});
@@ -4795,7 +4795,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
let inferred_ty = self.infer_maybe_standalone_expression(
value,
TypeContext::new(Some(declared.inner_type())),
TypeContext::declared(Some(declared.inner_type())),
);
let inferred_ty = if is_pep_613_type_alias && target.is_name_expr() {
// Alias type inference emits the diagnostic, but this runtime value is
@@ -5400,7 +5400,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
return_ty
};
TypeContext::new(Some(context_ty))
TypeContext::declared(Some(context_ty))
})
.unwrap_or_default()
} else {
@@ -5856,7 +5856,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
return None;
}
let narrowed_tcx = TypeContext::new(Some(narrowed_ty));
let narrowed_tcx = call_expression_tcx.with_annotation(Some(narrowed_ty));
let mut speculative_bindings = bindings.clone();
let mut speculative_builder = self.speculate();
@@ -6532,7 +6532,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
&& let Some(peer_ty) = peer_ty
&& prefer_collection_literal_peer_context(db, env, tcx)
{
TypeContext::new(Some(peer_ty))
TypeContext::declared(Some(peer_ty))
} else {
return infer_expression(self, tcx);
};
@@ -7197,7 +7197,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
let mut speculative_builder = self.speculate();
let inferred_ty = speculative_builder
.infer_tuple_expression_impl(tuple, TypeContext::new(Some(*narrowed_ty)));
.infer_tuple_expression_impl(tuple, tcx.with_annotation(Some(*narrowed_ty)));
if inferred_ty.is_assignable_to(db, env, *narrowed_ty) {
self.extend(speculative_builder);
if teardown_expression_cache {
@@ -7290,7 +7290,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
} else {
annotated_elt_ty
};
TypeContext::new(expected)
tcx.with_annotation(expected)
} else {
TypeContext::default()
};
@@ -7431,7 +7431,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
return TypeContext::default();
}
TypeContext::new(
tcx.with_annotation(
tcx.annotation
.and_then(|annotation| self.typed_dict_key_expected_type(annotation)),
)
@@ -7475,7 +7475,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
// the non-`TypedDict` arm of the union.
let mut speculative_builder = self.speculate_without_diagnostics();
has_dict_compatible_fallback = speculative_builder
.infer_dict_expression(dict, TypeContext::new(Some(element)))
.infer_dict_expression(dict, tcx.with_annotation(Some(element)))
.is_assignable_to(db, env, element);
}
}
@@ -7579,7 +7579,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
collection_expr,
elts,
infer_elt_expression,
TypeContext::new(Some(narrowed_ty)),
tcx.with_annotation(Some(narrowed_ty)),
)?;
// Ensure the inferred return type is assignable to the narrowed declared type.
@@ -7845,7 +7845,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
elt_tcx
};
let inferred_elt_ty =
infer_elt_expression(self, (i, elt, TypeContext::new(Some(elt_tcx))));
infer_elt_expression(self, (i, elt, tcx.with_annotation(Some(elt_tcx))));
inferred_elt_tys[i] = Some(inferred_elt_ty);
if !inferred_elt_ty.is_assignable_to(db, env, elt_tcx) {
@@ -8032,7 +8032,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
.as_ref()
.and_then(|inferred_elts| inferred_elts[elts_index][i])
.unwrap_or_else(|| {
infer_elt_expression(self, (i, elt, TypeContext::new(elt_tcx)))
infer_elt_expression(self, (i, elt, tcx.with_annotation(elt_tcx)))
});
// Simplify the inference based on a non-covariant declared type.
@@ -8166,7 +8166,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
}
}
TypeContext::new(yield_tcx.map(|accumulator| accumulator.into_type(db, env)))
tcx.with_annotation(yield_tcx.map(|accumulator| accumulator.into_type(db, env)))
}
fn infer_generator_expression(
@@ -8843,14 +8843,14 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
// return type as type context.
let return_tcx = if let Some(signature) = callable_tcx {
match signature.return_ty {
Type::Dynamic(DynamicType::Unknown) => TypeContext::new(None),
_ => TypeContext::new(Some(signature.return_ty)),
Type::Dynamic(DynamicType::Unknown) => TypeContext::declared(None),
_ => tcx.with_annotation(Some(signature.return_ty)),
}
} else {
// TODO: Useful inference of a lambda's return type will require a different approach,
// which does the inference of the body expression based on arguments at each call site,
// rather than eagerly computing a return type without knowing the argument types.
TypeContext::new(None)
TypeContext::declared(None)
};
let inference = infer_scope_types(self.db(), scope, return_tcx);
@@ -9378,7 +9378,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
let default_ty = if let Some(default) = arguments.args.get(1) {
self.get_or_infer_expression(
default,
TypeContext::new(Some(field.declared_ty)),
TypeContext::declared(Some(field.declared_ty)),
)
} else {
Type::none(db, env)
@@ -9437,7 +9437,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
field.declared_ty,
self.get_or_infer_expression(
default,
TypeContext::new(Some(field.declared_ty)),
TypeContext::declared(Some(field.declared_ty)),
),
)
},
@@ -9449,7 +9449,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
let default = &arguments.args[1];
let default_ty = self.get_or_infer_expression(
default,
TypeContext::new(Some(field.declared_ty)),
TypeContext::declared(Some(field.declared_ty)),
);
TypedDictKeyAssignment {
context: &self.context,
@@ -9941,7 +9941,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
};
let expected_yield_ty = generator_type_params.yield_ty;
let tcx = TypeContext::new(expected_yield_ty);
let tcx = TypeContext::declared(expected_yield_ty);
let yielded_ty = self
.infer_optional_expression(value.as_deref(), tcx)
.unwrap_or_else(|| Type::none(db, env));
@@ -9991,7 +9991,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
};
let return_type_span = enclosing_function.spans(self.db()).return_type;
let tcx = TypeContext::new(outer_expected.yield_ty.map(|yielded_ty| {
let tcx = TypeContext::declared(outer_expected.yield_ty.map(|yielded_ty| {
KnownClass::Iterable.to_specialized_instance(db, env, &[yielded_ty])
}));
let iterable_type = self.infer_expression(value, tcx);
@@ -13121,7 +13121,7 @@ struct AddBinding<'db, 'ast> {
impl<'db, 'ast> AddBinding<'db, 'ast> {
fn type_context(&self) -> TypeContext<'db> {
TypeContext::new(self.declared_ty)
TypeContext::declared(self.declared_ty)
}
fn insert(
@@ -403,7 +403,7 @@ impl<'db> AssignmentAttributeWriteEvaluator<'_, 'db, '_, '_> {
AttributeWriteRequirement::Module(write_ty) => {
if let Some(write_ty) = write_ty {
let value_ty =
self.infer_value(TypeContext::new(Some(*write_ty)), emit_diagnostics);
self.infer_value(TypeContext::declared(Some(*write_ty)), emit_diagnostics);
self.check_type_pair(value_ty, *write_ty, emit_diagnostics)
} else {
self.infer_value(TypeContext::default(), emit_diagnostics);
@@ -422,7 +422,7 @@ impl<'db> AssignmentAttributeWriteEvaluator<'_, 'db, '_, '_> {
} => match write {
Some(ProtocolMemberWriteRequirement::AssignableTo(write_ty)) => {
let value_ty =
self.infer_value(TypeContext::new(Some(*write_ty)), emit_diagnostics);
self.infer_value(TypeContext::declared(Some(*write_ty)), emit_diagnostics);
self.check_type_pair(value_ty, *write_ty, emit_diagnostics)
}
Some(ProtocolMemberWriteRequirement::Descriptor {
@@ -430,7 +430,7 @@ impl<'db> AssignmentAttributeWriteEvaluator<'_, 'db, '_, '_> {
domain,
}) => {
let value_ty = self.infer_value(
TypeContext::new(Some(domain.unwrap_or_else(Type::unknown))),
TypeContext::declared(Some(domain.unwrap_or_else(Type::unknown))),
emit_diagnostics,
);
if let Some(domain) = domain
@@ -785,7 +785,7 @@ impl<'db> AssignmentAttributeWriteEvaluator<'_, 'db, '_, '_> {
receiver_ty,
)
{
TypeContext::new(Some(write_ty))
TypeContext::declared(Some(write_ty))
} else {
TypeContext::default()
}
@@ -811,7 +811,7 @@ impl<'db> AssignmentAttributeWriteEvaluator<'_, 'db, '_, '_> {
.is_some()
}),
ExplicitAttributeWriteRequirement::AssignableTo { ty, .. } => {
let value_ty = self.infer_value(TypeContext::new(Some(*ty)), false);
let value_ty = self.infer_value(TypeContext::declared(Some(*ty)), false);
self.check_type_pair(value_ty, *ty, emit_diagnostics)
}
}
@@ -918,7 +918,7 @@ impl<'db> AssignmentAttributeWriteEvaluator<'_, 'db, '_, '_> {
if !self.final_assignment_is_valid(object_ty, *qualifiers, emit_diagnostics) {
return false;
}
let value_ty = self.infer_value(TypeContext::new(Some(*ty)), false);
let value_ty = self.infer_value(TypeContext::declared(Some(*ty)), false);
let valid = self.check_type_pair(value_ty, *ty, emit_diagnostics);
if *possibly_missing {
self.report(AssignmentAttributeWriteDiagnostic::PossiblyMissing);
@@ -946,7 +946,7 @@ impl<'db> AssignmentAttributeWriteEvaluator<'_, 'db, '_, '_> {
possibly_missing,
} => {
let value_ty = self.infer_value(
TypeContext::new(Some(*ty)),
TypeContext::declared(Some(*ty)),
matches!(inference, ContextualInference::Commit) && emit_diagnostics,
);
if !self.builder.validate_generic_class_attribute_access(
@@ -319,7 +319,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
let db = self.db();
let update_ty = self.speculate_without_diagnostics().infer_expression(
update,
TypeContext::new(Some(Type::TypedDict(update_context_typed_dict))),
TypeContext::declared(Some(Type::TypedDict(update_context_typed_dict))),
);
let env = self.program_environment();
@@ -366,7 +366,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
.try_typed_dict_pep_584_dunder(value_expr, typed_dict, typed_dict, "__ior__")
.is_some()
{
infer_value_ty(self, TypeContext::new(Some(typed_dict_ty)));
infer_value_ty(self, TypeContext::declared(Some(typed_dict_ty)));
return Some(typed_dict_ty);
}
@@ -376,7 +376,10 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
.try_typed_dict_pep_584_dunder(value_expr, update_patch, typed_dict, "__ior__")
.is_some()
{
infer_value_ty(self, TypeContext::new(Some(Type::TypedDict(update_patch))));
infer_value_ty(
self,
TypeContext::declared(Some(Type::TypedDict(update_patch))),
);
return Some(typed_dict_ty);
}
@@ -839,7 +839,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
let annotation = param_with_default
.annotation()
.map(|annotation| function_signature_expression_type(db, definition, annotation));
self.infer_expression(default, TypeContext::new(annotation));
self.infer_expression(default, TypeContext::declared(annotation));
}
self.deferred_state = previous_deferred_state;
@@ -1813,7 +1813,10 @@ impl KnownFunction {
.is_none_or(|value_expr| {
builder
.speculate_without_diagnostics()
.infer_expression(value_expr, TypeContext::new(Some(casted_type)))
.infer_expression(
value_expr,
TypeContext::declared(Some(casted_type)),
)
.is_disjoint_from(db, env, casted_type)
})
&& let Some(diagnostic) =
@@ -1832,7 +1832,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
&& let Some(expected_ty) = typed_dict.arbitrary_key_mutation_type(db, env)
{
let rhs_value_ty =
infer_rhs_value(self, TypeContext::new(Some(expected_ty)));
infer_rhs_value(self, TypeContext::declared(Some(expected_ty)));
if rhs_value_ty.is_assignable_to(db, env, expected_ty) {
return true;
}
@@ -1902,7 +1902,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
let item = typed_dict.item(db, key);
let value_ty = infer_rhs_value.infer_silent(
self,
TypeContext::new(item.as_ref().map(|item| item.declared_ty)),
TypeContext::declared(item.as_ref().map(|item| item.declared_ty)),
);
if item.is_some() {
@@ -58,7 +58,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
{
let contextual_ty = self
.speculate_without_diagnostics()
.infer_value_expression_impl(expression, TypeContext::new(Some(target)));
.infer_value_expression_impl(expression, TypeContext::declared(Some(target)));
if contextual_ty.is_assignable_to(db, env, target) {
return None;
}
@@ -339,7 +339,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
} = dict;
let key_tcx =
TypeContext::new(self.typed_dict_key_expected_type(Type::TypedDict(typed_dict)));
TypeContext::declared(self.typed_dict_key_expected_type(Type::TypedDict(typed_dict)));
for item in items {
let key_ty = self.infer_optional_expression(item.key.as_ref(), key_tcx);
@@ -351,12 +351,12 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
&& let Some(key) = key_ty.as_string_literal()
&& let Some(field) = typed_dict.item(self.db(), key.value(self.db()))
{
self.infer_expression(&item.value, TypeContext::new(Some(field.declared_ty)))
self.infer_expression(&item.value, TypeContext::declared(Some(field.declared_ty)))
} else if let Some(key_ty) = key_ty {
if key_ty.is_assignable_to(db, env, KnownClass::Str.to_instance(db, env))
&& let Some(value_ty) = typed_dict.arbitrary_key_initialization_type(db, env)
{
self.infer_expression(&item.value, TypeContext::new(Some(value_ty)))
self.infer_expression(&item.value, TypeContext::declared(Some(value_ty)))
} else {
self.infer_expression(&item.value, TypeContext::default())
}
@@ -573,12 +573,12 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
match form {
TypedDictConstructorForm::LiteralOnly(argument) => {
let target_ty = Type::TypedDict(typed_dict);
self.get_or_infer_expression(argument, TypeContext::new(Some(target_ty)));
self.get_or_infer_expression(argument, TypeContext::declared(Some(target_ty)));
return;
}
TypedDictConstructorForm::SinglePositional(argument) => {
let target_ty = Type::TypedDict(typed_dict);
self.get_or_infer_expression(argument, TypeContext::new(Some(target_ty)));
self.get_or_infer_expression(argument, TypeContext::declared(Some(target_ty)));
}
TypedDictConstructorForm::MixedPositionalAndKeywords => {
let unpacked_keyword_types =
@@ -595,7 +595,10 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
);
let positional_target = typed_dict_with_relaxed_keys(db, typed_dict, &keyword_keys);
let target_ty = Type::TypedDict(positional_target);
self.get_or_infer_expression(&arguments.args[0], TypeContext::new(Some(target_ty)));
self.get_or_infer_expression(
&arguments.args[0],
TypeContext::declared(Some(target_ty)),
);
}
TypedDictConstructorForm::MixedLiteralAndKeywords(dict_expr) => {
self.infer_typed_dict_constructor_dict_literal_values(typed_dict, dict_expr);
@@ -634,7 +637,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
.arg
.as_ref()
.and_then(|arg_name| typed_dict.item(self.db(), arg_name.id.as_str()))
.map(|field| TypeContext::new(Some(field.declared_ty)))
.map(|field| TypeContext::declared(Some(field.declared_ty)))
.unwrap_or_default();
self.get_or_infer_expression(&keyword.value, value_tcx);
}
@@ -654,7 +657,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
let db = self.db();
let env = self.program_environment();
let key_tcx =
TypeContext::new(self.typed_dict_key_expected_type(Type::TypedDict(typed_dict)));
TypeContext::declared(self.typed_dict_key_expected_type(Type::TypedDict(typed_dict)));
for item in &dict_expr.items {
let key_ty = item
@@ -664,10 +667,10 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
let value_tcx = if let Some(key) = key_ty.and_then(Type::as_string_literal)
&& let Some(field) = typed_dict.item(self.db(), key.value(self.db()))
{
TypeContext::new(Some(field.declared_ty))
TypeContext::declared(Some(field.declared_ty))
} else if let Some(key_ty) = key_ty {
if key_ty.is_assignable_to(db, env, KnownClass::Str.to_instance(db, env)) {
TypeContext::new(typed_dict.arbitrary_key_initialization_type(db, env))
TypeContext::declared(typed_dict.arbitrary_key_initialization_type(db, env))
} else {
TypeContext::default()
}
+1 -1
View File
@@ -1057,7 +1057,7 @@ impl<'db> FixedLengthTuple<Type<'db>> {
Some(tuple) => Either::Left(
tuple
.iter_element_types(db)
.map(|tcx| TypeContext::new(Some(tcx))),
.map(|tcx| TypeContext::declared(Some(tcx))),
),
};
@@ -2649,8 +2649,10 @@ pub(super) fn validate_typed_dict_constructor<'db, 'ast>(
&& positional_target.openness(db).is_implicitly_open();
let positional_target_ty = Type::TypedDict(positional_target);
let positional_inference_target_ty = Type::TypedDict(positional_inference_target);
let arg_ty =
expression_type_fn(arg, TypeContext::new(Some(positional_inference_target_ty)));
let arg_ty = expression_type_fn(
arg,
TypeContext::declared(Some(positional_inference_target_ty)),
);
if let Some(provided_keys) = validate_from_typed_dict_argument(
context,
@@ -2702,7 +2704,7 @@ pub(super) fn validate_typed_dict_constructor<'db, 'ast>(
// Assignability already checks for required keys and type compatibility,
// so we don't need separate validation.
let arg = &arguments.args[0];
let arg_ty = expression_type_fn(arg, TypeContext::new(Some(typed_dict_ty)));
let arg_ty = expression_type_fn(arg, TypeContext::declared(Some(typed_dict_ty)));
if !arg_ty.is_assignable_to(db, env, typed_dict_ty) {
if let Some(builder) = context.report_lint(&INVALID_ARGUMENT_TYPE, arg) {
@@ -2794,7 +2796,7 @@ fn validate_from_keywords<'db, 'ast>(
let value_tcx = typed_dict
.item(db, arg_name.id.as_str())
.map(|field| TypeContext::new(Some(field.declared_ty)))
.map(|field| TypeContext::declared(Some(field.declared_ty)))
.unwrap_or_default();
let value_ty = expression_type_fn(&keyword.value, value_tcx);
TypedDictKeyAssignment {
@@ -2877,8 +2879,10 @@ fn validate_merged_dict_literal<'db, 'ast>(
if let Some(expected_ty) = typed_dict
.arbitrary_key_initialization_type_excluding(db, env, shadowed_keys)
{
let value_ty =
expression_type_fn(&item.value, TypeContext::new(Some(expected_ty)));
let value_ty = expression_type_fn(
&item.value,
TypeContext::declared(Some(expected_ty)),
);
if !value_ty.is_assignable_to(db, env, expected_ty) {
valid = false;
if let Some(builder) =
@@ -2920,7 +2924,7 @@ fn validate_merged_dict_literal<'db, 'ast>(
if !is_shadowed {
let value_tcx = typed_dict
.item(db, key.as_str())
.map(|field| TypeContext::new(Some(field.declared_ty)))
.map(|field| TypeContext::declared(Some(field.declared_ty)))
.unwrap_or_default();
let value_ty = expression_type_fn(&item.value, value_tcx);
valid &= TypedDictKeyAssignment {