Example usage of multiple suggestions

This commit is contained in:
Oliver Schneider 2017-05-10 13:19:29 +02:00
parent 67d762d896
commit e2f781c7ea
No known key found for this signature in database
GPG key ID: A69F8D225B3AD7D9
15 changed files with 113 additions and 91 deletions

View file

@ -81,6 +81,10 @@ impl Emitter for EmitterWriter {
/// maximum number of lines we will print for each error; arbitrary.
pub const MAX_HIGHLIGHT_LINES: usize = 6;
/// maximum number of suggestions to be shown
///
/// Arbitrary, but taken from trait import suggestion limit
pub const MAX_SUGGESTIONS: usize = 4;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorConfig {
@ -1077,20 +1081,22 @@ impl EmitterWriter {
assert!(!lines.lines.is_empty());
for complete in suggestion.splice_lines(cm.borrow()) {
buffer.append(0, &level.to_string(), Style::Level(level.clone()));
buffer.append(0, ": ", Style::HeaderMsg);
self.msg_to_buffer(&mut buffer,
&[(suggestion.msg.to_owned(), Style::NoStyle)],
max_line_num_len,
"suggestion",
Some(Style::HeaderMsg));
buffer.append(0, &level.to_string(), Style::Level(level.clone()));
buffer.append(0, ": ", Style::HeaderMsg);
self.msg_to_buffer(&mut buffer,
&[(suggestion.msg.to_owned(), Style::NoStyle)],
max_line_num_len,
"suggestion",
Some(Style::HeaderMsg));
let suggestions = suggestion.splice_lines(cm.borrow());
let mut row_num = 1;
for complete in suggestions.iter().take(MAX_SUGGESTIONS) {
// print the suggestion without any line numbers, but leave
// space for them. This helps with lining up with previous
// snippets from the actual error being reported.
let mut lines = complete.lines();
let mut row_num = 1;
for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
buffer.append(row_num, line, Style::NoStyle);
@ -1102,6 +1108,10 @@ impl EmitterWriter {
buffer.append(row_num, "...", Style::NoStyle);
}
}
if suggestions.len() > MAX_SUGGESTIONS {
let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
buffer.append(row_num, &msg, Style::NoStyle);
}
emit_to_destination(&buffer.render(), level, &mut self.dst)?;
}
Ok(())

View file

@ -183,7 +183,10 @@ impl CodeSuggestion {
prev_line = fm.get_line(prev_hi.line - 1);
}
for buf in &mut bufs {
push_trailing(buf, prev_line, &prev_hi, None);
// if the replacement already ends with a newline, don't print the next line
if !buf.ends_with('\n') {
push_trailing(buf, prev_line, &prev_hi, None);
}
// remove trailing newline
buf.pop();
}

View file

@ -150,7 +150,7 @@ impl<'a> Resolver<'a> {
view_path.span,
ResolutionError::SelfImportsOnlyAllowedWithin);
} else if source_name == "$crate" && full_path.segments.len() == 1 {
let crate_root = self.resolve_crate_var(source.ctxt);
let crate_root = self.resolve_crate_var(source.ctxt, item.span);
let crate_name = match crate_root.kind {
ModuleKind::Def(_, name) => name,
ModuleKind::Block(..) => unreachable!(),
@ -247,7 +247,7 @@ impl<'a> Resolver<'a> {
// n.b. we don't need to look at the path option here, because cstore already did
let crate_id = self.session.cstore.extern_mod_stmt_cnum(item.id).unwrap();
let module = self.get_extern_crate_root(crate_id);
let module = self.get_extern_crate_root(crate_id, item.span);
self.populate_module_if_necessary(module);
let used = self.process_legacy_macro_imports(item, module, expansion);
let binding =
@ -279,7 +279,7 @@ impl<'a> Resolver<'a> {
no_implicit_prelude: parent.no_implicit_prelude || {
attr::contains_name(&item.attrs, "no_implicit_prelude")
},
..ModuleData::new(Some(parent), module_kind, def_id)
..ModuleData::new(Some(parent), module_kind, def_id, item.span)
});
self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
self.module_map.insert(def_id, module);
@ -314,7 +314,10 @@ impl<'a> Resolver<'a> {
ItemKind::Enum(ref enum_definition, _) => {
let def = Def::Enum(self.definitions.local_def_id(item.id));
let module_kind = ModuleKind::Def(def, ident.name);
let module = self.new_module(parent, module_kind, parent.normal_ancestor_id);
let module = self.new_module(parent,
module_kind,
parent.normal_ancestor_id,
item.span);
self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
for variant in &(*enum_definition).variants {
@ -370,7 +373,10 @@ impl<'a> Resolver<'a> {
// Add all the items within to a new module.
let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name);
let module = self.new_module(parent, module_kind, parent.normal_ancestor_id);
let module = self.new_module(parent,
module_kind,
parent.normal_ancestor_id,
item.span);
self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
self.current_module = module;
}
@ -419,7 +425,7 @@ impl<'a> Resolver<'a> {
let parent = self.current_module;
if self.block_needs_anonymous_module(block) {
let module =
self.new_module(parent, ModuleKind::Block(block.id), parent.normal_ancestor_id);
self.new_module(parent, ModuleKind::Block(block.id), parent.normal_ancestor_id, block.span);
self.block_map.insert(block.id, module);
self.current_module = module; // Descend into the block.
}
@ -431,10 +437,14 @@ impl<'a> Resolver<'a> {
let def = child.def;
let def_id = def.def_id();
let vis = self.session.cstore.visibility(def_id);
let span = child.span;
match def {
Def::Mod(..) | Def::Enum(..) => {
let module = self.new_module(parent, ModuleKind::Def(def, ident.name), def_id);
let module = self.new_module(parent,
ModuleKind::Def(def, ident.name),
def_id,
span);
self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, Mark::root()));
}
Def::Variant(..) | Def::TyAlias(..) => {
@ -454,7 +464,10 @@ impl<'a> Resolver<'a> {
}
Def::Trait(..) => {
let module_kind = ModuleKind::Def(def, ident.name);
let module = self.new_module(parent, module_kind, parent.normal_ancestor_id);
let module = self.new_module(parent,
module_kind,
parent.normal_ancestor_id,
span);
self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, Mark::root()));
for child in self.session.cstore.item_children(def_id) {
@ -483,18 +496,18 @@ impl<'a> Resolver<'a> {
}
}
fn get_extern_crate_root(&mut self, cnum: CrateNum) -> Module<'a> {
fn get_extern_crate_root(&mut self, cnum: CrateNum, span: Span) -> Module<'a> {
let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
let name = self.session.cstore.crate_name(cnum);
let macros_only = self.session.cstore.dep_kind(cnum).macros_only();
let module_kind = ModuleKind::Def(Def::Mod(def_id), name);
let arenas = self.arenas;
*self.extern_crate_roots.entry((cnum, macros_only)).or_insert_with(|| {
arenas.alloc_module(ModuleData::new(None, module_kind, def_id))
arenas.alloc_module(ModuleData::new(None, module_kind, def_id, span))
})
}
pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
pub fn macro_def_scope(&mut self, expansion: Mark, span: Span) -> Module<'a> {
let def_id = self.macro_defs[&expansion];
if let Some(id) = self.definitions.as_local_node_id(def_id) {
self.local_macro_def_scopes[&id]
@ -503,7 +516,7 @@ impl<'a> Resolver<'a> {
self.graph_root
} else {
let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
self.get_extern_crate_root(module_def_id.krate)
self.get_extern_crate_root(module_def_id.krate, span)
}
}

View file

@ -865,12 +865,15 @@ pub struct ModuleData<'a> {
// access the children must be preceded with a
// `populate_module_if_necessary` call.
populated: Cell<bool>,
/// Span of the module itself. Used for error reporting.
span: Span,
}
pub type Module<'a> = &'a ModuleData<'a>;
impl<'a> ModuleData<'a> {
fn new(parent: Option<Module<'a>>, kind: ModuleKind, normal_ancestor_id: DefId) -> Self {
fn new(parent: Option<Module<'a>>, kind: ModuleKind, normal_ancestor_id: DefId, span: Span) -> Self {
ModuleData {
parent: parent,
kind: kind,
@ -884,6 +887,7 @@ impl<'a> ModuleData<'a> {
globs: RefCell::new((Vec::new())),
traits: RefCell::new(None),
populated: Cell::new(normal_ancestor_id.is_local()),
span: span,
}
}
@ -1298,7 +1302,7 @@ impl<'a> Resolver<'a> {
let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
let graph_root = arenas.alloc_module(ModuleData {
no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
..ModuleData::new(None, root_module_kind, root_def_id)
..ModuleData::new(None, root_module_kind, root_def_id, krate.span)
});
let mut module_map = FxHashMap();
module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
@ -1430,9 +1434,9 @@ impl<'a> Resolver<'a> {
self.crate_loader.postprocess(krate);
}
fn new_module(&self, parent: Module<'a>, kind: ModuleKind, normal_ancestor_id: DefId)
fn new_module(&self, parent: Module<'a>, kind: ModuleKind, normal_ancestor_id: DefId, span: Span)
-> Module<'a> {
self.arenas.alloc_module(ModuleData::new(Some(parent), kind, normal_ancestor_id))
self.arenas.alloc_module(ModuleData::new(Some(parent), kind, normal_ancestor_id, span))
}
fn record_use(&mut self, ident: Ident, ns: Namespace, binding: &'a NameBinding<'a>, span: Span)
@ -1535,12 +1539,12 @@ impl<'a> Resolver<'a> {
None
}
fn resolve_crate_var(&mut self, crate_var_ctxt: SyntaxContext) -> Module<'a> {
fn resolve_crate_var(&mut self, crate_var_ctxt: SyntaxContext, span: Span) -> Module<'a> {
let mut ctxt_data = crate_var_ctxt.data();
while ctxt_data.prev_ctxt != SyntaxContext::empty() {
ctxt_data = ctxt_data.prev_ctxt.data();
}
let module = self.macro_def_scope(ctxt_data.outer_mark);
let module = self.macro_def_scope(ctxt_data.outer_mark, span);
if module.is_local() { self.graph_root } else { module }
}
@ -2271,8 +2275,10 @@ impl<'a> Resolver<'a> {
let name = path.last().unwrap().name;
let candidates = this.lookup_import_candidates(name, ns, is_expected);
if !candidates.is_empty() {
let mut module_span = this.current_module.span;
module_span.hi = module_span.lo;
// Report import candidates as help and proceed searching for labels.
show_candidates(&mut err, &candidates, def.is_some());
show_candidates(&mut err, module_span, &candidates, def.is_some());
} else if is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
let enum_candidates = this.lookup_import_candidates(name, ns, is_enum_variant);
let mut enum_candidates = enum_candidates.iter()
@ -2584,7 +2590,7 @@ impl<'a> Resolver<'a> {
module = Some(self.graph_root);
continue
} else if i == 0 && ns == TypeNS && ident.name == "$crate" {
module = Some(self.resolve_crate_var(ident.ctxt));
module = Some(self.resolve_crate_var(ident.ctxt, DUMMY_SP));
continue
}
@ -3463,12 +3469,10 @@ fn import_candidate_to_paths(suggestion: &ImportSuggestion) -> (Span, String, St
/// When an entity with a given name is not available in scope, we search for
/// entities with that name in all crates. This method allows outputting the
/// results of this search in a programmer-friendly way
fn show_candidates(session: &mut DiagnosticBuilder,
fn show_candidates(err: &mut DiagnosticBuilder,
span: Span,
candidates: &[ImportSuggestion],
better: bool) {
// don't show more than MAX_CANDIDATES results, so
// we're consistent with the trait suggestions
const MAX_CANDIDATES: usize = 4;
// we want consistent results across executions, but candidates are produced
// by iterating through a hash map, so make sure they are ordered:
@ -3481,21 +3485,13 @@ fn show_candidates(session: &mut DiagnosticBuilder,
1 => " is found in another module, you can import it",
_ => "s are found in other modules, you can import them",
};
let msg = format!("possible {}candidate{} into scope", better, msg_diff);
let end = cmp::min(MAX_CANDIDATES, path_strings.len());
session.help(&format!("possible {}candidate{} into scope:{}{}",
better,
msg_diff,
&path_strings[0..end].iter().map(|candidate| {
format!("\n `use {};`", candidate)
}).collect::<String>(),
if path_strings.len() > MAX_CANDIDATES {
format!("\nand {} other candidates",
path_strings.len() - MAX_CANDIDATES)
} else {
"".to_owned()
}
));
for candidate in &mut path_strings {
*candidate = format!("use {};\n", candidate);
}
err.span_suggestions(span, &msg, path_strings);
}
/// A somewhat inefficient routine to obtain the name of a module.

View file

@ -123,14 +123,14 @@ impl<'a> base::Resolver for Resolver<'a> {
}
fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> {
struct EliminateCrateVar<'b, 'a: 'b>(&'b mut Resolver<'a>);
struct EliminateCrateVar<'b, 'a: 'b>(&'b mut Resolver<'a>, Span);
impl<'a, 'b> Folder for EliminateCrateVar<'a, 'b> {
fn fold_path(&mut self, mut path: ast::Path) -> ast::Path {
let ident = path.segments[0].identifier;
if ident.name == "$crate" {
path.segments[0].identifier.name = keywords::CrateRoot.name();
let module = self.0.resolve_crate_var(ident.ctxt);
let module = self.0.resolve_crate_var(ident.ctxt, self.1);
if !module.is_local() {
let span = path.segments[0].span;
path.segments.insert(1, match module.kind {
@ -149,7 +149,7 @@ impl<'a> base::Resolver for Resolver<'a> {
}
}
EliminateCrateVar(self).fold_item(item).expect_one("")
EliminateCrateVar(self, item.span).fold_item(item).expect_one("")
}
fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool {

View file

@ -4,8 +4,8 @@ error[E0425]: cannot find value `A` in module `namespaced_enums`
15 | let _ = namespaced_enums::A;
| ^ not found in `namespaced_enums`
|
= help: possible candidate is found in another module, you can import it into scope:
`use namespaced_enums::Foo::A;`
help: possible candidate is found in another module, you can import it into scope
| use namespaced_enums::Foo::A;
error[E0425]: cannot find function `B` in module `namespaced_enums`
--> $DIR/enums-are-namespaced-xc.rs:18:31
@ -13,8 +13,8 @@ error[E0425]: cannot find function `B` in module `namespaced_enums`
18 | let _ = namespaced_enums::B(10);
| ^ not found in `namespaced_enums`
|
= help: possible candidate is found in another module, you can import it into scope:
`use namespaced_enums::Foo::B;`
help: possible candidate is found in another module, you can import it into scope
| use namespaced_enums::Foo::B;
error[E0422]: cannot find struct, variant or union type `C` in module `namespaced_enums`
--> $DIR/enums-are-namespaced-xc.rs:21:31
@ -22,8 +22,8 @@ error[E0422]: cannot find struct, variant or union type `C` in module `namespace
21 | let _ = namespaced_enums::C { a: 10 };
| ^ not found in `namespaced_enums`
|
= help: possible candidate is found in another module, you can import it into scope:
`use namespaced_enums::Foo::C;`
help: possible candidate is found in another module, you can import it into scope
| use namespaced_enums::Foo::C;
error: aborting due to 3 previous errors

View file

@ -4,10 +4,10 @@ error[E0574]: expected struct, variant or union type, found enum `Result`
19 | Result {
| ^^^^^^ not a struct, variant or union type
|
= help: possible better candidates are found in other modules, you can import them into scope:
`use std::fmt::Result;`
`use std::io::Result;`
`use std::thread::Result;`
help: possible better candidates are found in other modules, you can import them into scope
| use std::fmt::Result;
| use std::io::Result;
| use std::thread::Result;
error: aborting due to previous error

View file

@ -4,8 +4,8 @@ error[E0422]: cannot find struct, variant or union type `E` in this scope
16 | E { name: "foobar" }; //~ ERROR unresolved struct, variant or union type `E`
| ^ not found in this scope
|
= help: possible candidate is found in another module, you can import it into scope:
`use SomeEnum::E;`
help: possible candidate is found in another module, you can import it into scope
| use SomeEnum::E;
error: aborting due to previous error

View file

@ -4,10 +4,10 @@ error[E0405]: cannot find trait `Mul` in this scope
53 | impl Mul for Foo {
| ^^^ not found in this scope
|
= help: possible candidates are found in other modules, you can import them into scope:
`use mul1::Mul;`
`use mul2::Mul;`
`use std::ops::Mul;`
help: possible candidates are found in other modules, you can import them into scope
| use mul1::Mul;
| use mul2::Mul;
| use std::ops::Mul;
error[E0412]: cannot find type `Mul` in this scope
--> $DIR/issue-21221-1.rs:72:16
@ -15,12 +15,12 @@ error[E0412]: cannot find type `Mul` in this scope
72 | fn getMul() -> Mul {
| ^^^ not found in this scope
|
= help: possible candidates are found in other modules, you can import them into scope:
`use mul1::Mul;`
`use mul2::Mul;`
`use mul3::Mul;`
`use mul4::Mul;`
and 2 other candidates
help: possible candidates are found in other modules, you can import them into scope
| use mul1::Mul;
| use mul2::Mul;
| use mul3::Mul;
| use mul4::Mul;
and 2 other candidates
error[E0405]: cannot find trait `ThisTraitReallyDoesntExistInAnyModuleReally` in this scope
--> $DIR/issue-21221-1.rs:83:6
@ -34,8 +34,8 @@ error[E0405]: cannot find trait `Div` in this scope
88 | impl Div for Foo {
| ^^^ not found in this scope
|
= help: possible candidate is found in another module, you can import it into scope:
`use std::ops::Div;`
help: possible candidate is found in another module, you can import it into scope
| use std::ops::Div;
error: cannot continue compilation due to previous error

View file

@ -4,8 +4,8 @@ error[E0405]: cannot find trait `T` in this scope
28 | impl T for Foo { }
| ^ not found in this scope
|
= help: possible candidate is found in another module, you can import it into scope:
`use foo::bar::T;`
help: possible candidate is found in another module, you can import it into scope
| use foo::bar::T;
error: main function not found

View file

@ -4,8 +4,8 @@ error[E0405]: cannot find trait `OuterTrait` in this scope
25 | impl OuterTrait for Foo {}
| ^^^^^^^^^^ not found in this scope
|
= help: possible candidate is found in another module, you can import it into scope:
`use issue_21221_3::outer::OuterTrait;`
help: possible candidate is found in another module, you can import it into scope
| use issue_21221_3::outer::OuterTrait;
error: cannot continue compilation due to previous error

View file

@ -4,8 +4,8 @@ error[E0405]: cannot find trait `T` in this scope
20 | impl T for Foo {}
| ^ not found in this scope
|
= help: possible candidate is found in another module, you can import it into scope:
`use issue_21221_4::T;`
help: possible candidate is found in another module, you can import it into scope
| use issue_21221_4::T;
error: cannot continue compilation due to previous error

View file

@ -4,8 +4,8 @@ error[E0404]: expected trait, found type alias `Foo`
20 | impl Foo for S { //~ ERROR expected trait, found type alias `Foo`
| ^^^ type aliases cannot be used for traits
|
= help: possible better candidate is found in another module, you can import it into scope:
`use issue_3907::Foo;`
help: possible better candidate is found in another module, you can import it into scope
| use issue_3907::Foo;
error: cannot continue compilation due to previous error

View file

@ -8,8 +8,8 @@ error[E0423]: expected value, found struct `Z`
| did you mean `S`?
| constructor is not visible here due to private fields
|
= help: possible better candidate is found in another module, you can import it into scope:
`use m::n::Z;`
help: possible better candidate is found in another module, you can import it into scope
| use m::n::Z;
error[E0423]: expected value, found struct `S`
--> $DIR/privacy-struct-ctor.rs:36:5
@ -20,8 +20,8 @@ error[E0423]: expected value, found struct `S`
| did you mean `S { /* fields */ }`?
| constructor is not visible here due to private fields
|
= help: possible better candidate is found in another module, you can import it into scope:
`use m::S;`
help: possible better candidate is found in another module, you can import it into scope
| use m::S;
error[E0423]: expected value, found struct `xcrate::S`
--> $DIR/privacy-struct-ctor.rs:42:5
@ -32,8 +32,8 @@ error[E0423]: expected value, found struct `xcrate::S`
| did you mean `xcrate::S { /* fields */ }`?
| constructor is not visible here due to private fields
|
= help: possible better candidate is found in another module, you can import it into scope:
`use m::S;`
help: possible better candidate is found in another module, you can import it into scope
| use m::S;
error: tuple struct `Z` is private
--> $DIR/privacy-struct-ctor.rs:25:9

View file

@ -4,8 +4,8 @@ error[E0404]: expected trait, found type parameter `Add`
15 | impl<T: Clone, Add> Add for Foo<T> {
| ^^^ not a trait
|
= help: possible better candidate is found in another module, you can import it into scope:
`use std::ops::Add;`
help: possible better candidate is found in another module, you can import it into scope
| use std::ops::Add;
error: main function not found