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