Skip to content

Commit 5eef9b2

Browse files
committed
Auto merge of #101990 - clubby789:dont-machine-apply-placeholder-method, r=compiler-errors
Fix auto-application of associated generic functions with placeholders Fixes #101920
2 parents 34115d0 + 7df4b0b commit 5eef9b2

12 files changed

+286
-35
lines changed

compiler/rustc_hir_typeck/src/method/suggest.rs

+115-20
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,17 @@ use rustc_hir::def::DefKind;
1414
use rustc_hir::def_id::DefId;
1515
use rustc_hir::lang_items::LangItem;
1616
use rustc_hir::{ExprKind, Node, QPath};
17-
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
17+
use rustc_infer::infer::{
18+
type_variable::{TypeVariableOrigin, TypeVariableOriginKind},
19+
RegionVariableOrigin,
20+
};
21+
use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
1822
use rustc_middle::traits::util::supertraits;
1923
use rustc_middle::ty::fast_reject::{simplify_type, TreatParams};
2024
use rustc_middle::ty::print::with_crate_prefix;
21-
use rustc_middle::ty::{self, DefIdTree, ToPredicate, Ty, TyCtxt, TypeVisitable};
25+
use rustc_middle::ty::{
26+
self, DefIdTree, GenericArg, GenericArgKind, ToPredicate, Ty, TyCtxt, TypeVisitable,
27+
};
2228
use rustc_middle::ty::{IsSuggestable, ToPolyTraitRef};
2329
use rustc_span::symbol::{kw, sym, Ident};
2430
use rustc_span::Symbol;
@@ -280,7 +286,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
280286
) {
281287
return None;
282288
}
283-
284289
span = item_name.span;
285290

