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