Skip to content

Commit 4ce1daf

Browse files
committed
Auto merge of #30377 - Wafflespeanut:levenshtein, r=Manishearth
fixes part of #30197
2 parents 3820150 + 51ff171 commit 4ce1daf

File tree

6 files changed

+94
-94
lines changed

6 files changed

+94
-94
lines changed

src/librustc_resolve/lib.rs

+13-32
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ extern crate syntax;
3030
#[no_link]
3131
extern crate rustc_bitflags;
3232
extern crate rustc_front;
33-
3433
extern crate rustc;
3534

3635
use self::PatternBindingMode::*;
@@ -66,7 +65,7 @@ use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
6665
use syntax::attr::AttrMetaMethods;
6766
use syntax::parse::token::{self, special_names, special_idents};
6867
use syntax::codemap::{self, Span, Pos};
69-
use syntax::util::lev_distance::{lev_distance, max_suggestion_distance};
68+
use syntax::util::lev_distance::find_best_match_for_name;
7069

7170
use rustc_front::intravisit::{self, FnKind, Visitor};
7271
use rustc_front::hir;
@@ -91,7 +90,6 @@ use std::cell::{Cell, RefCell};
9190
use std::fmt;
9291
use std::mem::replace;
9392
use std::rc::{Rc, Weak};
94-
use std::usize;
9593

9694
use resolve_imports::{Target, ImportDirective, ImportResolutionPerNamespace};
9795
use resolve_imports::Shadowable;
@@ -118,7 +116,7 @@ macro_rules! execute_callback {
118116

119117
enum SuggestionType {
120118
Macro(String),
121-
Function(String),
119+
Function(token::InternedString),
122120
NotFound,
123121
}
124122

@@ -3422,39 +3420,22 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
34223420
NoSuggestion
34233421
}
34243422