286291
// Don't show generic arguments when the method can't be found in any implementation (#81576).
@@ -393,28 +398,118 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
393398
custom_span_label = true;
394399
}
395400
if static_candidates.len() == 1 {
396-
let ty_str =
397-
if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0) {
398-
// When the "method" is resolved through dereferencing, we really want the
399-
// original type that has the associated function for accurate suggestions.
400-
// (#61411)
401-
let ty = tcx.at(span).type_of(*impl_did);
402-
match (&ty.peel_refs().kind(), &actual.peel_refs().kind()) {
403-
(ty::Adt(def, _), ty::Adt(def_actual, _)) if def == def_actual => {
404-
// Use `actual` as it will have more `substs` filled in.
405-
self.ty_to_value_string(actual.peel_refs())
401+
let mut has_unsuggestable_args = false;
402+
let ty_str = if let Some(CandidateSource::Impl(impl_did)) =
403+
static_candidates.get(0)
404+
{
405+
// When the "method" is resolved through dereferencing, we really want the
406+
// original type that has the associated function for accurate suggestions.
407+
// (#61411)
408+
let ty = tcx.at(span).type_of(*impl_did);
409+
match (&ty.peel_refs().kind(), &actual.peel_refs().kind()) {
410+
(ty::Adt(def, _), ty::Adt(def_actual, substs)) if def == def_actual => {
411+
// If there are any inferred arguments, (`{integer}`), we should replace
412+
// them with underscores to allow the compiler to infer them
413+
let infer_substs: Vec<GenericArg<'_>> = substs
414+
.into_iter()
415+
.map(|arg| {
416+
if !arg.is_suggestable(tcx, true) {
417+
has_unsuggestable_args = true;
418+
match arg.unpack() {
419+
GenericArgKind::Lifetime(_) => self
420+
.next_region_var(RegionVariableOrigin::MiscVariable(
421+
rustc_span::DUMMY_SP,
422+
))
423+
.into(),
424+
GenericArgKind::Type(_) => self
425+
.next_ty_var(TypeVariableOrigin {
426+
span: rustc_span::DUMMY_SP,
427+
kind: TypeVariableOriginKind::MiscVariable,
428+
})
429+
.into(),
430+
GenericArgKind::Const(arg) => self
431+
.next_const_var(
432+
arg.ty(),
433+
ConstVariableOrigin {
434+
span: rustc_span::DUMMY_SP,
435+
kind: ConstVariableOriginKind::MiscVariable,
436+
},
437+
)
438+
.into(),
439+
}
440+
} else {
441+
arg
442+
}
443+
})
444+
.collect::<Vec<_>>();
445+
446+
tcx.value_path_str_with_substs(
447+
def_actual.did(),
448+
tcx.intern_substs(&infer_substs),
449+
)
450+
}
451+
_ => self.ty_to_value_string(ty.peel_refs()),
452+
}
453+
} else {
454+
self.ty_to_value_string(actual.peel_refs())
455+
};
456+
if let SelfSource::MethodCall(_) = source {
457+
let first_arg = if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0) &&
458+
let Some(assoc) = self.associated_value(*impl_did, item_name) {
459+
let sig = self.tcx.fn_sig(assoc.def_id);
460+
if let Some(first) = sig.inputs().skip_binder().get(0) {
461+
if first.peel_refs() == rcvr_ty.peel_refs() {
462+
None
463+
} else {
464+
Some(if first.is_region_ptr() {
465+
if first.is_mutable_ptr() { "&mut " } else { "&" }
466+
} else {
467+
""
468+
})
406469
}
407-
_ => self.ty_to_value_string(ty.peel_refs()),
470+
} else {
471+
None
408472
}
409473
} else {
410-
self.ty_to_value_string(actual.peel_refs())
474+
None
475+
};
476+
let mut applicability = Applicability::MachineApplicable;
477+
let args = if let Some((receiver, args)) = args {
478+
// The first arg is the same kind as the receiver
479+
let explicit_args = if first_arg.is_some() {
480+
std::iter::once(receiver).chain(args.iter()).collect::<Vec<_>>()
481+
} else {
482+
// There is no `Self` kind to infer the arguments from
483+
if has_unsuggestable_args {
484+
applicability = Applicability::HasPlaceholders;
485+
}
486+
args.iter().collect()
487+
};
488+
format!(
489+
"({}{})",
490+
first_arg.unwrap_or(""),
491+
explicit_args
492+
.iter()
493+
.map(|arg| tcx
494+
.sess
495+
.source_map()
496+
.span_to_snippet(arg.span)
497+
.unwrap_or_else(|_| {
498+
applicability = Applicability::HasPlaceholders;
499+
"_".to_owned()
500+
}))
501+
.collect::<Vec<_>>()
502+
.join(", "),
503+
)
504+
} else {
505+
applicability = Applicability::HasPlaceholders;
506+
"(...)".to_owned()
411507
};
412-
if let SelfSource::MethodCall(expr) = source {
413508
err.span_suggestion(
414-
expr.span.to(span),
509+
sugg_span,
415510
"use associated function syntax instead",
416-
format!("{}::{}", ty_str, item_name),
417-
Applicability::MachineApplicable,
511+
format!("{}::{}{}", ty_str, item_name, args),
512+
applicability,
418513
);
419514
} else {
420515
err.help(&format!("try with `{}::{}`", ty_str, item_name,));
@@ -1827,7 +1922,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
18271922
/// Print out the type for use in value namespace.
18281923
fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String {
18291924
match ty.kind() {
1830-
ty::Adt(def, substs) => format!("{}", ty::Instance::new(def.did(), substs)),
1925+
ty::Adt(def, substs) => self.tcx.def_path_str_with_substs(def.did(), substs),
18311926
_ => self.ty_to_string(ty),
18321927
}
18331928
}

compiler/rustc_middle/src/ty/print/pretty.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1659,6 +1659,12 @@ impl<'t> TyCtxt<'t> {
16591659
debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
16601660
FmtPrinter::new(self, ns).print_def_path(def_id, substs).unwrap().into_buffer()
16611661
}
1662+
1663+
pub fn value_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1664+
let ns = guess_def_namespace(self, def_id);
1665+
debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
1666+
FmtPrinter::new(self, ns).print_value_path(def_id, substs).unwrap().into_buffer()
1667+
}
16621668
}
16631669

16641670
impl fmt::Write for FmtPrinter<'_, '_> {

src/test/ui/issues/issue-3707.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ error[E0599]: no method named `boom` found for reference `&Obj` in the current s
22
--> $DIR/issue-3707.rs:10:14
33
|
44
LL | self.boom();
5-
| -----^^^^
5+
| -----^^^^--
66
| | |
77
| | this is an associated function, not a method
8-
| help: use associated function syntax instead: `Obj::boom`
8+
| help: use associated function syntax instead: `Obj::boom()`
99
|
1010
= note: found the following associated functions; to be used as methods, functions must have a `self` parameter
1111
note: the candidate is defined in an impl for the type `Obj`

src/test/ui/suggestions/inner_type2.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,5 @@ fn main() {
2222
let item = std::mem::MaybeUninit::new(Struct { p: 42_u32 });
2323
item.method();
2424
//~^ ERROR no method named `method` found for union `MaybeUninit` in the current scope [E0599]
25-
//~| HELP if this `MaybeUninit::<Struct<u32>>` has been initialized, use one of the `assume_init` methods to access the inner value
25+
//~| HELP if this `MaybeUninit<Struct<u32>>` has been initialized, use one of the `assume_init` methods to access the inner value
2626
}

src/test/ui/suggestions/inner_type2.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ error[E0599]: no method named `method` found for union `MaybeUninit` in the curr
1717
LL | item.method();
1818
| ^^^^^^ method not found in `MaybeUninit<Struct<u32>>`
1919
|
20-
= help: if this `MaybeUninit::<Struct<u32>>` has been initialized, use one of the `assume_init` methods to access the inner value
20+
= help: if this `MaybeUninit<Struct<u32>>` has been initialized, use one of the `assume_init` methods to access the inner value
2121
note: the method `method` exists on the type `Struct<u32>`
2222
--> $DIR/inner_type2.rs:6:5
2323
|

src/test/ui/suggestions/issue-102354.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ LL | fn func() {}
1313
help: use associated function syntax instead
1414
|
1515
LL | i32::func();
16-
| ~~~~~~~~~
16+
| ~~~~~~~~~~~
1717
help: disambiguate the associated function for the candidate
1818
|
1919
LL | <i32 as Trait>::func(x);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
struct GenericAssocMethod<T>(T);
2+
3+
impl<T> GenericAssocMethod<T> {
4+
fn default_hello() {}
5+
}
6+
7+
fn main() {
8+
let x = GenericAssocMethod(33);
9+
x.default_hello();
10+
//~^ ERROR no method named `default_hello` found
11+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
error[E0599]: no method named `default_hello` found for struct `GenericAssocMethod<{integer}>` in the current scope
2+
--> $DIR/suggest-assoc-fn-call-with-turbofish-placeholder.rs:9:7
3+
|
4+
LL | struct GenericAssocMethod<T>(T);
5+
| ---------------------------- method `default_hello` not found for this struct
6+
...
7+
LL | x.default_hello();
8+
| --^^^^^^^^^^^^^--
9+
| | |
10+
| | this is an associated function, not a method
11+
| help: use associated function syntax instead: `GenericAssocMethod::<_>::default_hello()`
12+
|
13+
= note: found the following associated functions; to be used as methods, functions must have a `self` parameter
14+
note: the candidate is defined in an impl for the type `GenericAssocMethod<T>`
15+
--> $DIR/suggest-assoc-fn-call-with-turbofish-placeholder.rs:4:5
16+
|
17+
LL | fn default_hello() {}
18+
| ^^^^^^^^^^^^^^^^^^
19+
20+
error: aborting due to previous error
21+
22+
For more information about this error, try `rustc --explain E0599`.

src/test/ui/suggestions/suggest-assoc-fn-call-with-turbofish-through-deref.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ error[E0599]: no method named `hello` found for struct `RefMut<'_, HasAssocMetho
22
--> $DIR/suggest-assoc-fn-call-with-turbofish-through-deref.rs:11:11
33
|
44
LL | state.hello();
5-
| ------^^^^^
5+
| ------^^^^^--
66
| | |
77
| | this is an associated function, not a method
8-
| help: use associated function syntax instead: `HasAssocMethod::hello`
8+
| help: use associated function syntax instead: `HasAssocMethod::hello()`
99
|
1010
= note: found the following associated functions; to be used as methods, functions must have a `self` parameter
1111
note: the candidate is defined in an impl for the type `HasAssocMethod`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// run-rustfix
2+
3+
struct GenericAssocMethod<T>(T);
4+
5+
impl<T> GenericAssocMethod<T> {
6+
fn default_hello() {}
7+
fn self_ty_hello(_: Self) {}
8+
fn self_ty_ref_hello(_: &Self) {}
9+
}
10+
11+
fn main() {
12+
// Test for inferred types
13+
let x = GenericAssocMethod(33);
14+
GenericAssocMethod::<_>::self_ty_ref_hello(&x);
15+
//~^ ERROR no method named `self_ty_ref_hello` found
16+
GenericAssocMethod::<_>::self_ty_hello(x);
17+
//~^ ERROR no method named `self_ty_hello` found
18+
// Test for known types
19+
let y = GenericAssocMethod(33i32);
20+
GenericAssocMethod::<i32>::default_hello();
21+
//~^ ERROR no method named `default_hello` found
22+
GenericAssocMethod::<i32>::self_ty_ref_hello(&y);
23+
//~^ ERROR no method named `self_ty_ref_hello` found
24+
GenericAssocMethod::<i32>::self_ty_hello(y);
25+
//~^ ERROR no method named `self_ty_hello` found
26+
}
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,26 @@
1+
// run-rustfix
2+
13
struct GenericAssocMethod<T>(T);
24

35
impl<T> GenericAssocMethod<T> {
46
fn default_hello() {}
7+
fn self_ty_hello(_: Self) {}
8+
fn self_ty_ref_hello(_: &Self) {}
59
}
610

711
fn main() {
8-
let x = GenericAssocMethod(33i32);
9-
x.default_hello();
12+
// Test for inferred types
13+
let x = GenericAssocMethod(33);
14+
x.self_ty_ref_hello();
15+
//~^ ERROR no method named `self_ty_ref_hello` found
16+
x.self_ty_hello();
17+
//~^ ERROR no method named `self_ty_hello` found
18+
// Test for known types
19+
let y = GenericAssocMethod(33i32);
20+
y.default_hello();
1021
//~^ ERROR no method named `default_hello` found
22+
y.self_ty_ref_hello();
23+
//~^ ERROR no method named `self_ty_ref_hello` found
24+
y.self_ty_hello();
25+
//~^ ERROR no method named `self_ty_hello` found
1126
}

0 commit comments

Comments
 (0)