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