3425-
fn find_best_match_for_name(&mut self, name: &str) -> SuggestionType {
3426-
let mut maybes: Vec<token::InternedString> = Vec::new();
3427-
let mut values: Vec<usize> = Vec::new();
3428-
3423+
fn find_best_match(&mut self, name: &str) -> SuggestionType {
34293424
if let Some(macro_name) = self.session.available_macros
3430-
.borrow().iter().find(|n| n.as_str() == name) {
3425+
.borrow().iter().find(|n| n.as_str() == name) {
34313426
return SuggestionType::Macro(format!("{}!", macro_name));
34323427
}
34333428

3434-
for rib in self.value_ribs.iter().rev() {
3435-
for (&k, _) in &rib.bindings {
3436-
maybes.push(k.as_str());
3437-
values.push(usize::MAX);
3438-
}
3439-
}
3440-
3441-
let mut smallest = 0;
3442-
for (i, other) in maybes.iter().enumerate() {
3443-
values[i] = lev_distance(name, &other);
3429+
let names = self.value_ribs
3430+
.iter()
3431+
.rev()
3432+
.flat_map(|rib| rib.bindings.keys());
34443433

3445-
if values[i] <= values[smallest] {
3446-
smallest = i;
3434+
if let Some(found) = find_best_match_for_name(names, name, None) {
3435+
if name != &*found {
3436+
return SuggestionType::Function(found);
34473437
}
3448-
}
3449-
3450-
let max_distance = max_suggestion_distance(name);
3451-
if !values.is_empty() && values[smallest] <= max_distance && name != &maybes[smallest][..] {
3452-
3453-
SuggestionType::Function(maybes[smallest].to_string())
3454-
3455-
} else {
3456-
SuggestionType::NotFound
3457-
}
3438+
} SuggestionType::NotFound
34583439
}
34593440

34603441
fn resolve_expr(&mut self, expr: &Expr) {
@@ -3568,7 +3549,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
35683549
NoSuggestion => {
35693550
// limit search to 5 to reduce the number
35703551
// of stupid suggestions
3571-
match self.find_best_match_for_name(&path_name) {
3552+
match self.find_best_match(&path_name) {
35723553
SuggestionType::Macro(s) => {
35733554
format!("the macro `{}`", s)
35743555
}

src/librustc_resolve/resolve_imports.rs

+21-5
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ use rustc::middle::privacy::*;
3333
use syntax::ast::{NodeId, Name};
3434
use syntax::attr::AttrMetaMethods;
3535
use syntax::codemap::Span;
36+
use syntax::util::lev_distance::find_best_match_for_name;
3637

3738
use std::mem::replace;
3839
use std::rc::Rc;
3940

40-
4141
/// Contains data for specific types of import directives.
4242
#[derive(Copy, Clone,Debug)]
4343
pub enum ImportDirectiveSubclass {
@@ -425,17 +425,22 @@ impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
425425
};
426426

427427
// We need to resolve both namespaces for this to succeed.
428-
//
429428

430429
let mut value_result = UnknownResult;
431430
let mut type_result = UnknownResult;
431+
let mut lev_suggestion = "".to_owned();
432432

433433
// Search for direct children of the containing module.
434434
build_reduced_graph::populate_module_if_necessary(self.resolver, &target_module);
435435

436436
match target_module.children.borrow().get(&source) {
437437
None => {
438-
// Continue.
438+
let names = target_module.children.borrow();
439+
if let Some(name) = find_best_match_for_name(names.keys(),
440+
&source.as_str(),
441+
None) {
442+
lev_suggestion = format!(". Did you mean to use `{}`?", name);
443+
}
439444
}
440445
Some(ref child_name_bindings) => {
441446
// pub_err makes sure we don't give the same error twice.
@@ -516,6 +521,17 @@ impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
516521
// therefore accurately report that the names are
517522
// unbound.
518523

524+
if lev_suggestion.is_empty() { // skip if we already have a suggestion
525+
let names = target_module.import_resolutions.borrow();
526+
if let Some(name) = find_best_match_for_name(names.keys(),
527+
&source.as_str(),
528+
None) {
529+
lev_suggestion =
530+
format!(". Did you mean to use the re-exported import `{}`?",
531+
name);
532+
}
533+
}
534+
519535
if value_result.is_unknown() {
520536
value_result = UnboundResult;
521537
}
@@ -693,9 +709,9 @@ impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
693709
target);
694710

695711
if value_result.is_unbound() && type_result.is_unbound() {
696-
let msg = format!("There is no `{}` in `{}`",
712+
let msg = format!("There is no `{}` in `{}`{}",
697713
source,
698-
module_to_string(&target_module));
714+
module_to_string(&target_module), lev_suggestion);
699715
return ResolveResult::Failed(Some((directive.span, msg)));
700716
}
701717
let value_used_public = value_used_reexport || value_used_public;

src/librustc_typeck/check/mod.rs

+15-21
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ use syntax::attr::AttrMetaMethods;
121121
use syntax::codemap::{self, Span, Spanned};
122122
use syntax::parse::token::{self, InternedString};
123123
use syntax::ptr::P;
124-
use syntax::util::lev_distance::lev_distance;
124+
use syntax::util::lev_distance::find_best_match_for_name;
125125

126126
use rustc_front::intravisit::{self, Visitor};
127127
use rustc_front::hir;
@@ -2981,28 +2981,22 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>,
29812981
tcx: &ty::ctxt<'tcx>,
29822982
skip : Vec<InternedString>) {
29832983
let name = field.node.as_str();
2984+
let names = variant.fields
2985+
.iter()
2986+
.filter_map(|ref field| {
2987+
// ignore already set fields and private fields from non-local crates
2988+
if skip.iter().any(|x| *x == field.name.as_str()) ||
2989+
(variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
2990+
None
2991+
} else {
2992+
Some(&field.name)
2993+
}
2994+
});
2995+
29842996
// only find fits with at least one matching letter
2985-
let mut best_dist = name.len();
2986-
let mut best = None;
2987-
for elem in &variant.fields {
2988-
let n = elem.name.as_str();
2989-
// ignore already set fields
2990-
if skip.iter().any(|x| *x == n) {
2991-
continue;
2992-
}
2993-
// ignore private fields from non-local crates
2994-
if variant.did.krate != LOCAL_CRATE && elem.vis != Visibility::Public {
2995-
continue;
2996-
}
2997-
let dist = lev_distance(&n, &name);
2998-
if dist < best_dist {
2999-
best = Some(n);
3000-
best_dist = dist;
3001-
}
3002-
}
3003-
if let Some(n) = best {
2997+
if let Some(name) = find_best_match_for_name(names, &name, Some(name.len())) {
30042998
tcx.sess.span_help(field.span,
3005-
&format!("did you mean `{}`?", n));
2999+
&format!("did you mean `{}`?", name));
30063000
}
30073001
}
30083002

src/libsyntax/ext/base.rs

+3-10
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use parse::token;
2424
use parse::token::{InternedString, intern, str_to_ident};
2525
use ptr::P;
2626
use util::small_vector::SmallVector;
27-
use util::lev_distance::{lev_distance, max_suggestion_distance};
27+
use util::lev_distance::find_best_match_for_name;
2828
use ext::mtwt;
2929
use fold::Folder;
3030

@@ -744,15 +744,8 @@ impl<'a> ExtCtxt<'a> {
744744
}
745745

746746
pub fn suggest_macro_name(&mut self, name: &str, span: Span) {
747-
let mut min: Option<(Name, usize)> = None;
748-
let max_dist = max_suggestion_distance(name);
749-
for macro_name in self.syntax_env.names.iter() {
750-
let dist = lev_distance(name, &macro_name.as_str());
751-
if dist <= max_dist && (min.is_none() || min.unwrap().1 > dist) {
752-
min = Some((*macro_name, dist));
753-
}
754-
}
755-
if let Some((suggestion, _)) = min {
747+
let names = &self.syntax_env.names;
748+
if let Some(suggestion) = find_best_match_for_name(names.iter(), name, None) {
756749
self.fileline_help(span, &format!("did you mean `{}!`?", suggestion));
757750
}
758751
}

src/libsyntax/util/lev_distance.rs

+34-20
Original file line numberDiff line numberDiff line change
@@ -8,50 +8,64 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
use ast::Name;
1112
use std::cmp;
13+
use parse::token::InternedString;
1214

13-
pub fn lev_distance(me: &str, t: &str) -> usize {
14-
if me.is_empty() { return t.chars().count(); }
15-
if t.is_empty() { return me.chars().count(); }
15+
/// To find the Levenshtein distance between two strings
16+
pub fn lev_distance(a: &str, b: &str) -> usize {
17+
// cases which don't require further computation
18+
if a.is_empty() {
19+
return b.chars().count();
20+
} else if b.is_empty() {
21+
return a.chars().count();
22+
}
1623

17-
let mut dcol: Vec<_> = (0..t.len() + 1).collect();
24+
let mut dcol: Vec<_> = (0..b.len() + 1).collect();
1825
let mut t_last = 0;
1926

20-
for (i, sc) in me.chars().enumerate() {
21-
27+
for (i, sc) in a.chars().enumerate() {
2228
let mut current = i;
2329
dcol[0] = current + 1;
2430

25-
for (j, tc) in t.chars().enumerate() {
26-
31+
for (j, tc) in b.chars().enumerate() {
2732
let next = dcol[j + 1];
28-
2933
if sc == tc {
3034
dcol[j + 1] = current;
3135
} else {
3236
dcol[j + 1] = cmp::min(current, next);
3337
dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1;
3438
}
35-
3639
current = next;
3740
t_last = j;
3841
}
39-
}
40-
41-
dcol[t_last + 1]
42+
} dcol[t_last + 1]
4243
}
4344

44-
pub fn max_suggestion_distance(name: &str) -> usize {
45-
use std::cmp::max;
46-
// As a loose rule to avoid obviously incorrect suggestions, clamp the
47-
// maximum edit distance we will accept for a suggestion to one third of
48-
// the typo'd name's length.
49-
max(name.len(), 3) / 3
45+
/// To find the best match for a given string from an iterator of names
46+
/// As a loose rule to avoid the obviously incorrect suggestions, it takes
47+
/// an optional limit for the maximum allowable edit distance, which defaults
48+
/// to one-third of the given word
49+
pub fn find_best_match_for_name<'a, T>(iter_names: T,
50+
lookup: &str,
51+
dist: Option<usize>) -> Option<InternedString>
52+
where T: Iterator<Item = &'a Name> {
53+
let max_dist = dist.map_or_else(|| cmp::max(lookup.len(), 3) / 3, |d| d);
54+
iter_names
55+
.filter_map(|name| {
56+
let dist = lev_distance(lookup, &name.as_str());
57+
match dist <= max_dist { // filter the unwanted cases
58+
true => Some((name.as_str(), dist)),
59+
false => None,
60+
}
61+
})
62+
.min_by_key(|&(_, val)| val) // extract the tuple containing the minimum edit distance
63+
.map(|(s, _)| s) // and return only the string
5064
}
5165

5266
#[test]
5367
fn test_lev_distance() {
54-
use std::char::{ from_u32, MAX };
68+
use std::char::{from_u32, MAX};
5569
// Test bytelength agnosticity
5670
for c in (0..MAX as u32)
5771
.filter_map(|i| from_u32(i))

src/test/compile-fail/unresolved-import.rs

+8-6
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,26 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
// ignore-tidy-linelength
12+
1113
use foo::bar; //~ ERROR unresolved import `foo::bar`. Maybe a missing `extern crate foo`?
1214

13-
use bar::baz as x; //~ ERROR unresolved import `bar::baz`. There is no `baz` in `bar`
15+
use bar::Baz as x; //~ ERROR unresolved import `bar::Baz`. There is no `Baz` in `bar`. Did you mean to use `Bar`?
1416

15-
use food::baz; //~ ERROR unresolved import `food::baz`. There is no `baz` in `food`
17+
use food::baz; //~ ERROR unresolved import `food::baz`. There is no `baz` in `food`. Did you mean to use the re-exported import `bag`?
1618

17-
use food::{quux as beans}; //~ ERROR unresolved import `food::quux`. There is no `quux` in `food`
19+
use food::{beens as Foo}; //~ ERROR unresolved import `food::beens`. There is no `beens` in `food`. Did you mean to use the re-exported import `beans`?
1820

1921
mod bar {
20-
struct bar;
22+
pub struct Bar;
2123
}
2224

2325
mod food {
24-
pub use self::zug::baz::{self as bag, quux as beans};
26+
pub use self::zug::baz::{self as bag, foobar as beans};
2527

2628
mod zug {
2729
pub mod baz {
28-
pub struct quux;
30+
pub struct foobar;
2931
}
3032
}
3133
}

0 commit comments

Comments
 (0)