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