Skip to content

Commit bfe82cd

Browse files
committed
Auto merge of rust-lang#14036 - Veykril:write-method-resolution, r=Veykril
Record method resolution for remaining operator expressions This allows goto def and future substituted hover to work for the concrete impls.
2 parents a4d3a4a + 4ff6f38 commit bfe82cd

File tree

13 files changed

+163
-103
lines changed

13 files changed

+163
-103
lines changed

crates/hir-expand/src/name.rs

+1
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,7 @@ pub mod known {
347347
recursion_limit,
348348
feature,
349349
// known methods of lang items
350+
call_once,
350351
eq,
351352
ne,
352353
ge,

crates/hir-ty/src/builder.rs

+16-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ impl<D> TyBuilder<D> {
6363
}
6464

6565
fn build_internal(self) -> (D, Substitution) {
66-
assert_eq!(self.vec.len(), self.param_kinds.len());
66+
assert_eq!(self.vec.len(), self.param_kinds.len(), "{:?}", &self.param_kinds);
6767
for (a, e) in self.vec.iter().zip(self.param_kinds.iter()) {
6868
self.assert_match_kind(a, e);
6969
}
@@ -282,6 +282,21 @@ impl TyBuilder<Tuple> {
282282
let (Tuple(size), subst) = self.build_internal();
283283
TyKind::Tuple(size, subst).intern(Interner)
284284
}
285+
286+
pub fn tuple_with<I>(elements: I) -> Ty
287+
where
288+
I: IntoIterator<Item = Ty>,
289+
<I as IntoIterator>::IntoIter: ExactSizeIterator,
290+
{
291+
let elements = elements.into_iter();
292+
let len = elements.len();
293+
let mut b =
294+
TyBuilder::new(Tuple(len), iter::repeat(ParamKind::Type).take(len).collect(), None);
295+
for e in elements {
296+
b = b.push(e);
297+
}
298+
b.build()
299+
}
285300
}
286301

287302
impl TyBuilder<TraitId> {

crates/hir-ty/src/infer.rs

+13-13
Original file line numberDiff line numberDiff line change
@@ -938,19 +938,24 @@ impl<'a> InferenceContext<'a> {
938938
self.db.trait_data(trait_).associated_type_by_name(&name![Item])
939939
}
940940

941-
fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
942-
let trait_ = self.resolve_lang_item(LangItem::Try)?.as_trait()?;
941+
fn resolve_output_on(&self, trait_: TraitId) -> Option<TypeAliasId> {
943942
self.db.trait_data(trait_).associated_type_by_name(&name![Output])
944943
}
945944

945+
fn resolve_lang_trait(&self, lang: LangItem) -> Option<TraitId> {
946+
self.resolve_lang_item(lang)?.as_trait()
947+
}
948+
949+
fn resolve_ops_try_output(&self) -> Option<TypeAliasId> {
950+
self.resolve_output_on(self.resolve_lang_trait(LangItem::Try)?)
951+
}
952+
946953
fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
947-
let trait_ = self.resolve_lang_item(LangItem::Neg)?.as_trait()?;
948-
self.db.trait_data(trait_).associated_type_by_name(&name![Output])
954+
self.resolve_output_on(self.resolve_lang_trait(LangItem::Neg)?)
949955
}
950956

951957
fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
952-
let trait_ = self.resolve_lang_item(LangItem::Not)?.as_trait()?;
953-
self.db.trait_data(trait_).associated_type_by_name(&name![Output])
958+
self.resolve_output_on(self.resolve_lang_trait(LangItem::Not)?)
954959
}
955960

956961
fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
@@ -960,7 +965,7 @@ impl<'a> InferenceContext<'a> {
960965
.lookup(self.db.upcast())
961966
.container
962967
else { return None };
963-
self.db.trait_data(trait_).associated_type_by_name(&name![Output])
968+
self.resolve_output_on(trait_)
964969
}
965970

966971
fn resolve_boxed_box(&self) -> Option<AdtId> {
@@ -998,13 +1003,8 @@ impl<'a> InferenceContext<'a> {
9981003
Some(struct_.into())
9991004
}
10001005

1001-
fn resolve_ops_index(&self) -> Option<TraitId> {
1002-
self.resolve_lang_item(LangItem::Index)?.as_trait()
1003-
}
1004-
10051006
fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
1006-
let trait_ = self.resolve_ops_index()?;
1007-
self.db.trait_data(trait_).associated_type_by_name(&name![Output])
1007+
self.resolve_output_on(self.resolve_lang_trait(LangItem::Index)?)
10081008
}
10091009

