Skip to content

Commit d30dfb0

Browse files
committed
Provide more and more accurate suggestions when calling the wrong method
``` error[E0308]: mismatched types --> $DIR/rustc_confusables_std_cases.rs:20:14 | LL | x.append(42); | ------ ^^ expected `&mut Vec<{integer}>`, found integer | | | arguments to this method are incorrect | = note: expected mutable reference `&mut Vec<{integer}>` found type `{integer}` note: method defined here --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL help: you might have meant to use `push` | LL | x.push(42); | ~~~~ ```
1 parent e13d452 commit d30dfb0

File tree

5 files changed

+189
-31
lines changed

5 files changed

+189
-31
lines changed

compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs

+98-8
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
use crate::coercion::CoerceMany;
22
use crate::errors::SuggestPtrNullMut;
33
use crate::fn_ctxt::arg_matrix::{ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx};
4+
use crate::fn_ctxt::infer::FnCall;
45
use crate::gather_locals::Declaration;
6+
use crate::method::probe::IsSuggestion;
7+
use crate::method::probe::Mode::MethodCall;
8+
use crate::method::probe::ProbeScope::TraitsInScope;
59
use crate::method::MethodCallee;
610
use crate::TupleArgumentsFlag::*;
711
use crate::{errors, Expectation::*};
@@ -532,25 +536,111 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
532536
let callee_ty = callee_expr
533537
.and_then(|callee_expr| self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr));
534538

539+
// Obtain another method on `Self` that have similar name.
540+
let similar_assoc = |call_name: Ident| -> Option<(ty::AssocItem, ty::FnSig<'_>)> {
541+
if let Some(callee_ty) = callee_ty
542+
&& let Ok(Some(assoc)) = self.probe_op(
543+
call_name.span,
544+
MethodCall,
545+
Some(call_name),
546+
None,
547+
IsSuggestion(true),
548+
callee_ty.peel_refs(),
549+
callee_expr.unwrap().hir_id,
550+
TraitsInScope,
551+
|mut ctxt| ctxt.probe_for_similar_candidate(),
552+
)
553+
&& let ty::AssocKind::Fn = assoc.kind
554+
&& assoc.fn_has_self_parameter
555+
{
556+
let fn_sig =
557+
if let ty::Adt(_, args) = callee_ty.peel_refs().kind() {
558+
let args = ty::GenericArgs::identity_for_item(tcx, assoc.def_id)
559+
.rebase_onto(tcx, assoc.container_id(tcx), args);
560+
tcx.fn_sig(assoc.def_id).instantiate(tcx, args)
561+
} else {
562+
tcx.fn_sig(assoc.def_id).instantiate_identity()
563+
};
564+
let fn_sig =
565+
self.instantiate_binder_with_fresh_vars(call_name.span, FnCall, fn_sig);
566+
Some((assoc, fn_sig));
567+
}
568+
None
569+
};
570+
535571
let suggest_confusable = |err: &mut Diagnostic| {
536572
if let Some(call_name) = call_ident
537573
&& let Some(callee_ty) = callee_ty
538574
{
539-
// FIXME: check in the following order
540-
// - methods marked as `rustc_confusables` with the provided arguments (done)
541-
// - methods marked as `rustc_confusables` with the right number of arguments
542-
// - methods marked as `rustc_confusables` (done)
543-
// - methods with the same argument type/count and short levenshtein distance
544-
// - methods with short levenshtein distance
545-
// - methods with the same argument type/count
575+
let input_types: Vec<Ty<'_>> = provided_arg_tys.iter().map(|(ty, _)| *ty).collect();
576+
// Check for other methods in the following order
577+
// - methods marked as `rustc_confusables` with the provided arguments
578+
// - methods with the same argument type/count and short levenshtein distance
579+
// - methods marked as `rustc_confusables` (done)
580+
// - methods with short levenshtein distance
581+
582+
// Look for commonly confusable method names considering arguments.
546583
self.confusable_method_name(
547584
err,
548585
callee_ty.peel_refs(),
549586
call_name,
550-
Some(provided_arg_tys.iter().map(|(ty, _)| *ty).collect()),
587+
Some(input_types.clone()),
551588
)
552589
.or_else(|| {
590+
// Look for method names with short levenshtein distance, considering arguments.
591+
if let Some((assoc, fn_sig)) = similar_assoc(call_name)
592+
&& fn_sig.inputs()[1..]
593+
.iter()
594+
.zip(input_types.iter())
595+
.all(|(expected, found)| self.can_coerce(*expected, *found))
596+
&& fn_sig.inputs()[1..].len() == input_types.len()
597+
{
598+
err.span_suggestion_verbose(
599+
call_name.span,
600+
format!("you might have meant to use `{}`", assoc.name),
601+
assoc.name,
602+
Applicability::MaybeIncorrect,
603+
);
604+
return Some(assoc.name);
605+
}
606+
None
607+
})
608+
.or_else(|| {
609+
// Look for commonly confusable method names disregarding arguments.
553610
self.confusable_method_name(err, callee_ty.peel_refs(), call_name, None)
611+
})
612+
.or_else(|| {
613+
// Look for similarly named methods with levenshtein distance with the right
614+
// number of arguments.
615+
if let Some((assoc, fn_sig)) = similar_assoc(call_name)
616+
&& fn_sig.inputs()[1..].len() == input_types.len()
617+
{
618+
err.span_note(
619+
tcx.def_span(assoc.def_id),
620+
format!(
621+
"there's is a method with similar name `{}`, but the arguments \
622+
don't match",
623+
assoc.name,
624+
),
625+
);
626+
return Some(assoc.name);
627+
}
628+
None
629+
})
630+
.or_else(|| {
631+
// Fallthrough: look for similarly named methods with levenshtein distance.
632+
if let Some((assoc, _)) = similar_assoc(call_name) {
633+
err.span_note(
634+
tcx.def_span(assoc.def_id),
635+
format!(
636+
"there's is a method with similar name `{}`, but their argument \
637+
count doesn't match",
638+
assoc.name,
639+
),
640+
);
641+
return Some(assoc.name);
642+
}
643+
None
554644
});
555645
}
556646
};

