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