Skip to content

Commit 67f1d8f

Browse files
committed
Test all generic args for trait when finding matching impl
1 parent 15d4383 commit 67f1d8f

File tree

3 files changed

+156
-62
lines changed

3 files changed

+156
-62
lines changed

crates/hir-ty/src/method_resolution.rs

+53-29
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ use crate::{
2222
from_foreign_def_id,
2323
infer::{unify::InferenceTable, Adjust, Adjustment, AutoBorrow, OverloadedDeref, PointerCast},
2424
primitive::{FloatTy, IntTy, UintTy},
25-
static_lifetime,
25+
static_lifetime, to_chalk_trait_id,
2626
utils::all_super_traits,
2727
AdtId, Canonical, CanonicalVarKinds, DebruijnIndex, ForeignDefId, InEnvironment, Interner,
28-
Scalar, TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyExt, TyKind,
28+
Scalar, Substitution, TraitEnvironment, TraitRef, TraitRefExt, Ty, TyBuilder, TyExt, TyKind,
2929
};
3030

3131
/// This is used as a key for indexing impls.
@@ -624,52 +624,76 @@ pub(crate) fn iterate_method_candidates<T>(
624624
slot
625625
}
626626

627+
/// Looks up the impl method that actually runs for the trait method `func`.
628+
///
629+
/// Returns `func` if it's not a method defined in a trait or the lookup failed.
627630
pub fn lookup_impl_method(
628-
self_ty: &Ty,
629631
db: &dyn HirDatabase,
630632
env: Arc<TraitEnvironment>,
631-
trait_: TraitId,
633+
func: FunctionId,
634+
fn_subst: Substitution,
635+
) -> FunctionId {
636+
let trait_id = match func.lookup(db.upcast()).container {
637+
ItemContainerId::TraitId(id) => id,
638+
_ => return func,
639+
};
640+
let trait_params = db.generic_params(trait_id.into()).type_or_consts.len();
641+
let fn_params = fn_subst.len(Interner) - trait_params;
642+
let trait_ref = TraitRef {
643+
trait_id: to_chalk_trait_id(trait_id),
644+
substitution: Substitution::from_iter(Interner, fn_subst.iter(Interner).skip(fn_params)),
645+
};
646+
647+
let name = &db.function_data(func).name;
648+
lookup_impl_method_for_trait_ref(trait_ref, db, env, name).unwrap_or(func)
649+
}
650+
651+
fn lookup_impl_method_for_trait_ref(
652+
trait_ref: TraitRef,
653+
db: &dyn HirDatabase,
654+
env: Arc<TraitEnvironment>,
632655
name: &Name,
633656
) -> Option<FunctionId> {
634-
let self_ty_fp = TyFingerprint::for_trait_impl(self_ty)?;
635-
let trait_impls = db.trait_impls_in_deps(env.krate);
636-
let impls = trait_impls.for_trait_and_self_ty(trait_, self_ty_fp);
637-
let mut table = InferenceTable::new(db, env.clone());
638-
find_matching_impl(impls, &mut table, &self_ty).and_then(|data| {
639-
data.items.iter().find_map(|it| match it {
640-
AssocItemId::FunctionId(f) => (db.function_data(*f).name == *name).then(|| *f),
641-
_ => None,
642-
})
657+
let self_ty = trait_ref.self_type_parameter(Interner);
658+
let self_ty_fp = TyFingerprint::for_trait_impl(&self_ty)?;
659+
let impls = db.trait_impls_in_deps(env.krate);
660+
let impls = impls.for_trait_and_self_ty(trait_ref.hir_trait_id(), self_ty_fp);
661+
662+
let table = InferenceTable::new(db, env);
663+
664+
let impl_data = find_matching_impl(impls, table, trait_ref)?;
665+
impl_data.items.iter().find_map(|it| match it {
666+
AssocItemId::FunctionId(f) => (db.function_data(*f).name == *name).then(|| *f),
667+
_ => None,
643668
})
644669
}
645670

646671
fn find_matching_impl(
647672
mut impls: impl Iterator<Item = ImplId>,
648-
table: &mut InferenceTable<'_>,
649-
self_ty: &Ty,
673+
mut table: InferenceTable<'_>,
674+
actual_trait_ref: TraitRef,
650675
) -> Option<Arc<ImplData>> {
651676
let db = table.db;
652677
loop {
653678
let impl_ = impls.next()?;
654679
let r = table.run_in_snapshot(|table| {
655680
let impl_data = db.impl_data(impl_);
656-
let substs =
681+
let impl_substs =
657682
TyBuilder::subst_for_def(db, impl_, None).fill_with_inference_vars(table).build();
658-
let impl_ty = db.impl_self_ty(impl_).substitute(Interner, &substs);
659-
660-
table
661-
.unify(self_ty, &impl_ty)
662-
.then(|| {
663-
let wh_goals =
664-
crate::chalk_db::convert_where_clauses(db, impl_.into(), &substs)
665-
.into_iter()
666-
.map(|b| b.cast(Interner));
683+
let trait_ref = db
684+
.impl_trait(impl_)
685+
.expect("non-trait method in find_matching_impl")
686+
.substitute(Interner, &impl_substs);
667687

668-
let goal = crate::Goal::all(Interner, wh_goals);
688+
if !table.unify(&trait_ref, &actual_trait_ref) {
689+
return None;
690+
}
669691

670-
table.try_obligation(goal).map(|_| impl_data)
671-
})
672-
.flatten()
692+
let wcs = crate::chalk_db::convert_where_clauses(db, impl_.into(), &impl_substs)
693+
.into_iter()
694+
.map(|b| b.cast(Interner));
695+
let goal = crate::Goal::all(Interner, wcs);
696+
table.try_obligation(goal).map(|_| impl_data)
673697
});
674698
if r.is_some() {
675699
break r;

crates/hir/src/source_analyzer.rs

+21-33
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ impl SourceAnalyzer {
270270
let expr_id = self.expr_id(db, &call.clone().into())?;
271271
let (f_in_trait, substs) = self.infer.as_ref()?.method_resolution(expr_id)?;
272272

273-
Some(self.resolve_impl_method_or_trait_def(db, f_in_trait, &substs))
273+
Some(self.resolve_impl_method_or_trait_def(db, f_in_trait, substs))
274274
}
275275

276276
pub(crate) fn resolve_await_to_poll(
@@ -311,7 +311,7 @@ impl SourceAnalyzer {
311311
// HACK: subst for `poll()` coincides with that for `Future` because `poll()` itself
312312
// doesn't have any generic parameters, so we skip building another subst for `poll()`.
313313
let substs = hir_ty::TyBuilder::subst_for_def(db, future_trait, None).push(ty).build();
314-
Some(self.resolve_impl_method_or_trait_def(db, poll_fn, &substs))
314+
Some(self.resolve_impl_method_or_trait_def(db, poll_fn, substs))
315315
}
316316

317317
pub(crate) fn resolve_prefix_expr(
@@ -331,7 +331,7 @@ impl SourceAnalyzer {
331331
// don't have any generic parameters, so we skip building another subst for the methods.
332332
let substs = hir_ty::TyBuilder::subst_for_def(db, op_trait, None).push(ty.clone()).build();
333333

334-
Some(self.resolve_impl_method_or_trait_def(db, op_fn, &substs))
334+
Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
335335
}
336336

337337
pub(crate) fn resolve_index_expr(
@@ -351,7 +351,7 @@ impl SourceAnalyzer {
351351
.push(base_ty.clone())
352352
.push(index_ty.clone())
353353
.build();
354-
Some(self.resolve_impl_method_or_trait_def(db, op_fn, &substs))
354+
Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
355355
}
356356

357357
pub(crate) fn resolve_bin_expr(
@@ -372,7 +372,7 @@ impl SourceAnalyzer {
372372
.push(rhs.clone())
373373
.build();
374374

375-
Some(self.resolve_impl_method_or_trait_def(db, op_fn, &substs))
375+
Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
376376
}
377377

378378
pub(crate) fn resolve_try_expr(
@@ -392,7 +392,7 @@ impl SourceAnalyzer {
392392
// doesn't have any generic parameters, so we skip building another subst for `branch()`.
393393
let substs = hir_ty::TyBuilder::subst_for_def(db, op_trait, None).push(ty.clone()).build();
394394

395-
Some(self.resolve_impl_method_or_trait_def(db, op_fn, &substs))
395+
Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
396396
}
397397

398398
pub(crate) fn resolve_field(
@@ -497,9 +497,12 @@ impl SourceAnalyzer {
497497
None => assoc,
498498
Some(func_ty) => {
499499
if let TyKind::FnDef(_fn_def, subs) = func_ty.kind(Interner) {
500-
self.resolve_impl_method(db, f_in_trait, subs)
501-
.map(AssocItemId::FunctionId)
502-
.unwrap_or(assoc)
500+
self.resolve_impl_method_or_trait_def(
501+
db,
502+
f_in_trait,
503+
subs.clone(),
504+
)
505+
.into()
503506
} else {
504507
assoc
505508
}
@@ -779,37 +782,22 @@ impl SourceAnalyzer {
779782
false
780783
}
781784

782-
fn resolve_impl_method(
785+
fn resolve_impl_method_or_trait_def(
783786
&self,
784787
db: &dyn HirDatabase,
785788
func: FunctionId,
786-
substs: &Substitution,
787-
) -> Option<FunctionId> {
788-
let impled_trait = match func.lookup(db.upcast()).container {
789-
ItemContainerId::TraitId(trait_id) => trait_id,
790-
_ => return None,
791-
};
792-
if substs.is_empty(Interner) {
793-
return None;
794-
}
795-
let self_ty = substs.at(Interner, 0).ty(Interner)?;
789+
substs: Substitution,
790+
) -> FunctionId {
796791
let krate = self.resolver.krate();
797-
let trait_env = self.resolver.body_owner()?.as_generic_def_id().map_or_else(
792+
let owner = match self.resolver.body_owner() {
793+
Some(it) => it,
794+
None => return func,
795+
};
796+
let env = owner.as_generic_def_id().map_or_else(
798797
|| Arc::new(hir_ty::TraitEnvironment::empty(krate)),
799798
|d| db.trait_environment(d),
800799
);
801-
802-
let fun_data = db.function_data(func);
803-
method_resolution::lookup_impl_method(self_ty, db, trait_env, impled_trait, &fun_data.name)
804-
}
805-
806-
fn resolve_impl_method_or_trait_def(
807-
&self,
808-
db: &dyn HirDatabase,
809-
func: FunctionId,
810-
substs: &Substitution,
811-
) -> FunctionId {
812-
self.resolve_impl_method(db, func, substs).unwrap_or(func)
800+
method_resolution::lookup_impl_method(db, env, func, substs)
813801
}
814802

815803
fn lang_trait_fn(

crates/ide/src/goto_definition.rs

+82
Original file line numberDiff line numberDiff line change
@@ -1834,4 +1834,86 @@ fn f() {
18341834
"#,
18351835
);
18361836
}
1837+
1838+
#[test]
1839+
fn goto_bin_op_multiple_impl() {
1840+
check(
1841+
r#"
1842+
//- minicore: add
1843+
struct S;
1844+
impl core::ops::Add for S {
1845+
fn add(
1846+
//^^^
1847+
) {}
1848+
}
1849+
impl core::ops::Add<usize> for S {
1850+
fn add(
1851+
) {}
1852+
}
1853+
1854+
fn f() {
1855+
S +$0 S
1856+
}
1857+
"#,
1858+
);
1859+
1860+
check(
1861+
r#"
1862+
//- minicore: add
1863+
struct S;
1864+
impl core::ops::Add for S {
1865+
fn add(
1866+
) {}
1867+
}
1868+
impl core::ops::Add<usize> for S {
1869+
fn add(
1870+
//^^^
1871+
) {}
1872+
}
1873+
1874+
fn f() {
1875+
S +$0 0usize
1876+
}
1877+
"#,
1878+
);
1879+
}
1880+
1881+
#[test]
1882+
fn path_call_multiple_trait_impl() {
1883+
check(
1884+
r#"
1885+
trait Trait<T> {
1886+
fn f(_: T);
1887+
}
1888+
impl Trait<i32> for usize {
1889+
fn f(_: i32) {}
1890+
//^
1891+
}
1892+
impl Trait<i64> for usize {
1893+
fn f(_: i64) {}
1894+
}
1895+
fn main() {
1896+
usize::f$0(0i32);
1897+
}
1898+
"#,
1899+
);
1900+
1901+
check(
1902+
r#"
1903+
trait Trait<T> {
1904+
fn f(_: T);
1905+
}
1906+
impl Trait<i32> for usize {
1907+
fn f(_: i32) {}
1908+
}
1909+
impl Trait<i64> for usize {
1910+
fn f(_: i64) {}
1911+
//^
1912+
}
1913+
fn main() {
1914+
usize::f$0(0i64);
1915+
}
1916+
"#,
1917+
)
1918+
}
18371919
}

0 commit comments

Comments
 (0)