compiler/rustc_hir_typeck/src/method/probe.rs

+20-4
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ pub use self::PickKind::*;
5454
#[derive(Clone, Copy, Debug)]
5555
pub struct IsSuggestion(pub bool);
5656

57-
struct ProbeContext<'a, 'tcx> {
57+
pub(crate) struct ProbeContext<'a, 'tcx> {
5858
fcx: &'a FnCtxt<'a, 'tcx>,
5959
span: Span,
6060
mode: Mode,
@@ -355,7 +355,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
355355
.unwrap()
356356
}
357357

358-
fn probe_op<OP, R>(
358+
pub(crate) fn probe_op<OP, R>(
359359
&'a self,
360360
span: Span,
361361
mode: Mode,
@@ -1750,7 +1750,9 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
17501750
/// Similarly to `probe_for_return_type`, this method attempts to find the best matching
17511751
/// candidate method where the method name may have been misspelled. Similarly to other
17521752
/// edit distance based suggestions, we provide at most one such suggestion.
1753-
fn probe_for_similar_candidate(&mut self) -> Result<Option<ty::AssocItem>, MethodError<'tcx>> {
1753+
pub(crate) fn probe_for_similar_candidate(
1754+
&mut self,
1755+
) -> Result<Option<ty::AssocItem>, MethodError<'tcx>> {
17541756
debug!("probing for method names similar to {:?}", self.method_name);
17551757

17561758
self.probe(|_| {
@@ -1942,7 +1944,21 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
19421944
let hir_id = self.fcx.tcx.local_def_id_to_hir_id(local_def_id);
19431945
let attrs = self.fcx.tcx.hir().attrs(hir_id);
19441946
for attr in attrs {
1945-
let sym::doc = attr.name_or_empty() else {
1947+
if sym::doc == attr.name_or_empty() {
1948+
} else if sym::rustc_confusables == attr.name_or_empty() {
1949+
let Some(confusables) = attr.meta_item_list() else {
1950+
continue;
1951+
};
1952+
// #[rustc_confusables("foo", "bar"))]
1953+
for n in confusables {
1954+
if let Some(lit) = n.lit()
1955+
&& name.as_str() == lit.symbol.as_str()
1956+
{
1957+
return true;
1958+
}
1959+
}
1960+
continue;
1961+
} else {
19461962
continue;
19471963
};
19481964
let Some(values) = attr.meta_item_list() else {

compiler/rustc_hir_typeck/src/method/suggest.rs

+49-16
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ use rustc_hir::PatKind::Binding;
2323
use rustc_hir::PathSegment;
2424
use rustc_hir::{ExprKind, Node, QPath};
2525
use rustc_infer::infer::{
26+
self,
2627
type_variable::{TypeVariableOrigin, TypeVariableOriginKind},
2728
RegionVariableOrigin,
2829
};
@@ -1234,7 +1235,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
12341235
label_span_not_found(&mut err);
12351236
}
12361237

1237-
let confusable_suggested = self.confusable_method_name(&mut err, rcvr_ty, item_name, None);
1238+
let confusable_suggested = self.confusable_method_name(
1239+
&mut err,
1240+
rcvr_ty,
1241+
item_name,
1242+
args.map(|args| {
1243+
args.iter()
1244+
.map(|expr| {
1245+
self.node_ty_opt(expr.hir_id).unwrap_or_else(|| {
1246+
self.next_ty_var(TypeVariableOrigin {
1247+
kind: TypeVariableOriginKind::MiscVariable,
1248+
span: expr.span,
1249+
})
1250+
})
1251+
})
1252+
.collect()
1253+
}),
1254+
);
12381255

12391256
// Don't suggest (for example) `expr.field.clone()` if `expr.clone()`
12401257
// can't be called due to `typeof(expr): Clone` not holding.
@@ -1421,9 +1438,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
14211438
err: &mut Diagnostic,
14221439
rcvr_ty: Ty<'tcx>,
14231440
item_name: Ident,
1424-
args: Option<Vec<Ty<'tcx>>>,
1441+
call_args: Option<Vec<Ty<'tcx>>>,
14251442
) -> Option<Symbol> {
1426-
if let ty::Adt(adt, _) = rcvr_ty.kind() {
1443+
if let ty::Adt(adt, adt_args) = rcvr_ty.kind() {
14271444
for inherent_impl_did in self.tcx.inherent_impls(adt.did()).into_iter().flatten() {
14281445
for inherent_method in
14291446
self.tcx.associated_items(inherent_impl_did).in_definition_order()
@@ -1432,29 +1449,45 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
14321449
self.tcx.get_attr(inherent_method.def_id, sym::rustc_confusables)
14331450
&& let Some(candidates) = parse_confusables(attr)
14341451
&& candidates.contains(&item_name.name)
1452+
&& let ty::AssocKind::Fn = inherent_method.kind
14351453
{
1436-
let mut matches_args = args.is_none();
1437-
if let ty::AssocKind::Fn = inherent_method.kind
1438-
&& let Some(ref args) = args
1439-
{
1440-
let fn_sig =
1441-
self.tcx.fn_sig(inherent_method.def_id).instantiate_identity();
1442-
matches_args = fn_sig
1443-
.inputs()
1444-
.skip_binder()
1454+
let args =
1455+
ty::GenericArgs::identity_for_item(self.tcx, inherent_method.def_id)
1456+
.rebase_onto(
1457+
self.tcx,
1458+
inherent_method.container_id(self.tcx),
1459+
adt_args,
1460+
);
1461+
let fn_sig =
1462+
self.tcx.fn_sig(inherent_method.def_id).instantiate(self.tcx, args);
1463+
let fn_sig = self.instantiate_binder_with_fresh_vars(
1464+
item_name.span,
1465+
infer::FnCall,
1466+
fn_sig,
1467+
);
1468+
if let Some(ref args) = call_args
1469+
&& fn_sig.inputs()[1..]
14451470
.iter()
1446-
.skip(1)
14471471
.zip(args.into_iter())
1448-
.all(|(expected, found)| self.can_coerce(*expected, *found));
1449-
}
1450-
if matches_args {
1472+
.all(|(expected, found)| self.can_coerce(*expected, *found))
1473+
&& fn_sig.inputs()[1..].len() == args.len()
1474+
{
14511475
err.span_suggestion_verbose(
14521476
item_name.span,
14531477
format!("you might have meant to use `{}`", inherent_method.name),
14541478
inherent_method.name,
14551479
Applicability::MaybeIncorrect,
14561480
);
14571481
return Some(inherent_method.name);
1482+
} else if let None = call_args {
1483+
err.span_note(
1484+
self.tcx.def_span(inherent_method.def_id),
1485+
format!(
1486+
"you might have meant to use method `{}`",
1487+
inherent_method.name,
1488+
),
1489+
);
1490+
return Some(inherent_method.name);
14581491
}
14591492
}
14601493
}

tests/ui/attributes/rustc_confusables_std_cases.rs

+2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ fn main() {
1717
x.size(); //~ ERROR E0599
1818
//~^ HELP you might have meant to use `len`
1919
//~| HELP there is a method with a similar name
20+
x.append(42); //~ ERROR E0308
21+
//~^ HELP you might have meant to use `push`
2022
String::new().push(""); //~ ERROR E0308
2123
//~^ HELP you might have meant to use `push_str`
2224
String::new().append(""); //~ ERROR E0599

tests/ui/attributes/rustc_confusables_std_cases.stderr

+20-3
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,24 @@ LL | x.resize();
5858
| ~~~~~~
5959

6060
error[E0308]: mismatched types
61-
--> $DIR/rustc_confusables_std_cases.rs:20:24
61+
--> $DIR/rustc_confusables_std_cases.rs:20:14
62+
|
63+
LL | x.append(42);
64+
| ------ ^^ expected `&mut Vec<{integer}>`, found integer
65+
| |
66+
| arguments to this method are incorrect
67+
|
68+
= note: expected mutable reference `&mut Vec<{integer}>`
69+
found type `{integer}`
70+
note: method defined here
71+
--> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
72+
help: you might have meant to use `push`
73+
|
74+
LL | x.push(42);
75+
| ~~~~
76+
77+
error[E0308]: mismatched types
78+
--> $DIR/rustc_confusables_std_cases.rs:22:24
6279
|
6380
LL | String::new().push("");
6481
| ---- ^^ expected `char`, found `&str`
@@ -73,7 +90,7 @@ LL | String::new().push_str("");
7390
| ~~~~~~~~
7491

7592
error[E0599]: no method named `append` found for struct `String` in the current scope
76-
--> $DIR/rustc_confusables_std_cases.rs:22:19
93+
--> $DIR/rustc_confusables_std_cases.rs:24:19
7794
|
7895
LL | String::new().append("");
7996
| ^^^^^^ method not found in `String`
@@ -83,7 +100,7 @@ help: you might have meant to use `push_str`
83100
LL | String::new().push_str("");
84101
| ~~~~~~~~
85102

86-
error: aborting due to 7 previous errors
103+
error: aborting due to 8 previous errors
87104

88105
Some errors have detailed explanations: E0308, E0599.
89106
For more information about an error, try `rustc --explain E0308`.

0 commit comments

Comments
 (0)