Skip to content

Commit 51ff171

Browse files
committed
Modify the Levenshtein-based suggestions to include imports
1 parent 35b6461 commit 51ff171

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
@@ -33,7 +33,6 @@ extern crate syntax;
3333
#[no_link]
3434
extern crate rustc_bitflags;
3535
extern crate rustc_front;
36-
3736
extern crate rustc;
3837

3938
use self::PatternBindingMode::*;
@@ -69,7 +68,7 @@ use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
6968
use syntax::attr::AttrMetaMethods;
7069
use syntax::parse::token::{self, special_names, special_idents};
7170
use syntax::codemap::{self, Span, Pos};
72-
use syntax::util::lev_distance::{lev_distance, max_suggestion_distance};
71+
use syntax::util::lev_distance::find_best_match_for_name;
7372

7473
use rustc_front::intravisit::{self, FnKind, Visitor};
7574
use rustc_front::hir;
@@ -94,7 +93,6 @@ use std::cell::{Cell, RefCell};
9493
use std::fmt;
9594
use std::mem::replace;
9695
use std::rc::{Rc, Weak};
97-
use std::usize;
9896

9997
use resolve_imports::{Target, ImportDirective, ImportResolutionPerNamespace};
10098
use resolve_imports::Shadowable;
@@ -121,7 +119,7 @@ macro_rules! execute_callback {
121119

122120
enum SuggestionType {
123121
Macro(String),
124-
Function(String),
122+
Function(token::InternedString),
125123
NotFound,
126124
}
127125

@@ -3352,39 +3350,22 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
33523350
NoSuggestion
33533351
}
33543352