10101010
fn resolve_va_list(&self) -> Option<AdtId> {

crates/hir-ty/src/infer/expr.rs

+36-6
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,12 @@ use hir_def::{
1313
ArithOp, Array, BinaryOp, ClosureKind, Expr, ExprId, LabelId, Literal, Statement, UnaryOp,
1414
},
1515
generics::TypeOrConstParamData,
16+
lang_item::LangItem,
1617
path::{GenericArg, GenericArgs},
1718
resolver::resolver_for_expr,
1819
ConstParamId, FieldId, ItemContainerId, Lookup,
1920
};
20-
use hir_expand::name::Name;
21+
use hir_expand::name::{name, Name};
2122
use stdx::always;
2223
use syntax::ast::RangeOp;
2324

@@ -157,7 +158,8 @@ impl<'a> InferenceContext<'a> {
157158
}
158159

159160
// The ok-ish type that is expected from the last expression
160-
let ok_ty = self.resolve_associated_type(try_ty.clone(), self.resolve_ops_try_ok());
161+
let ok_ty =
162+
self.resolve_associated_type(try_ty.clone(), self.resolve_ops_try_output());
161163

162164
self.with_breakable_ctx(BreakableKind::Block, ok_ty.clone(), None, |this| {
163165
this.infer_expr(*body, &Expectation::has_type(ok_ty));
@@ -331,11 +333,18 @@ impl<'a> InferenceContext<'a> {
331333
derefed_callee.callable_sig(self.db).map_or(false, |sig| sig.is_varargs)
332334
|| res.is_none();
333335
let (param_tys, ret_ty) = match res {
334-
Some(res) => {
336+
Some((func, params, ret_ty)) => {
335337
let adjustments = auto_deref_adjust_steps(&derefs);
336338
// FIXME: Handle call adjustments for Fn/FnMut
337339
self.write_expr_adj(*callee, adjustments);
338-
res
340+
if let Some((trait_, func)) = func {
341+
let subst = TyBuilder::subst_for_def(self.db, trait_, None)
342+
.push(callee_ty.clone())
343+
.push(TyBuilder::tuple_with(params.iter().cloned()))
344+
.build();
345+
self.write_method_resolution(tgt_expr, func, subst.clone());
346+
}
347+
(params, ret_ty)
339348
}
340349
None => (Vec::new(), self.err_ty()), // FIXME diagnostic
341350
};
@@ -587,7 +596,18 @@ impl<'a> InferenceContext<'a> {
587596
}
588597
Expr::Try { expr } => {
589598
let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
590-
self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
599+
if let Some(trait_) = self.resolve_lang_trait(LangItem::Try) {
600+
if let Some(func) = self.db.trait_data(trait_).method_by_name(&name!(branch)) {
601+
let subst = TyBuilder::subst_for_def(self.db, trait_, None)
602+
.push(inner_ty.clone())
603+
.build();
604+
self.write_method_resolution(tgt_expr, func, subst.clone());
605+
}
606+
let try_output = self.resolve_output_on(trait_);
607+
self.resolve_associated_type(inner_ty, try_output)
608+
} else {
609+
self.err_ty()
610+
}
591611
}
592612
Expr::Cast { expr, type_ref } => {
593613
// FIXME: propagate the "castable to" expectation (and find a test case that shows this is necessary)
@@ -626,6 +646,7 @@ impl<'a> InferenceContext<'a> {
626646
Expr::UnaryOp { expr, op } => {
627647
let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
628648
let inner_ty = self.resolve_ty_shallow(&inner_ty);
649+
// FIXME: Note down method resolution her
629650
match op {
630651
UnaryOp::Deref => {
631652
autoderef::deref(&mut self.table, inner_ty).unwrap_or_else(|| self.err_ty())
@@ -735,7 +756,7 @@ impl<'a> InferenceContext<'a> {
735756
let base_ty = self.infer_expr_inner(*base, &Expectation::none());
736757
let index_ty = self.infer_expr(*index, &Expectation::none());
737758

738-
if let Some(index_trait) = self.resolve_ops_index() {
759+
if let Some(index_trait) = self.resolve_lang_trait(LangItem::Index) {
739760
let canonicalized = self.canonicalize(base_ty.clone());
740761
let receiver_adjustments = method_resolution::resolve_indexing_op(
741762
self.db,
@@ -748,6 +769,15 @@ impl<'a> InferenceContext<'a> {
748769
adj.apply(&mut self.table, base_ty)
749770
});
750771
self.write_expr_adj(*base, adj);
772+
if let Some(func) =
773+
self.db.trait_data(index_trait).method_by_name(&name!(index))
774+
{
775+
let substs = TyBuilder::subst_for_def(self.db, index_trait, None)
776+
.push(self_ty.clone())
777+
.push(index_ty.clone())
778+
.build();
779+
self.write_method_resolution(tgt_expr, func, substs.clone());
780+
}
751781
self.resolve_associated_type_with_params(
752782
self_ty,
753783
self.resolve_ops_index_output(),

crates/hir-ty/src/infer/unify.rs

+19-6
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use chalk_ir::{
88
};
99
use chalk_solve::infer::ParameterEnaVariableExt;
1010
use ena::unify::UnifyKey;
11+
use hir_def::{FunctionId, TraitId};
1112
use hir_expand::name;
1213
use stdx::never;
1314

@@ -626,18 +627,26 @@ impl<'a> InferenceTable<'a> {
626627
}
627628
}
628629

629-
pub(crate) fn callable_sig(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
630+
pub(crate) fn callable_sig(
631+
&mut self,
632+
ty: &Ty,
633+
num_args: usize,
634+
) -> Option<(Option<(TraitId, FunctionId)>, Vec<Ty>, Ty)> {
630635
match ty.callable_sig(self.db) {
631-
Some(sig) => Some((sig.params().to_vec(), sig.ret().clone())),
636+
Some(sig) => Some((None, sig.params().to_vec(), sig.ret().clone())),
632637
None => self.callable_sig_from_fn_trait(ty, num_args),
633638
}
634639
}
635640

636-
fn callable_sig_from_fn_trait(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
641+
fn callable_sig_from_fn_trait(
642+
&mut self,
643+
ty: &Ty,
644+
num_args: usize,
645+
) -> Option<(Option<(TraitId, FunctionId)>, Vec<Ty>, Ty)> {
637646
let krate = self.trait_env.krate;
638647
let fn_once_trait = FnTrait::FnOnce.get_id(self.db, krate)?;
639-
let output_assoc_type =
640-
self.db.trait_data(fn_once_trait).associated_type_by_name(&name![Output])?;
648+
let trait_data = self.db.trait_data(fn_once_trait);
649+
let output_assoc_type = trait_data.associated_type_by_name(&name![Output])?;
641650

642651
let mut arg_tys = vec![];
643652
let arg_ty = TyBuilder::tuple(num_args)
@@ -675,7 +684,11 @@ impl<'a> InferenceTable<'a> {
675684
if self.db.trait_solve(krate, canonical.value.cast(Interner)).is_some() {
676685
self.register_obligation(obligation.goal);
677686
let return_ty = self.normalize_projection_ty(projection);
678-
Some((arg_tys, return_ty))
687+
Some((
688+
Some(fn_once_trait).zip(trait_data.method_by_name(&name!(call_once))),
689+
arg_tys,
690+
return_ty,
691+
))
679692
} else {
680693
None
681694
}

crates/hir-ty/src/tests/method_resolution.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -986,14 +986,13 @@ fn main() {
986986
}
987987

988988
#[test]
989-
fn method_resolution_encountering_fn_type() {
989+
fn explicit_fn_once_call_fn_item() {
990990
check_types(
991991
r#"
992-
//- /main.rs
992+
//- minicore: fn
993993
fn foo() {}
994-
trait FnOnce { fn call(self); }
995-
fn test() { foo.call(); }
996-
//^^^^^^^^^^ {unknown}
994+
fn test() { foo.call_once(); }
995+
//^^^^^^^^^^^^^^^ ()
997996
"#,
998997
);
999998
}

crates/hir-ty/src/tests/traits.rs

+30-45
Original file line numberDiff line numberDiff line change
@@ -1757,25 +1757,19 @@ fn test() {
17571757
fn fn_trait() {
17581758
check_infer_with_mismatches(
17591759
r#"
1760-
trait FnOnce<Args> {
1761-
type Output;
1762-
1763-
fn call_once(self, args: Args) -> <Self as FnOnce<Args>>::Output;
1764-
}
1760+
//- minicore: fn
17651761
17661762
fn test<F: FnOnce(u32, u64) -> u128>(f: F) {
17671763
f.call_once((1, 2));
17681764
}"#,
17691765
expect![[r#"
1770-
56..60 'self': Self
1771-
62..66 'args': Args
1772-
149..150 'f': F
1773-
155..183 '{ ...2)); }': ()
1774-
161..162 'f': F
1775-
161..180 'f.call...1, 2))': u128
1776-
173..179 '(1, 2)': (u32, u64)
1777-
174..175 '1': u32
1778-
177..178 '2': u64
1766+
38..39 'f': F
1767+
44..72 '{ ...2)); }': ()
1768+
50..51 'f': F
1769+
50..69 'f.call...1, 2))': u128
1770+
62..68 '(1, 2)': (u32, u64)
1771+
63..64 '1': u32
1772+
66..67 '2': u64
17791773
"#]],
17801774
);
17811775
}
@@ -1784,12 +1778,7 @@ fn test<F: FnOnce(u32, u64) -> u128>(f: F) {
17841778
fn fn_ptr_and_item() {
17851779
check_infer_with_mismatches(
17861780
r#"
1787-
#[lang="fn_once"]
1788-
trait FnOnce<Args> {
1789-
type Output;
1790-
1791-
fn call_once(self, args: Args) -> Self::Output;
1792-
}
1781+
//- minicore: fn
17931782
17941783
trait Foo<T> {
17951784
fn foo(&self) -> T;
@@ -1815,27 +1804,25 @@ fn test() {
18151804
opt.map(f);
18161805
}"#,
18171806
expect![[r#"
1818-
74..78 'self': Self
1819-
80..84 'args': Args
1820-
139..143 'self': &Self
1821-
243..247 'self': &Bar<F>
1822-
260..271 '{ loop {} }': (A1, R)
1823-
262..269 'loop {}': !
1824-
267..269 '{}': ()
1825-
355..359 'self': Opt<T>
1826-
361..362 'f': F
1827-
377..388 '{ loop {} }': Opt<U>
1828-
379..386 'loop {}': !
1829-
384..386 '{}': ()
1830-
402..518 '{ ...(f); }': ()
1831-
412..415 'bar': Bar<fn(u8) -> u32>
1832-
441..444 'bar': Bar<fn(u8) -> u32>
1833-
441..450 'bar.foo()': (u8, u32)
1834-
461..464 'opt': Opt<u8>
1835-
483..484 'f': fn(u8) -> u32
1836-
505..508 'opt': Opt<u8>
1837-
505..515 'opt.map(f)': Opt<u32>
1838-
513..514 'f': fn(u8) -> u32
1807+
28..32 'self': &Self
1808+
132..136 'self': &Bar<F>
1809+
149..160 '{ loop {} }': (A1, R)
1810+
151..158 'loop {}': !
1811+
156..158 '{}': ()
1812+
244..248 'self': Opt<T>
1813+
250..251 'f': F
1814+
266..277 '{ loop {} }': Opt<U>
1815+
268..275 'loop {}': !
1816+
273..275 '{}': ()
1817+
291..407 '{ ...(f); }': ()
1818+
301..304 'bar': Bar<fn(u8) -> u32>
1819+
330..333 'bar': Bar<fn(u8) -> u32>
1820+
330..339 'bar.foo()': (u8, u32)
1821+
350..353 'opt': Opt<u8>
1822+
372..373 'f': fn(u8) -> u32
1823+
394..397 'opt': Opt<u8>
1824+
394..404 'opt.map(f)': Opt<u32>
1825+
402..403 'f': fn(u8) -> u32
18391826
"#]],
18401827
);
18411828
}
@@ -2308,10 +2295,8 @@ fn unselected_projection_in_trait_env_no_cycle() {
23082295
// this is not a cycle
23092296
check_types(
23102297
r#"
2311-
//- /main.rs
2312-
trait Index {
2313-
type Output;
2314-
}
2298+
//- minicore: index
2299+
use core::ops::Index;
23152300
23162301
type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
23172302

0 commit comments

Comments
 (0)