]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/diagnostics.rs
resolve: Introduce a new scope for derive helpers
[rust.git] / src / librustc_resolve / diagnostics.rs
1 use std::cmp::Reverse;
2
3 use errors::{Applicability, DiagnosticBuilder};
4 use log::debug;
5 use rustc::bug;
6 use rustc::hir::def::{self, DefKind, NonMacroAttrKind};
7 use rustc::hir::def::Namespace::{self, *};
8 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
9 use rustc::session::Session;
10 use rustc::ty::{self, DefIdTree};
11 use rustc::util::nodemap::FxHashSet;
12 use syntax::ast::{self, Ident, Path};
13 use syntax::feature_gate::BUILTIN_ATTRIBUTES;
14 use syntax::source_map::SourceMap;
15 use syntax::struct_span_err;
16 use syntax::symbol::{Symbol, kw};
17 use syntax::util::lev_distance::find_best_match_for_name;
18 use syntax_pos::hygiene::MacroKind;
19 use syntax_pos::{BytePos, Span, MultiSpan};
20
21 use crate::resolve_imports::{ImportDirective, ImportDirectiveSubclass, ImportResolver};
22 use crate::path_names_to_string;
23 use crate::{BindingError, CrateLint, HasGenericParams, LegacyScope, Module, ModuleOrUniformRoot};
24 use crate::{PathResult, ParentScope, ResolutionError, Resolver, Scope, ScopeSet, Segment};
25
26 use rustc_error_codes::*;
27
28 type Res = def::Res<ast::NodeId>;
29
30 /// A vector of spans and replacements, a message and applicability.
31 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
32
33 crate struct TypoSuggestion {
34     pub candidate: Symbol,
35     pub res: Res,
36 }
37
38 impl TypoSuggestion {
39     crate fn from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
40         TypoSuggestion { candidate, res }
41     }
42 }
43
44 /// A free importable items suggested in case of resolution failure.
45 crate struct ImportSuggestion {
46     pub did: Option<DefId>,
47     pub path: Path,
48 }
49
50 /// Adjust the impl span so that just the `impl` keyword is taken by removing
51 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
52 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
53 ///
54 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
55 /// parser. If you need to use this function or something similar, please consider updating the
56 /// `source_map` functions and this function to something more robust.
57 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
58     let impl_span = cm.span_until_char(impl_span, '<');
59     let impl_span = cm.span_until_whitespace(impl_span);
60     impl_span
61 }
62
63 impl<'a> Resolver<'a> {
64     crate fn add_module_candidates(
65         &mut self,
66         module: Module<'a>,
67         names: &mut Vec<TypoSuggestion>,
68         filter_fn: &impl Fn(Res) -> bool,
69     ) {
70         for (key, resolution) in self.resolutions(module).borrow().iter() {
71             if let Some(binding) = resolution.borrow().binding {
72                 let res = binding.res();
73                 if filter_fn(res) {
74                     names.push(TypoSuggestion::from_res(key.ident.name, res));
75                 }
76             }
77         }
78     }
79
80     /// Combines an error with provided span and emits it.
81     ///
82     /// This takes the error provided, combines it with the span and any additional spans inside the
83     /// error and emits it.
84     crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
85         self.into_struct_error(span, resolution_error).emit();
86     }
87
88     crate fn into_struct_error(
89         &self, span: Span, resolution_error: ResolutionError<'_>
90     ) -> DiagnosticBuilder<'_> {
91         match resolution_error {
92             ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
93                 let mut err = struct_span_err!(self.session,
94                     span,
95                     E0401,
96                     "can't use generic parameters from outer function",
97                 );
98                 err.span_label(span, format!("use of generic parameter from outer function"));
99
100                 let cm = self.session.source_map();
101                 match outer_res {
102                     Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
103                         if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
104                             self.definitions.opt_span(def_id)
105                         }) {
106                             err.span_label(
107                                 reduce_impl_span_to_impl_keyword(cm, impl_span),
108                                 "`Self` type implicitly declared here, by this `impl`",
109                             );
110                         }
111                         match (maybe_trait_defid, maybe_impl_defid) {
112                             (Some(_), None) => {
113                                 err.span_label(span, "can't use `Self` here");
114                             }
115                             (_, Some(_)) => {
116                                 err.span_label(span, "use a type here instead");
117                             }
118                             (None, None) => bug!("`impl` without trait nor type?"),
119                         }
120                         return err;
121                     },
122                     Res::Def(DefKind::TyParam, def_id) => {
123                         if let Some(span) = self.definitions.opt_span(def_id) {
124                             err.span_label(span, "type parameter from outer function");
125                         }
126                     }
127                     Res::Def(DefKind::ConstParam, def_id) => {
128                         if let Some(span) = self.definitions.opt_span(def_id) {
129                             err.span_label(span, "const parameter from outer function");
130                         }
131                     }
132                     _ => {
133                         bug!("GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
134                             DefKind::TyParam");
135                     }
136                 }
137
138                 if has_generic_params == HasGenericParams::Yes {
139                     // Try to retrieve the span of the function signature and generate a new
140                     // message with a local type or const parameter.
141                     let sugg_msg = &format!("try using a local generic parameter instead");
142                     if let Some((sugg_span, snippet)) = cm.generate_local_type_param_snippet(span) {
143                         // Suggest the modification to the user
144                         err.span_suggestion(
145                             sugg_span,
146                             sugg_msg,
147                             snippet,
148                             Applicability::MachineApplicable,
149                         );
150                     } else if let Some(sp) = cm.generate_fn_name_span(span) {
151                         err.span_label(sp,
152                             format!("try adding a local generic parameter in this method instead"));
153                     } else {
154                         err.help(&format!("try using a local generic parameter instead"));
155                     }
156                 }
157
158                 err
159             }
160             ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
161                 let mut err = struct_span_err!(
162                     self.session,
163                     span,
164                     E0403,
165                     "the name `{}` is already used for a generic \
166                      parameter in this item's generic parameters",
167                     name,
168                 );
169                 err.span_label(span, "already used");
170                 err.span_label(first_use_span, format!("first use of `{}`", name));
171                 err
172             }
173             ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
174                 let mut err = struct_span_err!(self.session,
175                                             span,
176                                             E0407,
177                                             "method `{}` is not a member of trait `{}`",
178                                             method,
179                                             trait_);
180                 err.span_label(span, format!("not a member of trait `{}`", trait_));
181                 err
182             }
183             ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
184                 let mut err = struct_span_err!(self.session,
185                                 span,
186                                 E0437,
187                                 "type `{}` is not a member of trait `{}`",
188                                 type_,
189                                 trait_);
190                 err.span_label(span, format!("not a member of trait `{}`", trait_));
191                 err
192             }
193             ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
194                 let mut err = struct_span_err!(self.session,
195                                 span,
196                                 E0438,
197                                 "const `{}` is not a member of trait `{}`",
198                                 const_,
199                                 trait_);
200                 err.span_label(span, format!("not a member of trait `{}`", trait_));
201                 err
202             }
203             ResolutionError::VariableNotBoundInPattern(binding_error) => {
204                 let BindingError { name, target, origin, could_be_path } = binding_error;
205
206                 let target_sp = target.iter().copied().collect::<Vec<_>>();
207                 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
208
209                 let msp = MultiSpan::from_spans(target_sp.clone());
210                 let mut err = struct_span_err!(
211                     self.session,
212                     msp,
213                     E0408,
214                     "variable `{}` is not bound in all patterns", name,
215                 );
216                 for sp in target_sp {
217                     err.span_label(sp, format!("pattern doesn't bind `{}`", name));
218                 }
219                 for sp in origin_sp {
220                     err.span_label(sp, "variable not in all patterns");
221                 }
222                 if *could_be_path {
223                     let help_msg = format!(
224                         "if you meant to match on a variant or a `const` item, consider \
225                          making the path in the pattern qualified: `?::{}`",
226                          name,
227                      );
228                     err.span_help(span, &help_msg);
229                 }
230                 err
231             }
232             ResolutionError::VariableBoundWithDifferentMode(variable_name,
233                                                             first_binding_span) => {
234                 let mut err = struct_span_err!(self.session,
235                                 span,
236                                 E0409,
237                                 "variable `{}` is bound in inconsistent \
238                                 ways within the same match arm",
239                                 variable_name);
240                 err.span_label(span, "bound in different ways");
241                 err.span_label(first_binding_span, "first binding");
242                 err
243             }
244             ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
245                 let mut err = struct_span_err!(self.session,
246                                 span,
247                                 E0415,
248                                 "identifier `{}` is bound more than once in this parameter list",
249                                 identifier);
250                 err.span_label(span, "used as parameter more than once");
251                 err
252             }
253             ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
254                 let mut err = struct_span_err!(self.session,
255                                 span,
256                                 E0416,
257                                 "identifier `{}` is bound more than once in the same pattern",
258                                 identifier);
259                 err.span_label(span, "used in a pattern more than once");
260                 err
261             }
262             ResolutionError::UndeclaredLabel(name, lev_candidate) => {
263                 let mut err = struct_span_err!(self.session,
264                                             span,
265                                             E0426,
266                                             "use of undeclared label `{}`",
267                                             name);
268                 if let Some(lev_candidate) = lev_candidate {
269                     err.span_suggestion(
270                         span,
271                         "a label with a similar name exists in this scope",
272                         lev_candidate.to_string(),
273                         Applicability::MaybeIncorrect,
274                     );
275                 } else {
276                     err.span_label(span, format!("undeclared label `{}`", name));
277                 }
278                 err
279             }
280             ResolutionError::SelfImportsOnlyAllowedWithin => {
281                 struct_span_err!(self.session,
282                                 span,
283                                 E0429,
284                                 "{}",
285                                 "`self` imports are only allowed within a { } list")
286             }
287             ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
288                 let mut err = struct_span_err!(self.session, span, E0430,
289                                             "`self` import can only appear once in an import list");
290                 err.span_label(span, "can only appear once in an import list");
291                 err
292             }
293             ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
294                 let mut err = struct_span_err!(self.session, span, E0431,
295                                             "`self` import can only appear in an import list with \
296                                                 a non-empty prefix");
297                 err.span_label(span, "can only appear in an import list with a non-empty prefix");
298                 err
299             }
300             ResolutionError::FailedToResolve { label, suggestion } => {
301                 let mut err = struct_span_err!(self.session, span, E0433,
302                                             "failed to resolve: {}", &label);
303                 err.span_label(span, label);
304
305                 if let Some((suggestions, msg, applicability)) = suggestion {
306                     err.multipart_suggestion(&msg, suggestions, applicability);
307                 }
308
309                 err
310             }
311             ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
312                 let mut err = struct_span_err!(self.session,
313                                             span,
314                                             E0434,
315                                             "{}",
316                                             "can't capture dynamic environment in a fn item");
317                 err.help("use the `|| { ... }` closure form instead");
318                 err
319             }
320             ResolutionError::AttemptToUseNonConstantValueInConstant => {
321                 let mut err = struct_span_err!(self.session, span, E0435,
322                                             "attempt to use a non-constant value in a constant");
323                 err.span_label(span, "non-constant value");
324                 err
325             }
326             ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
327                 let res = binding.res();
328                 let shadows_what = res.descr();
329                 let mut err = struct_span_err!(self.session, span, E0530, "{}s cannot shadow {}s",
330                                             what_binding, shadows_what);
331                 err.span_label(span, format!("cannot be named the same as {} {}",
332                                             res.article(), shadows_what));
333                 let participle = if binding.is_import() { "imported" } else { "defined" };
334                 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
335                 err.span_label(binding.span, msg);
336                 err
337             }
338             ResolutionError::ForwardDeclaredTyParam => {
339                 let mut err = struct_span_err!(self.session, span, E0128,
340                                             "type parameters with a default cannot use \
341                                                 forward declared identifiers");
342                 err.span_label(
343                     span, "defaulted type parameters cannot be forward declared".to_string());
344                 err
345             }
346             ResolutionError::SelfInTyParamDefault => {
347                 let mut err = struct_span_err!(
348                     self.session,
349                     span,
350                     E0735,
351                     "type parameters cannot use `Self` in their defaults"
352                 );
353                 err.span_label(
354                     span, "`Self` in type parameter default".to_string());
355                 err
356             }
357         }
358     }
359
360     /// Lookup typo candidate in scope for a macro or import.
361     fn early_lookup_typo_candidate(
362         &mut self,
363         scope_set: ScopeSet,
364         parent_scope: &ParentScope<'a>,
365         ident: Ident,
366         filter_fn: &impl Fn(Res) -> bool,
367     ) -> Option<TypoSuggestion> {
368         let mut suggestions = Vec::new();
369         self.visit_scopes(scope_set, parent_scope, ident, |this, scope, use_prelude, _| {
370             match scope {
371                 Scope::DeriveHelpers(expn_id) => {
372                     let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
373                     if filter_fn(res) {
374                         suggestions.extend(this.helper_attrs.get(&expn_id)
375                                                .into_iter().flatten().map(|ident| {
376                             TypoSuggestion::from_res(ident.name, res)
377                         }));
378                     }
379                 }
380                 Scope::DeriveHelpersCompat => {
381                     let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
382                     if filter_fn(res) {
383                         for derive in parent_scope.derives {
384                             let parent_scope =
385                                 &ParentScope { derives: &[], ..*parent_scope };
386                             if let Ok((Some(ext), _)) = this.resolve_macro_path(
387                                 derive, Some(MacroKind::Derive), parent_scope, false, false
388                             ) {
389                                 suggestions.extend(ext.helper_attrs.iter().map(|name| {
390                                     TypoSuggestion::from_res(*name, res)
391                                 }));
392                             }
393                         }
394                     }
395                 }
396                 Scope::MacroRules(legacy_scope) => {
397                     if let LegacyScope::Binding(legacy_binding) = legacy_scope {
398                         let res = legacy_binding.binding.res();
399                         if filter_fn(res) {
400                             suggestions.push(
401                                 TypoSuggestion::from_res(legacy_binding.ident.name, res)
402                             )
403                         }
404                     }
405                 }
406                 Scope::CrateRoot => {
407                     let root_ident = Ident::new(kw::PathRoot, ident.span);
408                     let root_module = this.resolve_crate_root(root_ident);
409                     this.add_module_candidates(root_module, &mut suggestions, filter_fn);
410                 }
411                 Scope::Module(module) => {
412                     this.add_module_candidates(module, &mut suggestions, filter_fn);
413                 }
414                 Scope::RegisteredAttrs => {
415                     let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
416                     if filter_fn(res) {
417                         suggestions.extend(this.registered_attrs.iter().map(|ident| {
418                             TypoSuggestion::from_res(ident.name, res)
419                         }));
420                     }
421                 }
422                 Scope::MacroUsePrelude => {
423                     suggestions.extend(this.macro_use_prelude.iter().filter_map(|(name, binding)| {
424                         let res = binding.res();
425                         if filter_fn(res) {
426                             Some(TypoSuggestion::from_res(*name, res))
427                         } else {
428                             None
429                         }
430                     }));
431                 }
432                 Scope::BuiltinAttrs => {
433                     let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
434                     if filter_fn(res) {
435                         suggestions.extend(BUILTIN_ATTRIBUTES.iter().map(|(name, ..)| {
436                             TypoSuggestion::from_res(*name, res)
437                         }));
438                     }
439                 }
440                 Scope::LegacyPluginHelpers => {
441                     let res = Res::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper);
442                     if filter_fn(res) {
443                         let plugin_attributes = this.session.plugin_attributes.borrow();
444                         suggestions.extend(plugin_attributes.iter().map(|(name, _)| {
445                             TypoSuggestion::from_res(*name, res)
446                         }));
447                     }
448                 }
449                 Scope::ExternPrelude => {
450                     suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
451                         let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
452                         if filter_fn(res) {
453                             Some(TypoSuggestion::from_res(ident.name, res))
454                         } else {
455                             None
456                         }
457                     }));
458                 }
459                 Scope::ToolPrelude => {
460                     let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
461                     suggestions.extend(this.registered_tools.iter().map(|ident| {
462                         TypoSuggestion::from_res(ident.name, res)
463                     }));
464                 }
465                 Scope::StdLibPrelude => {
466                     if let Some(prelude) = this.prelude {
467                         let mut tmp_suggestions = Vec::new();
468                         this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
469                         suggestions.extend(tmp_suggestions.into_iter().filter(|s| {
470                             use_prelude || this.is_builtin_macro(s.res)
471                         }));
472                     }
473                 }
474                 Scope::BuiltinTypes => {
475                     let primitive_types = &this.primitive_type_table.primitive_types;
476                     suggestions.extend(
477                         primitive_types.iter().flat_map(|(name, prim_ty)| {
478                             let res = Res::PrimTy(*prim_ty);
479                             if filter_fn(res) {
480                                 Some(TypoSuggestion::from_res(*name, res))
481                             } else {
482                                 None
483                             }
484                         })
485                     )
486                 }
487             }
488
489             None::<()>
490         });
491
492         // Make sure error reporting is deterministic.
493         suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
494
495         match find_best_match_for_name(
496             suggestions.iter().map(|suggestion| &suggestion.candidate),
497             &ident.as_str(),
498             None,
499         ) {
500             Some(found) if found != ident.name => suggestions
501                 .into_iter()
502                 .find(|suggestion| suggestion.candidate == found),
503             _ => None,
504         }
505     }
506
507     fn lookup_import_candidates_from_module<FilterFn>(&mut self,
508                                           lookup_ident: Ident,
509                                           namespace: Namespace,
510                                           start_module: Module<'a>,
511                                           crate_name: Ident,
512                                           filter_fn: FilterFn)
513                                           -> Vec<ImportSuggestion>
514         where FilterFn: Fn(Res) -> bool
515     {
516         let mut candidates = Vec::new();
517         let mut seen_modules = FxHashSet::default();
518         let not_local_module = crate_name.name != kw::Crate;
519         let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
520
521         while let Some((in_module,
522                         path_segments,
523                         in_module_is_extern)) = worklist.pop() {
524             // We have to visit module children in deterministic order to avoid
525             // instabilities in reported imports (#43552).
526             in_module.for_each_child(self, |this, ident, ns, name_binding| {
527                 // avoid imports entirely
528                 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
529                 // avoid non-importable candidates as well
530                 if !name_binding.is_importable() { return; }
531
532                 // collect results based on the filter function
533                 if ident.name == lookup_ident.name && ns == namespace {
534                     let res = name_binding.res();
535                     if filter_fn(res) {
536                         // create the path
537                         let mut segms = path_segments.clone();
538                         if lookup_ident.span.rust_2018() {
539                             // crate-local absolute paths start with `crate::` in edition 2018
540                             // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
541                             segms.insert(
542                                 0, ast::PathSegment::from_ident(crate_name)
543                             );
544                         }
545
546                         segms.push(ast::PathSegment::from_ident(ident));
547                         let path = Path {
548                             span: name_binding.span,
549                             segments: segms,
550                         };
551                         // the entity is accessible in the following cases:
552                         // 1. if it's defined in the same crate, it's always
553                         // accessible (since private entities can be made public)
554                         // 2. if it's defined in another crate, it's accessible
555                         // only if both the module is public and the entity is
556                         // declared as public (due to pruning, we don't explore
557                         // outside crate private modules => no need to check this)
558                         if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
559                             let did = match res {
560                                 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
561                                 _ => res.opt_def_id(),
562                             };
563                             candidates.push(ImportSuggestion { did, path });
564                         }
565                     }
566                 }
567
568                 // collect submodules to explore
569                 if let Some(module) = name_binding.module() {
570                     // form the path
571                     let mut path_segments = path_segments.clone();
572                     path_segments.push(ast::PathSegment::from_ident(ident));
573
574                     let is_extern_crate_that_also_appears_in_prelude =
575                         name_binding.is_extern_crate() &&
576                         lookup_ident.span.rust_2018();
577
578                     let is_visible_to_user =
579                         !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
580
581                     if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
582                         // add the module to the lookup
583                         let is_extern = in_module_is_extern || name_binding.is_extern_crate();
584                         if seen_modules.insert(module.def_id().unwrap()) {
585                             worklist.push((module, path_segments, is_extern));
586                         }
587                     }
588                 }
589             })
590         }
591
592         candidates
593     }
594
595     /// When name resolution fails, this method can be used to look up candidate
596     /// entities with the expected name. It allows filtering them using the
597     /// supplied predicate (which should be used to only accept the types of
598     /// definitions expected, e.g., traits). The lookup spans across all crates.
599     ///
600     /// N.B., the method does not look into imports, but this is not a problem,
601     /// since we report the definitions (thus, the de-aliased imports).
602     crate fn lookup_import_candidates<FilterFn>(
603         &mut self, lookup_ident: Ident, namespace: Namespace, filter_fn: FilterFn
604     ) -> Vec<ImportSuggestion>
605         where FilterFn: Fn(Res) -> bool
606     {
607         let mut suggestions = self.lookup_import_candidates_from_module(
608             lookup_ident, namespace, self.graph_root, Ident::with_dummy_span(kw::Crate), &filter_fn
609         );
610
611         if lookup_ident.span.rust_2018() {
612             let extern_prelude_names = self.extern_prelude.clone();
613             for (ident, _) in extern_prelude_names.into_iter() {
614                 if ident.span.from_expansion() {
615                     // Idents are adjusted to the root context before being
616                     // resolved in the extern prelude, so reporting this to the
617                     // user is no help. This skips the injected
618                     // `extern crate std` in the 2018 edition, which would
619                     // otherwise cause duplicate suggestions.
620                     continue;
621                 }
622                 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
623                                                                                     ident.span) {
624                     let crate_root = self.get_module(DefId {
625                         krate: crate_id,
626                         index: CRATE_DEF_INDEX,
627                     });
628                     suggestions.extend(self.lookup_import_candidates_from_module(
629                         lookup_ident, namespace, crate_root, ident, &filter_fn));
630                 }
631             }
632         }
633
634         suggestions
635     }
636
637     crate fn unresolved_macro_suggestions(
638         &mut self,
639         err: &mut DiagnosticBuilder<'a>,
640         macro_kind: MacroKind,
641         parent_scope: &ParentScope<'a>,
642         ident: Ident,
643     ) {
644         let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
645         let suggestion = self.early_lookup_typo_candidate(
646             ScopeSet::Macro(macro_kind), parent_scope, ident, is_expected
647         );
648         self.add_typo_suggestion(err, suggestion, ident.span);
649
650         if macro_kind == MacroKind::Derive &&
651            (ident.as_str() == "Send" || ident.as_str() == "Sync") {
652             let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
653             err.span_note(ident.span, &msg);
654         }
655         if self.macro_names.contains(&ident.modern()) {
656             err.help("have you added the `#[macro_use]` on the module/import?");
657         }
658     }
659
660     crate fn add_typo_suggestion(
661         &self,
662         err: &mut DiagnosticBuilder<'_>,
663         suggestion: Option<TypoSuggestion>,
664         span: Span,
665     ) -> bool {
666         if let Some(suggestion) = suggestion {
667             let msg = format!(
668                 "{} {} with a similar name exists", suggestion.res.article(), suggestion.res.descr()
669             );
670             err.span_suggestion(
671                 span, &msg, suggestion.candidate.to_string(), Applicability::MaybeIncorrect
672             );
673             let def_span = suggestion.res.opt_def_id()
674                 .and_then(|def_id| self.definitions.opt_span(def_id));
675             if let Some(span) = def_span {
676                 err.span_label(span, &format!(
677                     "similarly named {} `{}` defined here",
678                     suggestion.res.descr(),
679                     suggestion.candidate.as_str(),
680                 ));
681             }
682             return true;
683         }
684         false
685     }
686 }
687
688 impl<'a, 'b> ImportResolver<'a, 'b> {
689     /// Adds suggestions for a path that cannot be resolved.
690     pub(crate) fn make_path_suggestion(
691         &mut self,
692         span: Span,
693         mut path: Vec<Segment>,
694         parent_scope: &ParentScope<'b>,
695     ) -> Option<(Vec<Segment>, Vec<String>)> {
696         debug!("make_path_suggestion: span={:?} path={:?}", span, path);
697
698         match (path.get(0), path.get(1)) {
699             // `{{root}}::ident::...` on both editions.
700             // On 2015 `{{root}}` is usually added implicitly.
701             (Some(fst), Some(snd)) if fst.ident.name == kw::PathRoot &&
702                                       !snd.ident.is_path_segment_keyword() => {}
703             // `ident::...` on 2018.
704             (Some(fst), _) if fst.ident.span.rust_2018() &&
705                               !fst.ident.is_path_segment_keyword() => {
706                 // Insert a placeholder that's later replaced by `self`/`super`/etc.
707                 path.insert(0, Segment::from_ident(Ident::invalid()));
708             }
709             _ => return None,
710         }
711
712         self.make_missing_self_suggestion(span, path.clone(), parent_scope)
713             .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
714             .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
715             .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
716     }
717
718     /// Suggest a missing `self::` if that resolves to an correct module.
719     ///
720     /// ```
721     ///    |
722     /// LL | use foo::Bar;
723     ///    |     ^^^ did you mean `self::foo`?
724     /// ```
725     fn make_missing_self_suggestion(
726         &mut self,
727         span: Span,
728         mut path: Vec<Segment>,
729         parent_scope: &ParentScope<'b>,
730     ) -> Option<(Vec<Segment>, Vec<String>)> {
731         // Replace first ident with `self` and check if that is valid.
732         path[0].ident.name = kw::SelfLower;
733         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
734         debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
735         if let PathResult::Module(..) = result {
736             Some((path, Vec::new()))
737         } else {
738             None
739         }
740     }
741
742     /// Suggests a missing `crate::` if that resolves to an correct module.
743     ///
744     /// ```
745     ///    |
746     /// LL | use foo::Bar;
747     ///    |     ^^^ did you mean `crate::foo`?
748     /// ```
749     fn make_missing_crate_suggestion(
750         &mut self,
751         span: Span,
752         mut path: Vec<Segment>,
753         parent_scope: &ParentScope<'b>,
754     ) -> Option<(Vec<Segment>, Vec<String>)> {
755         // Replace first ident with `crate` and check if that is valid.
756         path[0].ident.name = kw::Crate;
757         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
758         debug!("make_missing_crate_suggestion:  path={:?} result={:?}", path, result);
759         if let PathResult::Module(..) = result {
760             Some((
761                 path,
762                 vec![
763                     "`use` statements changed in Rust 2018; read more at \
764                      <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
765                      clarity.html>".to_string()
766                 ],
767             ))
768         } else {
769             None
770         }
771     }
772
773     /// Suggests a missing `super::` if that resolves to an correct module.
774     ///
775     /// ```
776     ///    |
777     /// LL | use foo::Bar;
778     ///    |     ^^^ did you mean `super::foo`?
779     /// ```
780     fn make_missing_super_suggestion(
781         &mut self,
782         span: Span,
783         mut path: Vec<Segment>,
784         parent_scope: &ParentScope<'b>,
785     ) -> Option<(Vec<Segment>, Vec<String>)> {
786         // Replace first ident with `crate` and check if that is valid.
787         path[0].ident.name = kw::Super;
788         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
789         debug!("make_missing_super_suggestion:  path={:?} result={:?}", path, result);
790         if let PathResult::Module(..) = result {
791             Some((path, Vec::new()))
792         } else {
793             None
794         }
795     }
796
797     /// Suggests a missing external crate name if that resolves to an correct module.
798     ///
799     /// ```
800     ///    |
801     /// LL | use foobar::Baz;
802     ///    |     ^^^^^^ did you mean `baz::foobar`?
803     /// ```
804     ///
805     /// Used when importing a submodule of an external crate but missing that crate's
806     /// name as the first part of path.
807     fn make_external_crate_suggestion(
808         &mut self,
809         span: Span,
810         mut path: Vec<Segment>,
811         parent_scope: &ParentScope<'b>,
812     ) -> Option<(Vec<Segment>, Vec<String>)> {
813         if path[1].ident.span.rust_2015() {
814             return None;
815         }
816
817         // Sort extern crate names in reverse order to get
818         // 1) some consistent ordering for emitted dignostics, and
819         // 2) `std` suggestions before `core` suggestions.
820         let mut extern_crate_names =
821             self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
822         extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
823
824         for name in extern_crate_names.into_iter() {
825             // Replace first ident with a crate name and check if that is valid.
826             path[0].ident.name = name;
827             let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
828             debug!("make_external_crate_suggestion: name={:?} path={:?} result={:?}",
829                     name, path, result);
830             if let PathResult::Module(..) = result {
831                 return Some((path, Vec::new()));
832             }
833         }
834
835         None
836     }
837
838     /// Suggests importing a macro from the root of the crate rather than a module within
839     /// the crate.
840     ///
841     /// ```
842     /// help: a macro with this name exists at the root of the crate
843     ///    |
844     /// LL | use issue_59764::makro;
845     ///    |     ^^^^^^^^^^^^^^^^^^
846     ///    |
847     ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
848     ///            at the root of the crate instead of the module where it is defined
849     /// ```
850     pub(crate) fn check_for_module_export_macro(
851         &mut self,
852         directive: &'b ImportDirective<'b>,
853         module: ModuleOrUniformRoot<'b>,
854         ident: Ident,
855     ) -> Option<(Option<Suggestion>, Vec<String>)> {
856         let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
857             module
858         } else {
859             return None;
860         };
861
862         while let Some(parent) = crate_module.parent {
863             crate_module = parent;
864         }
865
866         if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
867             // Don't make a suggestion if the import was already from the root of the
868             // crate.
869             return None;
870         }
871
872         let resolutions = self.r.resolutions(crate_module).borrow();
873         let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
874         let binding = resolution.borrow().binding()?;
875         if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
876             let module_name = crate_module.kind.name().unwrap();
877             let import = match directive.subclass {
878                 ImportDirectiveSubclass::SingleImport { source, target, .. } if source != target =>
879                     format!("{} as {}", source, target),
880                 _ => format!("{}", ident),
881             };
882
883             let mut corrections: Vec<(Span, String)> = Vec::new();
884             if !directive.is_nested() {
885                 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
886                 // intermediate segments.
887                 corrections.push((directive.span, format!("{}::{}", module_name, import)));
888             } else {
889                 // Find the binding span (and any trailing commas and spaces).
890                 //   ie. `use a::b::{c, d, e};`
891                 //                      ^^^
892                 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
893                     self.r.session, directive.span, directive.use_span,
894                 );
895                 debug!("check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
896                        found_closing_brace, binding_span);
897
898                 let mut removal_span = binding_span;
899                 if found_closing_brace {
900                     // If the binding span ended with a closing brace, as in the below example:
901                     //   ie. `use a::b::{c, d};`
902                     //                      ^
903                     // Then expand the span of characters to remove to include the previous
904                     // binding's trailing comma.
905                     //   ie. `use a::b::{c, d};`
906                     //                    ^^^
907                     if let Some(previous_span) = extend_span_to_previous_binding(
908                         self.r.session, binding_span,
909                     ) {
910                         debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
911                         removal_span = removal_span.with_lo(previous_span.lo());
912                     }
913                 }
914                 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
915
916                 // Remove the `removal_span`.
917                 corrections.push((removal_span, "".to_string()));
918
919                 // Find the span after the crate name and if it has nested imports immediatately
920                 // after the crate name already.
921                 //   ie. `use a::b::{c, d};`
922                 //               ^^^^^^^^^
923                 //   or  `use a::{b, c, d}};`
924                 //               ^^^^^^^^^^^
925                 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
926                     self.r.session, module_name, directive.use_span,
927                 );
928                 debug!("check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
929                        has_nested, after_crate_name);
930
931                 let source_map = self.r.session.source_map();
932
933                 // Add the import to the start, with a `{` if required.
934                 let start_point = source_map.start_point(after_crate_name);
935                 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
936                     corrections.push((
937                         start_point,
938                         if has_nested {
939                             // In this case, `start_snippet` must equal '{'.
940                             format!("{}{}, ", start_snippet, import)
941                         } else {
942                             // In this case, add a `{`, then the moved import, then whatever
943                             // was there before.
944                             format!("{{{}, {}", import, start_snippet)
945                         }
946                     ));
947                 }
948
949                 // Add a `};` to the end if nested, matching the `{` added at the start.
950                 if !has_nested {
951                     corrections.push((source_map.end_point(after_crate_name),
952                                      "};".to_string()));
953                 }
954             }
955
956             let suggestion = Some((
957                 corrections,
958                 String::from("a macro with this name exists at the root of the crate"),
959                 Applicability::MaybeIncorrect,
960             ));
961             let note = vec![
962                 "this could be because a macro annotated with `#[macro_export]` will be exported \
963                  at the root of the crate instead of the module where it is defined".to_string(),
964             ];
965             Some((suggestion, note))
966         } else {
967             None
968         }
969     }
970 }
971
972 /// Given a `binding_span` of a binding within a use statement:
973 ///
974 /// ```
975 /// use foo::{a, b, c};
976 ///              ^
977 /// ```
978 ///
979 /// then return the span until the next binding or the end of the statement:
980 ///
981 /// ```
982 /// use foo::{a, b, c};
983 ///              ^^^
984 /// ```
985 pub(crate) fn find_span_of_binding_until_next_binding(
986     sess: &Session,
987     binding_span: Span,
988     use_span: Span,
989 ) -> (bool, Span) {
990     let source_map = sess.source_map();
991
992     // Find the span of everything after the binding.
993     //   ie. `a, e};` or `a};`
994     let binding_until_end = binding_span.with_hi(use_span.hi());
995
996     // Find everything after the binding but not including the binding.
997     //   ie. `, e};` or `};`
998     let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
999
1000     // Keep characters in the span until we encounter something that isn't a comma or
1001     // whitespace.
1002     //   ie. `, ` or ``.
1003     //
1004     // Also note whether a closing brace character was encountered. If there
1005     // was, then later go backwards to remove any trailing commas that are left.
1006     let mut found_closing_brace = false;
1007     let after_binding_until_next_binding = source_map.span_take_while(
1008         after_binding_until_end,
1009         |&ch| {
1010             if ch == '}' { found_closing_brace = true; }
1011             ch == ' ' || ch == ','
1012         }
1013     );
1014
1015     // Combine the two spans.
1016     //   ie. `a, ` or `a`.
1017     //
1018     // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1019     let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1020
1021     (found_closing_brace, span)
1022 }
1023
1024 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1025 /// binding.
1026 ///
1027 /// ```
1028 /// use foo::a::{a, b, c};
1029 ///               ^^--- binding span
1030 ///               |
1031 ///               returned span
1032 ///
1033 /// use foo::{a, b, c};
1034 ///           --- binding span
1035 /// ```
1036 pub(crate) fn extend_span_to_previous_binding(
1037     sess: &Session,
1038     binding_span: Span,
1039 ) -> Option<Span> {
1040     let source_map = sess.source_map();
1041
1042     // `prev_source` will contain all of the source that came before the span.
1043     // Then split based on a command and take the first (ie. closest to our span)
1044     // snippet. In the example, this is a space.
1045     let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1046
1047     let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1048     let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1049     if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1050         return None;
1051     }
1052
1053     let prev_comma = prev_comma.first().unwrap();
1054     let prev_starting_brace = prev_starting_brace.first().unwrap();
1055
1056     // If the amount of source code before the comma is greater than
1057     // the amount of source code before the starting brace then we've only
1058     // got one item in the nested item (eg. `issue_52891::{self}`).
1059     if prev_comma.len() > prev_starting_brace.len() {
1060         return None;
1061     }
1062
1063     Some(binding_span.with_lo(BytePos(
1064         // Take away the number of bytes for the characters we've found and an
1065         // extra for the comma.
1066         binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1
1067     )))
1068 }
1069
1070 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1071 /// it is a nested use tree.
1072 ///
1073 /// ```
1074 /// use foo::a::{b, c};
1075 ///          ^^^^^^^^^^ // false
1076 ///
1077 /// use foo::{a, b, c};
1078 ///          ^^^^^^^^^^ // true
1079 ///
1080 /// use foo::{a, b::{c, d}};
1081 ///          ^^^^^^^^^^^^^^^ // true
1082 /// ```
1083 fn find_span_immediately_after_crate_name(
1084     sess: &Session,
1085     module_name: Symbol,
1086     use_span: Span,
1087 ) -> (bool, Span) {
1088     debug!("find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1089            module_name, use_span);
1090     let source_map = sess.source_map();
1091
1092     // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1093     let mut num_colons = 0;
1094     // Find second colon.. `use issue_59764:`
1095     let until_second_colon = source_map.span_take_while(use_span, |c| {
1096         if *c == ':' { num_colons += 1; }
1097         match c {
1098             ':' if num_colons == 2 => false,
1099             _ => true,
1100         }
1101     });
1102     // Find everything after the second colon.. `foo::{baz, makro};`
1103     let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1104
1105     let mut found_a_non_whitespace_character = false;
1106     // Find the first non-whitespace character in `from_second_colon`.. `f`
1107     let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1108         if found_a_non_whitespace_character { return false; }
1109         if !c.is_whitespace() { found_a_non_whitespace_character = true; }
1110         true
1111     });
1112
1113     // Find the first `{` in from_second_colon.. `foo::{`
1114     let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1115
1116     (next_left_bracket == after_second_colon, from_second_colon)
1117 }
1118
1119 /// When an entity with a given name is not available in scope, we search for
1120 /// entities with that name in all crates. This method allows outputting the
1121 /// results of this search in a programmer-friendly way
1122 crate fn show_candidates(
1123     err: &mut DiagnosticBuilder<'_>,
1124     // This is `None` if all placement locations are inside expansions
1125     span: Option<Span>,
1126     candidates: &[ImportSuggestion],
1127     better: bool,
1128     found_use: bool,
1129 ) {
1130     // we want consistent results across executions, but candidates are produced
1131     // by iterating through a hash map, so make sure they are ordered:
1132     let mut path_strings: Vec<_> =
1133         candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
1134     path_strings.sort();
1135
1136     let better = if better { "better " } else { "" };
1137     let msg_diff = match path_strings.len() {
1138         1 => " is found in another module, you can import it",
1139         _ => "s are found in other modules, you can import them",
1140     };
1141     let msg = format!("possible {}candidate{} into scope", better, msg_diff);
1142
1143     if let Some(span) = span {
1144         for candidate in &mut path_strings {
1145             // produce an additional newline to separate the new use statement
1146             // from the directly following item.
1147             let additional_newline = if found_use {
1148                 ""
1149             } else {
1150                 "\n"
1151             };
1152             *candidate = format!("use {};\n{}", candidate, additional_newline);
1153         }
1154
1155         err.span_suggestions(
1156             span,
1157             &msg,
1158             path_strings.into_iter(),
1159             Applicability::Unspecified,
1160         );
1161     } else {
1162         let mut msg = msg;
1163         msg.push(':');
1164         for candidate in path_strings {
1165             msg.push('\n');
1166             msg.push_str(&candidate);
1167         }
1168     }
1169 }