3355-
fn find_best_match_for_name(&mut self, name: &str) -> SuggestionType {
3356-
let mut maybes: Vec<token::InternedString> = Vec::new();
3357-
let mut values: Vec<usize> = Vec::new();
3358-
3353+
fn find_best_match(&mut self, name: &str) -> SuggestionType {
33593354
if let Some(macro_name) = self.session.available_macros
3360-
.borrow().iter().find(|n| n.as_str() == name) {
3355+
.borrow().iter().find(|n| n.as_str() == name) {
33613356
return SuggestionType::Macro(format!("{}!", macro_name));
33623357
}
33633358

3364-
for rib in self.value_ribs.iter().rev() {
3365-
for (&k, _) in &rib.bindings {
3366-
maybes.push(k.as_str());
3367-
values.push(usize::MAX);
3368-
}
3369-
}
3370-
3371-
let mut smallest = 0;
3372-
for (i, other) in maybes.iter().enumerate() {
3373-
values[i] = lev_distance(name, &other);
3359+
let names = self.value_ribs
3360+
.iter()
3361+
.rev()
3362+
.flat_map(|rib| rib.bindings.keys());
33743363

3375-
if values[i] <= values[smallest] {
3376-
smallest = i;
3364+
if let Some(found) = find_best_match_for_name(names, name, None) {
3365+
if name != &*found {
3366+
return SuggestionType::Function(found);
33773367
}
3378-
}
3379-
3380-
let max_distance = max_suggestion_distance(name);
3381-
if !values.is_empty() && values[smallest] <= max_distance && name != &maybes[smallest][..] {
3382-
3383-
SuggestionType::Function(maybes[smallest].to_string())
3384-
3385-
} else {
3386-
SuggestionType::NotFound
3387-
}
3368+
} SuggestionType::NotFound
33883369
}
33893370

33903371
fn resolve_expr(&mut self, expr: &Expr) {
@@ -3495,7 +3476,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
34953476
NoSuggestion => {
34963477
// limit search to 5 to reduce the number
34973478
// of stupid suggestions
3498-
match self.find_best_match_for_name(&path_name) {
3479+
match self.find_best_match(&path_name) {
34993480
SuggestionType::Macro(s) => {
35003481
format!("the macro `{}`", s)
35013482
}

src/librustc_resolve/resolve_imports.rs

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

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

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

426426
// We need to resolve both namespaces for this to succeed.
427-
//
428427

429428
let mut value_result = UnknownResult;
430429
let mut type_result = UnknownResult;
430+
let mut lev_suggestion = "".to_owned();
431431

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

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

502+
if lev_suggestion.is_empty() { // skip if we already have a suggestion
503+
let names = target_module.import_resolutions.borrow();
504+
if let Some(name) = find_best_match_for_name(names.keys(),
505+
&source.as_str(),
506+
None) {
507+
lev_suggestion =
508+
format!(". Did you mean to use the re-exported import `{}`?",
509+
name);
510+
}
511+
}
512+
497513
if value_result.is_unknown() {
498514
value_result = UnboundResult;
499515
}
@@ -671,9 +687,9 @@ impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
671687
target);
672688

673689
if value_result.is_unbound() && type_result.is_unbound() {
674-
let msg = format!("There is no `{}` in `{}`",
690+
let msg = format!("There is no `{}` in `{}`{}",
675691
source,
676-
module_to_string(&target_module));
692+
module_to_string(&target_module), lev_suggestion);
677693
return ResolveResult::Failed(Some((directive.span, msg)));
678694
}
679695
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
@@ -122,7 +122,7 @@ use syntax::codemap::{self, Span, Spanned};
122122
use syntax::owned_slice::OwnedSlice;
123123
use syntax::parse::token::{self, InternedString};
124124
use syntax::ptr::P;
125-
use syntax::util::lev_distance::lev_distance;
125+
use syntax::util::lev_distance::find_best_match_for_name;
126126

127127
use rustc_front::intravisit::{self, Visitor};
128128
use rustc_front::hir;
@@ -2996,28 +2996,22 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>,
29962996
tcx: &ty::ctxt<'tcx>,
29972997
skip : Vec<InternedString>) {
29982998
let name = field.node.as_str();
2999+
let names = variant.fields
3000+
.iter()
3001+
.filter_map(|ref field| {
3002+
// ignore already set fields and private fields from non-local crates
3003+
if skip.iter().any(|x| *x == field.name.as_str()) ||
3004+
(variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
3005+
None
3006+
} else {
3007+
Some(&field.name)
3008+
}
3009+
});
3010+
29993011
// only find fits with at least one matching letter
3000-
let mut best_dist = name.len();
3001-
let mut best = None;
3002-
for elem in &variant.fields {
3003-
let n = elem.name.as_str();
3004-
// ignore already set fields
3005-
if skip.iter().any(|x| *x == n) {
3006-
continue;
3007-
}
3008-
// ignore private fields from non-local crates
3009-
if variant.did.krate != LOCAL_CRATE && elem.vis != Visibility::Public {
3010-
continue;
3011-
}
3012-
let dist = lev_distance(&n, &name);
3013-
if dist < best_dist {
3014-
best = Some(n);
3015-
best_dist = dist;
3016-
}
3017-
}
3018-
if let Some(n) = best {
3012+
if let Some(name) = find_best_match_for_name(names, &name, Some(name.len())) {
30193013
tcx.sess.span_help(field.span,
3020-
&format!("did you mean `{}`?", n));
3014+
&format!("did you mean `{}`?", name));
30213015
}
30223016
}
30233017

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

@@ -780,15 +780,8 @@ impl<'a> ExtCtxt<'a> {
780780
}
781781

782782
pub fn suggest_macro_name(&mut self, name: &str, span: Span) {
783-
let mut min: Option<(Name, usize)> = None;
784-
let max_dist = max_suggestion_distance(name);
785-
for macro_name in self.syntax_env.names.iter() {
786-
let dist = lev_distance(name, &macro_name.as_str());
787-
if dist <= max_dist && (min.is_none() || min.unwrap().1 > dist) {
788-
min = Some((*macro_name, dist));
789-
}
790-
}
791-
if let Some((suggestion, _)) = min {
783+
let names = &self.syntax_env.names;
784+
if let Some(suggestion) = find_best_match_for_name(names.iter(), name, None) {
792785
self.fileline_help(span, &format!("did you mean `{}!`?", suggestion));
793786
}
794787
}

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)