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