[ty] Improve disambiguation of types in many cases (#22019)

This commit is contained in:
Alex Waygood
2025-12-17 11:41:07 +00:00
committed by GitHub
parent 85af715880
commit 764ad8b29b
8 changed files with 173 additions and 12 deletions

View File

@@ -21,7 +21,6 @@ use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::{SmallVec, smallvec, smallvec_inline};
use super::{Argument, CallArguments, CallError, CallErrorKind, InferContext, Signature, Type};
use crate::Program;
use crate::db::Db;
use crate::dunder_all::dunder_all_names;
use crate::module_resolver::KnownModule;
@@ -52,6 +51,7 @@ use crate::types::{
enums, list_members, todo_type,
};
use crate::unpack::EvaluationMode;
use crate::{DisplaySettings, Program};
use ruff_db::diagnostic::{Annotation, Diagnostic, SubDiagnostic, SubDiagnosticSeverity};
use ruff_python_ast::{self as ast, ArgOrKeyword, PythonVersion};
@@ -4156,8 +4156,13 @@ impl<'db> BindingError<'db> {
return;
};
let provided_ty_display = provided_ty.display(context.db());
let expected_ty_display = expected_ty.display(context.db());
let display_settings = DisplaySettings::from_possibly_ambiguous_types(
context.db(),
[provided_ty, expected_ty],
);
let provided_ty_display =
provided_ty.display_with(context.db(), display_settings.clone());
let expected_ty_display = expected_ty.display_with(context.db(), display_settings);
let mut diag = builder.into_diagnostic(format_args!(
"Argument{} is incorrect",

View File

@@ -76,14 +76,15 @@ impl<'db> DisplaySettings<'db> {
}
#[must_use]
pub fn from_possibly_ambiguous_types(
db: &'db dyn Db,
types: impl IntoIterator<Item = Type<'db>>,
) -> Self {
pub fn from_possibly_ambiguous_types<I, T>(db: &'db dyn Db, types: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<Type<'db>>,
{
let collector = AmbiguousClassCollector::default();
for ty in types {
collector.visit_type(db, ty);
collector.visit_type(db, ty.into());
}
Self {
@@ -422,6 +423,8 @@ impl<'db> super::visitor::TypeVisitor<'db> for AmbiguousClassCollector<'db> {
inner: Protocol::FromClass(class),
..
}) => return self.visit_type(db, Type::from(class)),
// no need to recurse into TypeVar bounds/constraints
Type::TypeVar(_) => return,
_ => {}
}
@@ -439,7 +442,7 @@ impl<'db> Type<'db> {
pub fn display(self, db: &'db dyn Db) -> DisplayType<'db> {
DisplayType {
ty: self,
settings: DisplaySettings::default(),
settings: DisplaySettings::from_possibly_ambiguous_types(db, [self]),
db,
}
}