Skip to content

Commit

Permalink
Rollup merge of #107108 - sulami:issue-83968-doc-alias-typo-suggestio…
Browse files Browse the repository at this point in the history
…ns, r=compiler-errors

Consider doc(alias) when providing typo suggestions

This means that

```rust
impl Foo {
    #[doc(alias = "quux")]
    fn bar(&self) {}
}

fn main() {
    (Foo {}).quux();
}
```

will suggest `bar`. This currently uses the "there is a method with a similar name" help text, because the point where we choose and emit a suggestion is different from where we gather the suggestions. Changes have mainly been made to the latter.

The selection code will now fall back to aliased candidates, but generally only if there is no candidate that matches based on the existing Levenshtein methodology.

Fixes #83968.
  • Loading branch information
Dylan-DPC authored Jan 23, 2023
2 parents 28081a6 + f908f0b commit f4f3335
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 13 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/method/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub struct NoMatchData<'tcx> {
pub unsatisfied_predicates:
Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>,
pub out_of_scope_traits: Vec<DefId>,
pub lev_candidate: Option<ty::AssocItem>,
pub similar_candidate: Option<ty::AssocItem>,
pub mode: probe::Mode,
}

Expand Down
49 changes: 45 additions & 4 deletions compiler/rustc_hir_typeck/src/method/probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
static_candidates: Vec::new(),
unsatisfied_predicates: Vec::new(),
out_of_scope_traits: Vec::new(),
lev_candidate: None,
similar_candidate: None,
mode,
}));
}
Expand Down Expand Up @@ -1076,13 +1076,13 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
if let Some((kind, def_id)) = private_candidate {
return Err(MethodError::PrivateMatch(kind, def_id, out_of_scope_traits));
}
let lev_candidate = self.probe_for_lev_candidate()?;
let similar_candidate = self.probe_for_similar_candidate()?;

Err(MethodError::NoMatch(NoMatchData {
static_candidates,
unsatisfied_predicates,
out_of_scope_traits,
lev_candidate,
similar_candidate,
mode: self.mode,
}))
}
Expand Down Expand Up @@ -1787,7 +1787,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
/// Similarly to `probe_for_return_type`, this method attempts to find the best matching
/// candidate method where the method name may have been misspelled. Similarly to other
/// Levenshtein based suggestions, we provide at most one such suggestion.
fn probe_for_lev_candidate(&mut self) -> Result<Option<ty::AssocItem>, MethodError<'tcx>> {
fn probe_for_similar_candidate(&mut self) -> Result<Option<ty::AssocItem>, MethodError<'tcx>> {
debug!("probing for method names similar to {:?}", self.method_name);

let steps = self.steps.clone();
Expand Down Expand Up @@ -1831,6 +1831,12 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
None,
)
}
.or_else(|| {
applicable_close_candidates
.iter()
.find(|cand| self.matches_by_doc_alias(cand.def_id))
.map(|cand| cand.name)
})
.unwrap();
Ok(applicable_close_candidates.into_iter().find(|method| method.name == best_name))
}
Expand Down Expand Up @@ -1981,6 +1987,38 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
}
}

/// Determine if the associated item withe the given DefId matches
/// the desired name via a doc alias.
fn matches_by_doc_alias(&self, def_id: DefId) -> bool {
let Some(name) = self.method_name else { return false; };
let Some(local_def_id) = def_id.as_local() else { return false; };
let hir_id = self.fcx.tcx.hir().local_def_id_to_hir_id(local_def_id);
let attrs = self.fcx.tcx.hir().attrs(hir_id);
for attr in attrs {
let sym::doc = attr.name_or_empty() else { continue; };
let Some(values) = attr.meta_item_list() else { continue; };
for v in values {
if v.name_or_empty() != sym::alias {
continue;
}
if let Some(nested) = v.meta_item_list() {
// #[doc(alias("foo", "bar"))]
for n in nested {
if let Some(lit) = n.lit() && name.as_str() == lit.symbol.as_str() {
return true;
}
}
} else if let Some(meta) = v.meta_item()
&& let Some(lit) = meta.name_value_literal()
&& name.as_str() == lit.symbol.as_str() {
// #[doc(alias = "foo")]
return true;
}
}
}
false
}

/// Finds the method with the appropriate name (or return type, as the case may be). If
/// `allow_similar_names` is set, find methods with close-matching names.
// The length of the returned iterator is nearly always 0 or 1 and this
Expand All @@ -1996,6 +2034,9 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
if !self.is_relevant_kind_for_mode(x.kind) {
return false;
}
if self.matches_by_doc_alias(x.def_id) {
return true;
}
match lev_distance_with_substrings(name.as_str(), x.name.as_str(), max_dist)
{
Some(d) => d > 0,
Expand Down
16 changes: 8 additions & 8 deletions compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let ty_str = with_forced_trimmed_paths!(self.ty_to_string(rcvr_ty));
let is_method = mode == Mode::MethodCall;
let unsatisfied_predicates = &no_match_data.unsatisfied_predicates;
let lev_candidate = no_match_data.lev_candidate;
let similar_candidate = no_match_data.similar_candidate;
let item_kind = if is_method {
"method"
} else if rcvr_ty.is_enum() {
Expand Down Expand Up @@ -937,7 +937,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// give a helping note that it has to be called as `(x.f)(...)`.
if let SelfSource::MethodCall(expr) = source {
if !self.suggest_calling_field_as_fn(span, rcvr_ty, expr, item_name, &mut err)
&& lev_candidate.is_none()
&& similar_candidate.is_none()
&& !custom_span_label
{
label_span_not_found(&mut err);
Expand Down Expand Up @@ -1015,20 +1015,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if fallback_span {
err.span_label(span, msg);
}
} else if let Some(lev_candidate) = lev_candidate {
} else if let Some(similar_candidate) = similar_candidate {
// Don't emit a suggestion if we found an actual method
// that had unsatisfied trait bounds
if unsatisfied_predicates.is_empty() {
let def_kind = lev_candidate.kind.as_def_kind();
let def_kind = similar_candidate.kind.as_def_kind();
// Methods are defined within the context of a struct and their first parameter is always self,
// which represents the instance of the struct the method is being called on
// Associated functions don’t take self as a parameter and
// they are not methods because they don’t have an instance of the struct to work with.
if def_kind == DefKind::AssocFn && lev_candidate.fn_has_self_parameter {
if def_kind == DefKind::AssocFn && similar_candidate.fn_has_self_parameter {
err.span_suggestion(
span,
"there is a method with a similar name",
lev_candidate.name,
similar_candidate.name,
Applicability::MaybeIncorrect,
);
} else {
Expand All @@ -1037,9 +1037,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&format!(
"there is {} {} with a similar name",
def_kind.article(),
def_kind.descr(lev_candidate.def_id),
def_kind.descr(similar_candidate.def_id),
),
lev_candidate.name,
similar_candidate.name,
Applicability::MaybeIncorrect,
);
}
Expand Down
11 changes: 11 additions & 0 deletions tests/ui/methods/method-not-found-but-doc-alias.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
struct Foo;

impl Foo {
#[doc(alias = "quux")]
fn bar(&self) {}
}

fn main() {
Foo.quux();
//~^ ERROR no method named `quux` found for struct `Foo` in the current scope
}
12 changes: 12 additions & 0 deletions tests/ui/methods/method-not-found-but-doc-alias.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
error[E0599]: no method named `quux` found for struct `Foo` in the current scope
--> $DIR/method-not-found-but-doc-alias.rs:9:9
|
LL | struct Foo;
| ---------- method `quux` not found for this struct
...
LL | Foo.quux();
| ^^^^ help: there is a method with a similar name: `bar`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0599`.

0 comments on commit f4f3335

Please sign in to comment.