]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/diagnostics.rs
track_caller for slice length assertions
[rust.git] / compiler / rustc_resolve / src / diagnostics.rs
1 use std::cmp::Reverse;
2 use std::ptr;
3
4 use rustc_ast::{self as ast, Path};
5 use rustc_ast_pretty::pprust;
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
8 use rustc_feature::BUILTIN_ATTRIBUTES;
9 use rustc_hir::def::Namespace::{self, *};
10 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind};
11 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::PrimTy;
13 use rustc_middle::bug;
14 use rustc_middle::ty::{self, DefIdTree};
15 use rustc_session::Session;
16 use rustc_span::hygiene::MacroKind;
17 use rustc_span::lev_distance::find_best_match_for_name;
18 use rustc_span::source_map::SourceMap;
19 use rustc_span::symbol::{kw, sym, Ident, Symbol};
20 use rustc_span::{BytePos, MultiSpan, Span};
21 use tracing::debug;
22
23 use crate::imports::{Import, ImportKind, ImportResolver};
24 use crate::path_names_to_string;
25 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
26 use crate::{
27     BindingError, CrateLint, HasGenericParams, MacroRulesScope, Module, ModuleOrUniformRoot,
28 };
29 use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
30 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment};
31
32 type Res = def::Res<ast::NodeId>;
33
34 /// A vector of spans and replacements, a message and applicability.
35 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
36
37 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
38 /// similarly named label and whether or not it is reachable.
39 crate type LabelSuggestion = (Ident, bool);
40
41 crate enum SuggestionTarget {
42     /// The target has a similar name as the name used by the programmer (probably a typo)
43     SimilarlyNamed,
44     /// The target is the only valid item that can be used in the corresponding context
45     SingleItem,
46 }
47
48 crate struct TypoSuggestion {
49     pub candidate: Symbol,
50     pub res: Res,
51     pub target: SuggestionTarget,
52 }
53
54 impl TypoSuggestion {
55     crate fn typo_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
56         Self { candidate, res, target: SuggestionTarget::SimilarlyNamed }
57     }
58     crate fn single_item_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
59         Self { candidate, res, target: SuggestionTarget::SingleItem }
60     }
61 }
62
63 /// A free importable items suggested in case of resolution failure.
64 crate struct ImportSuggestion {
65     pub did: Option<DefId>,
66     pub descr: &'static str,
67     pub path: Path,
68     pub accessible: bool,
69 }
70
71 /// Adjust the impl span so that just the `impl` keyword is taken by removing
72 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
73 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
74 ///
75 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
76 /// parser. If you need to use this function or something similar, please consider updating the
77 /// `source_map` functions and this function to something more robust.
78 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
79     let impl_span = sm.span_until_char(impl_span, '<');
80     sm.span_until_whitespace(impl_span)
81 }
82
83 impl<'a> Resolver<'a> {
84     crate fn add_module_candidates(
85         &mut self,
86         module: Module<'a>,
87         names: &mut Vec<TypoSuggestion>,
88         filter_fn: &impl Fn(Res) -> bool,
89     ) {
90         for (key, resolution) in self.resolutions(module).borrow().iter() {
91             if let Some(binding) = resolution.borrow().binding {
92                 let res = binding.res();
93                 if filter_fn(res) {
94                     names.push(TypoSuggestion::typo_from_res(key.ident.name, res));
95                 }
96             }
97         }
98     }
99
100     /// Combines an error with provided span and emits it.
101     ///
102     /// This takes the error provided, combines it with the span and any additional spans inside the
103     /// error and emits it.
104     crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
105         self.into_struct_error(span, resolution_error).emit();
106     }
107
108     crate fn into_struct_error(
109         &self,
110         span: Span,
111         resolution_error: ResolutionError<'_>,
112     ) -> DiagnosticBuilder<'_> {
113         match resolution_error {
114             ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
115                 let mut err = struct_span_err!(
116                     self.session,
117                     span,
118                     E0401,
119                     "can't use generic parameters from outer function",
120                 );
121                 err.span_label(span, "use of generic parameter from outer function".to_string());
122
123                 let sm = self.session.source_map();
124                 match outer_res {
125                     Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
126                         if let Some(impl_span) =
127                             maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
128                         {
129                             err.span_label(
130                                 reduce_impl_span_to_impl_keyword(sm, impl_span),
131                                 "`Self` type implicitly declared here, by this `impl`",
132                             );
133                         }
134                         match (maybe_trait_defid, maybe_impl_defid) {
135                             (Some(_), None) => {
136                                 err.span_label(span, "can't use `Self` here");
137                             }
138                             (_, Some(_)) => {
139                                 err.span_label(span, "use a type here instead");
140                             }
141                             (None, None) => bug!("`impl` without trait nor type?"),
142                         }
143                         return err;
144                     }
145                     Res::Def(DefKind::TyParam, def_id) => {
146                         if let Some(span) = self.opt_span(def_id) {
147                             err.span_label(span, "type parameter from outer function");
148                         }
149                     }
150                     Res::Def(DefKind::ConstParam, def_id) => {
151                         if let Some(span) = self.opt_span(def_id) {
152                             err.span_label(span, "const parameter from outer function");
153                         }
154                     }
155                     _ => {
156                         bug!(
157                             "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
158                             DefKind::TyParam or DefKind::ConstParam"
159                         );
160                     }
161                 }
162
163                 if has_generic_params == HasGenericParams::Yes {
164                     // Try to retrieve the span of the function signature and generate a new
165                     // message with a local type or const parameter.
166                     let sugg_msg = "try using a local generic parameter instead";
167                     if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
168                         // Suggest the modification to the user
169                         err.span_suggestion(
170                             sugg_span,
171                             sugg_msg,
172                             snippet,
173                             Applicability::MachineApplicable,
174                         );
175                     } else if let Some(sp) = sm.generate_fn_name_span(span) {
176                         err.span_label(
177                             sp,
178                             "try adding a local generic parameter in this method instead"
179                                 .to_string(),
180                         );
181                     } else {
182                         err.help("try using a local generic parameter instead");
183                     }
184                 }
185
186                 err
187             }
188             ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
189                 let mut err = struct_span_err!(
190                     self.session,
191                     span,
192                     E0403,
193                     "the name `{}` is already used for a generic \
194                      parameter in this item's generic parameters",
195                     name,
196                 );
197                 err.span_label(span, "already used");
198                 err.span_label(first_use_span, format!("first use of `{}`", name));
199                 err
200             }
201             ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
202                 let mut err = struct_span_err!(
203                     self.session,
204                     span,
205                     E0407,
206                     "method `{}` is not a member of trait `{}`",
207                     method,
208                     trait_
209                 );
210                 err.span_label(span, format!("not a member of trait `{}`", trait_));
211                 if let Some(candidate) = candidate {
212                     err.span_suggestion(
213                         method.span,
214                         "there is an associated function with a similar name",
215                         candidate.to_ident_string(),
216                         Applicability::MaybeIncorrect,
217                     );
218                 }
219                 err
220             }
221             ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
222                 let mut err = struct_span_err!(
223                     self.session,
224                     span,
225                     E0437,
226                     "type `{}` is not a member of trait `{}`",
227                     type_,
228                     trait_
229                 );
230                 err.span_label(span, format!("not a member of trait `{}`", trait_));
231                 if let Some(candidate) = candidate {
232                     err.span_suggestion(
233                         type_.span,
234                         "there is an associated type with a similar name",
235                         candidate.to_ident_string(),
236                         Applicability::MaybeIncorrect,
237                     );
238                 }
239                 err
240             }
241             ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
242                 let mut err = struct_span_err!(
243                     self.session,
244                     span,
245                     E0438,
246                     "const `{}` is not a member of trait `{}`",
247                     const_,
248                     trait_
249                 );
250                 err.span_label(span, format!("not a member of trait `{}`", trait_));
251                 if let Some(candidate) = candidate {
252                     err.span_suggestion(
253                         const_.span,
254                         "there is an associated constant with a similar name",
255                         candidate.to_ident_string(),
256                         Applicability::MaybeIncorrect,
257                     );
258                 }
259                 err
260             }
261             ResolutionError::VariableNotBoundInPattern(binding_error) => {
262                 let BindingError { name, target, origin, could_be_path } = binding_error;
263
264                 let target_sp = target.iter().copied().collect::<Vec<_>>();
265                 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
266
267                 let msp = MultiSpan::from_spans(target_sp.clone());
268                 let mut err = struct_span_err!(
269                     self.session,
270                     msp,
271                     E0408,
272                     "variable `{}` is not bound in all patterns",
273                     name,
274                 );
275                 for sp in target_sp {
276                     err.span_label(sp, format!("pattern doesn't bind `{}`", name));
277                 }
278                 for sp in origin_sp {
279                     err.span_label(sp, "variable not in all patterns");
280                 }
281                 if *could_be_path {
282                     let help_msg = format!(
283                         "if you meant to match on a variant or a `const` item, consider \
284                          making the path in the pattern qualified: `?::{}`",
285                         name,
286                     );
287                     err.span_help(span, &help_msg);
288                 }
289                 err
290             }
291             ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
292                 let mut err = struct_span_err!(
293                     self.session,
294                     span,
295                     E0409,
296                     "variable `{}` is bound inconsistently across alternatives separated by `|`",
297                     variable_name
298                 );
299                 err.span_label(span, "bound in different ways");
300                 err.span_label(first_binding_span, "first binding");
301                 err
302             }
303             ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
304                 let mut err = struct_span_err!(
305                     self.session,
306                     span,
307                     E0415,
308                     "identifier `{}` is bound more than once in this parameter list",
309                     identifier
310                 );
311                 err.span_label(span, "used as parameter more than once");
312                 err
313             }
314             ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
315                 let mut err = struct_span_err!(
316                     self.session,
317                     span,
318                     E0416,
319                     "identifier `{}` is bound more than once in the same pattern",
320                     identifier
321                 );
322                 err.span_label(span, "used in a pattern more than once");
323                 err
324             }
325             ResolutionError::UndeclaredLabel { name, suggestion } => {
326                 let mut err = struct_span_err!(
327                     self.session,
328                     span,
329                     E0426,
330                     "use of undeclared label `{}`",
331                     name
332                 );
333
334                 err.span_label(span, format!("undeclared label `{}`", name));
335
336                 match suggestion {
337                     // A reachable label with a similar name exists.
338                     Some((ident, true)) => {
339                         err.span_label(ident.span, "a label with a similar name is reachable");
340                         err.span_suggestion(
341                             span,
342                             "try using similarly named label",
343                             ident.name.to_string(),
344                             Applicability::MaybeIncorrect,
345                         );
346                     }
347                     // An unreachable label with a similar name exists.
348                     Some((ident, false)) => {
349                         err.span_label(
350                             ident.span,
351                             "a label with a similar name exists but is unreachable",
352                         );
353                     }
354                     // No similarly-named labels exist.
355                     None => (),
356                 }
357
358                 err
359             }
360             ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
361                 let mut err = struct_span_err!(
362                     self.session,
363                     span,
364                     E0429,
365                     "{}",
366                     "`self` imports are only allowed within a { } list"
367                 );
368
369                 // None of the suggestions below would help with a case like `use self`.
370                 if !root {
371                     // use foo::bar::self        -> foo::bar
372                     // use foo::bar::self as abc -> foo::bar as abc
373                     err.span_suggestion(
374                         span,
375                         "consider importing the module directly",
376                         "".to_string(),
377                         Applicability::MachineApplicable,
378                     );
379
380                     // use foo::bar::self        -> foo::bar::{self}
381                     // use foo::bar::self as abc -> foo::bar::{self as abc}
382                     let braces = vec![
383                         (span_with_rename.shrink_to_lo(), "{".to_string()),
384                         (span_with_rename.shrink_to_hi(), "}".to_string()),
385                     ];
386                     err.multipart_suggestion(
387                         "alternatively, use the multi-path `use` syntax to import `self`",
388                         braces,
389                         Applicability::MachineApplicable,
390                     );
391                 }
392                 err
393             }
394             ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
395                 let mut err = struct_span_err!(
396                     self.session,
397                     span,
398                     E0430,
399                     "`self` import can only appear once in an import list"
400                 );
401                 err.span_label(span, "can only appear once in an import list");
402                 err
403             }
404             ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
405                 let mut err = struct_span_err!(
406                     self.session,
407                     span,
408                     E0431,
409                     "`self` import can only appear in an import list with \
410                                                 a non-empty prefix"
411                 );
412                 err.span_label(span, "can only appear in an import list with a non-empty prefix");
413                 err
414             }
415             ResolutionError::FailedToResolve { label, suggestion } => {
416                 let mut err =
417                     struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
418                 err.span_label(span, label);
419
420                 if let Some((suggestions, msg, applicability)) = suggestion {
421                     err.multipart_suggestion(&msg, suggestions, applicability);
422                 }
423
424                 err
425             }
426             ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
427                 let mut err = struct_span_err!(
428                     self.session,
429                     span,
430                     E0434,
431                     "{}",
432                     "can't capture dynamic environment in a fn item"
433                 );
434                 err.help("use the `|| { ... }` closure form instead");
435                 err
436             }
437             ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
438                 let mut err = struct_span_err!(
439                     self.session,
440                     span,
441                     E0435,
442                     "attempt to use a non-constant value in a constant"
443                 );
444                 // let foo =...
445                 //     ^^^ given this Span
446                 // ------- get this Span to have an applicable suggestion
447                 let sp =
448                     self.session.source_map().span_extend_to_prev_str(ident.span, current, true);
449                 if sp.lo().0 == 0 {
450                     err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
451                 } else {
452                     let sp = sp.with_lo(BytePos(sp.lo().0 - current.len() as u32));
453                     err.span_suggestion(
454                         sp,
455                         &format!("consider using `{}` instead of `{}`", sugg, current),
456                         format!("{} {}", sugg, ident),
457                         Applicability::MaybeIncorrect,
458                     );
459                     err.span_label(span, "non-constant value");
460                 }
461                 err
462             }
463             ResolutionError::BindingShadowsSomethingUnacceptable {
464                 shadowing_binding_descr,
465                 name,
466                 participle,
467                 article,
468                 shadowed_binding_descr,
469                 shadowed_binding_span,
470             } => {
471                 let mut err = struct_span_err!(
472                     self.session,
473                     span,
474                     E0530,
475                     "{}s cannot shadow {}s",
476                     shadowing_binding_descr,
477                     shadowed_binding_descr,
478                 );
479                 err.span_label(
480                     span,
481                     format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
482                 );
483                 let msg =
484                     format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
485                 err.span_label(shadowed_binding_span, msg);
486                 err
487             }
488             ResolutionError::ForwardDeclaredGenericParam => {
489                 let mut err = struct_span_err!(
490                     self.session,
491                     span,
492                     E0128,
493                     "generic parameters with a default cannot use \
494                                                 forward declared identifiers"
495                 );
496                 err.span_label(
497                     span,
498                     "defaulted generic parameters cannot be forward declared".to_string(),
499                 );
500                 err
501             }
502             ResolutionError::ParamInTyOfConstParam(name) => {
503                 let mut err = struct_span_err!(
504                     self.session,
505                     span,
506                     E0770,
507                     "the type of const parameters must not depend on other generic parameters"
508                 );
509                 err.span_label(
510                     span,
511                     format!("the type must not depend on the parameter `{}`", name),
512                 );
513                 err
514             }
515             ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
516                 let mut err = self.session.struct_span_err(
517                     span,
518                     "generic parameters may not be used in const operations",
519                 );
520                 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
521
522                 if is_type {
523                     err.note("type parameters may not be used in const expressions");
524                 } else {
525                     err.help(&format!(
526                         "const parameters may only be used as standalone arguments, i.e. `{}`",
527                         name
528                     ));
529                 }
530
531                 if self.session.is_nightly_build() {
532                     err.help(
533                         "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
534                     );
535                 }
536
537                 err
538             }
539             ResolutionError::SelfInGenericParamDefault => {
540                 let mut err = struct_span_err!(
541                     self.session,
542                     span,
543                     E0735,
544                     "generic parameters cannot use `Self` in their defaults"
545                 );
546                 err.span_label(span, "`Self` in generic parameter default".to_string());
547                 err
548             }
549             ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
550                 let mut err = struct_span_err!(
551                     self.session,
552                     span,
553                     E0767,
554                     "use of unreachable label `{}`",
555                     name,
556                 );
557
558                 err.span_label(definition_span, "unreachable label defined here");
559                 err.span_label(span, format!("unreachable label `{}`", name));
560                 err.note(
561                     "labels are unreachable through functions, closures, async blocks and modules",
562                 );
563
564                 match suggestion {
565                     // A reachable label with a similar name exists.
566                     Some((ident, true)) => {
567                         err.span_label(ident.span, "a label with a similar name is reachable");
568                         err.span_suggestion(
569                             span,
570                             "try using similarly named label",
571                             ident.name.to_string(),
572                             Applicability::MaybeIncorrect,
573                         );
574                     }
575                     // An unreachable label with a similar name exists.
576                     Some((ident, false)) => {
577                         err.span_label(
578                             ident.span,
579                             "a label with a similar name exists but is also unreachable",
580                         );
581                     }
582                     // No similarly-named labels exist.
583                     None => (),
584                 }
585
586                 err
587             }
588         }
589     }
590
591     crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
592         match vis_resolution_error {
593             VisResolutionError::Relative2018(span, path) => {
594                 let mut err = self.session.struct_span_err(
595                     span,
596                     "relative paths are not supported in visibilities on 2018 edition",
597                 );
598                 err.span_suggestion(
599                     path.span,
600                     "try",
601                     format!("crate::{}", pprust::path_to_string(&path)),
602                     Applicability::MaybeIncorrect,
603                 );
604                 err
605             }
606             VisResolutionError::AncestorOnly(span) => struct_span_err!(
607                 self.session,
608                 span,
609                 E0742,
610                 "visibilities can only be restricted to ancestor modules"
611             ),
612             VisResolutionError::FailedToResolve(span, label, suggestion) => {
613                 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
614             }
615             VisResolutionError::ExpectedFound(span, path_str, res) => {
616                 let mut err = struct_span_err!(
617                     self.session,
618                     span,
619                     E0577,
620                     "expected module, found {} `{}`",
621                     res.descr(),
622                     path_str
623                 );
624                 err.span_label(span, "not a module");
625                 err
626             }
627             VisResolutionError::Indeterminate(span) => struct_span_err!(
628                 self.session,
629                 span,
630                 E0578,
631                 "cannot determine resolution for the visibility"
632             ),
633             VisResolutionError::ModuleOnly(span) => {
634                 self.session.struct_span_err(span, "visibility must resolve to a module")
635             }
636         }
637         .emit()
638     }
639
640     /// Lookup typo candidate in scope for a macro or import.
641     fn early_lookup_typo_candidate(
642         &mut self,
643         scope_set: ScopeSet<'a>,
644         parent_scope: &ParentScope<'a>,
645         ident: Ident,
646         filter_fn: &impl Fn(Res) -> bool,
647     ) -> Option<TypoSuggestion> {
648         let mut suggestions = Vec::new();
649         let ctxt = ident.span.ctxt();
650         self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
651             match scope {
652                 Scope::DeriveHelpers(expn_id) => {
653                     let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
654                     if filter_fn(res) {
655                         suggestions.extend(
656                             this.helper_attrs
657                                 .get(&expn_id)
658                                 .into_iter()
659                                 .flatten()
660                                 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
661                         );
662                     }
663                 }
664                 Scope::DeriveHelpersCompat => {
665                     let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
666                     if filter_fn(res) {
667                         for derive in parent_scope.derives {
668                             let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
669                             if let Ok((Some(ext), _)) = this.resolve_macro_path(
670                                 derive,
671                                 Some(MacroKind::Derive),
672                                 parent_scope,
673                                 false,
674                                 false,
675                             ) {
676                                 suggestions.extend(
677                                     ext.helper_attrs
678                                         .iter()
679                                         .map(|name| TypoSuggestion::typo_from_res(*name, res)),
680                                 );
681                             }
682                         }
683                     }
684                 }
685                 Scope::MacroRules(macro_rules_scope) => {
686                     if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
687                         let res = macro_rules_binding.binding.res();
688                         if filter_fn(res) {
689                             suggestions.push(TypoSuggestion::typo_from_res(
690                                 macro_rules_binding.ident.name,
691                                 res,
692                             ))
693                         }
694                     }
695                 }
696                 Scope::CrateRoot => {
697                     let root_ident = Ident::new(kw::PathRoot, ident.span);
698                     let root_module = this.resolve_crate_root(root_ident);
699                     this.add_module_candidates(root_module, &mut suggestions, filter_fn);
700                 }
701                 Scope::Module(module, _) => {
702                     this.add_module_candidates(module, &mut suggestions, filter_fn);
703                 }
704                 Scope::RegisteredAttrs => {
705                     let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
706                     if filter_fn(res) {
707                         suggestions.extend(
708                             this.registered_attrs
709                                 .iter()
710                                 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
711                         );
712                     }
713                 }
714                 Scope::MacroUsePrelude => {
715                     suggestions.extend(this.macro_use_prelude.iter().filter_map(
716                         |(name, binding)| {
717                             let res = binding.res();
718                             filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
719                         },
720                     ));
721                 }
722                 Scope::BuiltinAttrs => {
723                     let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
724                     if filter_fn(res) {
725                         suggestions.extend(
726                             BUILTIN_ATTRIBUTES
727                                 .iter()
728                                 .map(|(name, ..)| TypoSuggestion::typo_from_res(*name, res)),
729                         );
730                     }
731                 }
732                 Scope::ExternPrelude => {
733                     suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
734                         let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
735                         filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
736                     }));
737                 }
738                 Scope::ToolPrelude => {
739                     let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
740                     suggestions.extend(
741                         this.registered_tools
742                             .iter()
743                             .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
744                     );
745                 }
746                 Scope::StdLibPrelude => {
747                     if let Some(prelude) = this.prelude {
748                         let mut tmp_suggestions = Vec::new();
749                         this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
750                         suggestions.extend(
751                             tmp_suggestions
752                                 .into_iter()
753                                 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
754                         );
755                     }
756                 }
757                 Scope::BuiltinTypes => {
758                     suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
759                         let res = Res::PrimTy(*prim_ty);
760                         filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
761                     }))
762                 }
763             }
764
765             None::<()>
766         });
767
768         // Make sure error reporting is deterministic.
769         suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
770
771         match find_best_match_for_name(
772             &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
773             ident.name,
774             None,
775         ) {
776             Some(found) if found != ident.name => {
777                 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
778             }
779             _ => None,
780         }
781     }
782
783     fn lookup_import_candidates_from_module<FilterFn>(
784         &mut self,
785         lookup_ident: Ident,
786         namespace: Namespace,
787         parent_scope: &ParentScope<'a>,
788         start_module: Module<'a>,
789         crate_name: Ident,
790         filter_fn: FilterFn,
791     ) -> Vec<ImportSuggestion>
792     where
793         FilterFn: Fn(Res) -> bool,
794     {
795         let mut candidates = Vec::new();
796         let mut seen_modules = FxHashSet::default();
797         let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
798         let mut worklist_via_import = vec![];
799
800         while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
801             None => worklist_via_import.pop(),
802             Some(x) => Some(x),
803         } {
804             let in_module_is_extern = !in_module.def_id().is_local();
805             // We have to visit module children in deterministic order to avoid
806             // instabilities in reported imports (#43552).
807             in_module.for_each_child(self, |this, ident, ns, name_binding| {
808                 // avoid non-importable candidates
809                 if !name_binding.is_importable() {
810                     return;
811                 }
812
813                 let child_accessible =
814                     accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
815
816                 // do not venture inside inaccessible items of other crates
817                 if in_module_is_extern && !child_accessible {
818                     return;
819                 }
820
821                 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
822
823                 // There is an assumption elsewhere that paths of variants are in the enum's
824                 // declaration and not imported. With this assumption, the variant component is
825                 // chopped and the rest of the path is assumed to be the enum's own path. For
826                 // errors where a variant is used as the type instead of the enum, this causes
827                 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
828                 if via_import && name_binding.is_possibly_imported_variant() {
829                     return;
830                 }
831
832                 // #90113: Do not count an inaccessible reexported item as a candidate.
833                 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
834                     if this.is_accessible_from(binding.vis, parent_scope.module)
835                         && !this.is_accessible_from(name_binding.vis, parent_scope.module)
836                     {
837                         return;
838                     }
839                 }
840
841                 // collect results based on the filter function
842                 // avoid suggesting anything from the same module in which we are resolving
843                 if ident.name == lookup_ident.name
844                     && ns == namespace
845                     && !ptr::eq(in_module, parent_scope.module)
846                 {
847                     let res = name_binding.res();
848                     if filter_fn(res) {
849                         // create the path
850                         let mut segms = path_segments.clone();
851                         if lookup_ident.span.rust_2018() {
852                             // crate-local absolute paths start with `crate::` in edition 2018
853                             // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
854                             segms.insert(0, ast::PathSegment::from_ident(crate_name));
855                         }
856
857                         segms.push(ast::PathSegment::from_ident(ident));
858                         let path = Path { span: name_binding.span, segments: segms, tokens: None };
859                         let did = match res {
860                             Res::Def(DefKind::Ctor(..), did) => this.parent(did),
861                             _ => res.opt_def_id(),
862                         };
863
864                         if child_accessible {
865                             // Remove invisible match if exists
866                             if let Some(idx) = candidates
867                                 .iter()
868                                 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
869                             {
870                                 candidates.remove(idx);
871                             }
872                         }
873
874                         if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
875                             candidates.push(ImportSuggestion {
876                                 did,
877                                 descr: res.descr(),
878                                 path,
879                                 accessible: child_accessible,
880                             });
881                         }
882                     }
883                 }
884
885                 // collect submodules to explore
886                 if let Some(module) = name_binding.module() {
887                     // form the path
888                     let mut path_segments = path_segments.clone();
889                     path_segments.push(ast::PathSegment::from_ident(ident));
890
891                     let is_extern_crate_that_also_appears_in_prelude =
892                         name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
893
894                     if !is_extern_crate_that_also_appears_in_prelude {
895                         // add the module to the lookup
896                         if seen_modules.insert(module.def_id()) {
897                             if via_import { &mut worklist_via_import } else { &mut worklist }
898                                 .push((module, path_segments, child_accessible));
899                         }
900                     }
901                 }
902             })
903         }
904
905         // If only some candidates are accessible, take just them
906         if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
907             candidates = candidates.into_iter().filter(|x| x.accessible).collect();
908         }
909
910         candidates
911     }
912
913     /// When name resolution fails, this method can be used to look up candidate
914     /// entities with the expected name. It allows filtering them using the
915     /// supplied predicate (which should be used to only accept the types of
916     /// definitions expected, e.g., traits). The lookup spans across all crates.
917     ///
918     /// N.B., the method does not look into imports, but this is not a problem,
919     /// since we report the definitions (thus, the de-aliased imports).
920     crate fn lookup_import_candidates<FilterFn>(
921         &mut self,
922         lookup_ident: Ident,
923         namespace: Namespace,
924         parent_scope: &ParentScope<'a>,
925         filter_fn: FilterFn,
926     ) -> Vec<ImportSuggestion>
927     where
928         FilterFn: Fn(Res) -> bool,
929     {
930         let mut suggestions = self.lookup_import_candidates_from_module(
931             lookup_ident,
932             namespace,
933             parent_scope,
934             self.graph_root,
935             Ident::with_dummy_span(kw::Crate),
936             &filter_fn,
937         );
938
939         if lookup_ident.span.rust_2018() {
940             let extern_prelude_names = self.extern_prelude.clone();
941             for (ident, _) in extern_prelude_names.into_iter() {
942                 if ident.span.from_expansion() {
943                     // Idents are adjusted to the root context before being
944                     // resolved in the extern prelude, so reporting this to the
945                     // user is no help. This skips the injected
946                     // `extern crate std` in the 2018 edition, which would
947                     // otherwise cause duplicate suggestions.
948                     continue;
949                 }
950                 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
951                     let crate_root = self.expect_module(crate_id.as_def_id());
952                     suggestions.extend(self.lookup_import_candidates_from_module(
953                         lookup_ident,
954                         namespace,
955                         parent_scope,
956                         crate_root,
957                         ident,
958                         &filter_fn,
959                     ));
960                 }
961             }
962         }
963
964         suggestions
965     }
966
967     crate fn unresolved_macro_suggestions(
968         &mut self,
969         err: &mut DiagnosticBuilder<'a>,
970         macro_kind: MacroKind,
971         parent_scope: &ParentScope<'a>,
972         ident: Ident,
973     ) {
974         let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
975         let suggestion = self.early_lookup_typo_candidate(
976             ScopeSet::Macro(macro_kind),
977             parent_scope,
978             ident,
979             is_expected,
980         );
981         self.add_typo_suggestion(err, suggestion, ident.span);
982
983         let import_suggestions =
984             self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
985         show_candidates(
986             &self.definitions,
987             self.session,
988             err,
989             None,
990             &import_suggestions,
991             false,
992             true,
993         );
994
995         if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
996             let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
997             err.span_note(ident.span, &msg);
998             return;
999         }
1000         if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1001             err.help("have you added the `#[macro_use]` on the module/import?");
1002             return;
1003         }
1004         for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1005             if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1006                 ident,
1007                 ScopeSet::All(ns, false),
1008                 &parent_scope,
1009                 false,
1010                 false,
1011                 ident.span,
1012             ) {
1013                 let desc = match binding.res() {
1014                     Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1015                         "a function-like macro".to_string()
1016                     }
1017                     Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1018                         format!("an attribute: `#[{}]`", ident)
1019                     }
1020                     Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1021                         format!("a derive macro: `#[derive({})]`", ident)
1022                     }
1023                     Res::ToolMod => {
1024                         // Don't confuse the user with tool modules.
1025                         continue;
1026                     }
1027                     Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1028                         "only a trait, without a derive macro".to_string()
1029                     }
1030                     res => format!(
1031                         "{} {}, not {} {}",
1032                         res.article(),
1033                         res.descr(),
1034                         macro_kind.article(),
1035                         macro_kind.descr_expected(),
1036                     ),
1037                 };
1038                 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1039                     if !import.span.is_dummy() {
1040                         err.span_note(
1041                             import.span,
1042                             &format!("`{}` is imported here, but it is {}", ident, desc),
1043                         );
1044                         // Silence the 'unused import' warning we might get,
1045                         // since this diagnostic already covers that import.
1046                         self.record_use(ident, binding, false);
1047                         return;
1048                     }
1049                 }
1050                 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1051                 return;
1052             }
1053         }
1054     }
1055
1056     crate fn add_typo_suggestion(
1057         &self,
1058         err: &mut DiagnosticBuilder<'_>,
1059         suggestion: Option<TypoSuggestion>,
1060         span: Span,
1061     ) -> bool {
1062         let suggestion = match suggestion {
1063             None => return false,
1064             // We shouldn't suggest underscore.
1065             Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1066             Some(suggestion) => suggestion,
1067         };
1068         let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1069             LOCAL_CRATE => self.opt_span(def_id),
1070             _ => Some(
1071                 self.session
1072                     .source_map()
1073                     .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1074             ),
1075         });
1076         if let Some(def_span) = def_span {
1077             if span.overlaps(def_span) {
1078                 // Don't suggest typo suggestion for itself like in the following:
1079                 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1080                 //   --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1081                 //    |
1082                 // LL | struct X {}
1083                 //    | ----------- `X` defined here
1084                 // LL |
1085                 // LL | const Y: X = X("ö");
1086                 //    | -------------^^^^^^- similarly named constant `Y` defined here
1087                 //    |
1088                 // help: use struct literal syntax instead
1089                 //    |
1090                 // LL | const Y: X = X {};
1091                 //    |              ^^^^
1092                 // help: a constant with a similar name exists
1093                 //    |
1094                 // LL | const Y: X = Y("ö");
1095                 //    |              ^
1096                 return false;
1097             }
1098             let prefix = match suggestion.target {
1099                 SuggestionTarget::SimilarlyNamed => "similarly named ",
1100                 SuggestionTarget::SingleItem => "",
1101             };
1102
1103             err.span_label(
1104                 self.session.source_map().guess_head_span(def_span),
1105                 &format!(
1106                     "{}{} `{}` defined here",
1107                     prefix,
1108                     suggestion.res.descr(),
1109                     suggestion.candidate.as_str(),
1110                 ),
1111             );
1112         }
1113         let msg = match suggestion.target {
1114             SuggestionTarget::SimilarlyNamed => format!(
1115                 "{} {} with a similar name exists",
1116                 suggestion.res.article(),
1117                 suggestion.res.descr()
1118             ),
1119             SuggestionTarget::SingleItem => {
1120                 format!("maybe you meant this {}", suggestion.res.descr())
1121             }
1122         };
1123         err.span_suggestion(
1124             span,
1125             &msg,
1126             suggestion.candidate.to_string(),
1127             Applicability::MaybeIncorrect,
1128         );
1129         true
1130     }
1131
1132     fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1133         let res = b.res();
1134         if b.span.is_dummy() {
1135             // These already contain the "built-in" prefix or look bad with it.
1136             let add_built_in =
1137                 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1138             let (built_in, from) = if from_prelude {
1139                 ("", " from prelude")
1140             } else if b.is_extern_crate()
1141                 && !b.is_import()
1142                 && self.session.opts.externs.get(&ident.as_str()).is_some()
1143             {
1144                 ("", " passed with `--extern`")
1145             } else if add_built_in {
1146                 (" built-in", "")
1147             } else {
1148                 ("", "")
1149             };
1150
1151             let a = if built_in.is_empty() { res.article() } else { "a" };
1152             format!("{a}{built_in} {thing}{from}", thing = res.descr())
1153         } else {
1154             let introduced = if b.is_import() { "imported" } else { "defined" };
1155             format!("the {thing} {introduced} here", thing = res.descr())
1156         }
1157     }
1158
1159     crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1160         let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1161         let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1162             // We have to print the span-less alternative first, otherwise formatting looks bad.
1163             (b2, b1, misc2, misc1, true)
1164         } else {
1165             (b1, b2, misc1, misc2, false)
1166         };
1167
1168         let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1169         err.span_label(ident.span, "ambiguous name");
1170         err.note(&format!("ambiguous because of {}", kind.descr()));
1171
1172         let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1173             let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1174             let note_msg = format!("`{ident}` could{also} refer to {what}");
1175
1176             let thing = b.res().descr();
1177             let mut help_msgs = Vec::new();
1178             if b.is_glob_import()
1179                 && (kind == AmbiguityKind::GlobVsGlob
1180                     || kind == AmbiguityKind::GlobVsExpanded
1181                     || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1182             {
1183                 help_msgs.push(format!(
1184                     "consider adding an explicit import of `{ident}` to disambiguate"
1185                 ))
1186             }
1187             if b.is_extern_crate() && ident.span.rust_2018() {
1188                 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1189             }
1190             if misc == AmbiguityErrorMisc::SuggestCrate {
1191                 help_msgs
1192                     .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1193             } else if misc == AmbiguityErrorMisc::SuggestSelf {
1194                 help_msgs
1195                     .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1196             }
1197
1198             err.span_note(b.span, &note_msg);
1199             for (i, help_msg) in help_msgs.iter().enumerate() {
1200                 let or = if i == 0 { "" } else { "or " };
1201                 err.help(&format!("{}{}", or, help_msg));
1202             }
1203         };
1204
1205         could_refer_to(b1, misc1, "");
1206         could_refer_to(b2, misc2, " also");
1207         err.emit();
1208     }
1209
1210     /// If the binding refers to a tuple struct constructor with fields,
1211     /// returns the span of its fields.
1212     fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1213         if let NameBindingKind::Res(
1214             Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1215             _,
1216         ) = binding.kind
1217         {
1218             let def_id = self.parent(ctor_def_id).expect("no parent for a constructor");
1219             let fields = self.field_names.get(&def_id)?;
1220             return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1221         }
1222         None
1223     }
1224
1225     crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1226         let PrivacyError { ident, binding, .. } = *privacy_error;
1227
1228         let res = binding.res();
1229         let ctor_fields_span = self.ctor_fields_span(binding);
1230         let plain_descr = res.descr().to_string();
1231         let nonimport_descr =
1232             if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1233         let import_descr = nonimport_descr.clone() + " import";
1234         let get_descr =
1235             |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1236
1237         // Print the primary message.
1238         let descr = get_descr(binding);
1239         let mut err =
1240             struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1241         err.span_label(ident.span, &format!("private {}", descr));
1242         if let Some(span) = ctor_fields_span {
1243             err.span_label(span, "a constructor is private if any of the fields is private");
1244         }
1245
1246         // Print the whole import chain to make it easier to see what happens.
1247         let first_binding = binding;
1248         let mut next_binding = Some(binding);
1249         let mut next_ident = ident;
1250         while let Some(binding) = next_binding {
1251             let name = next_ident;
1252             next_binding = match binding.kind {
1253                 _ if res == Res::Err => None,
1254                 NameBindingKind::Import { binding, import, .. } => match import.kind {
1255                     _ if binding.span.is_dummy() => None,
1256                     ImportKind::Single { source, .. } => {
1257                         next_ident = source;
1258                         Some(binding)
1259                     }
1260                     ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1261                     ImportKind::ExternCrate { .. } => None,
1262                 },
1263                 _ => None,
1264             };
1265
1266             let first = ptr::eq(binding, first_binding);
1267             let msg = format!(
1268                 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1269                 and_refers_to = if first { "" } else { "...and refers to " },
1270                 item = get_descr(binding),
1271                 which = if first { "" } else { " which" },
1272                 dots = if next_binding.is_some() { "..." } else { "" },
1273             );
1274             let def_span = self.session.source_map().guess_head_span(binding.span);
1275             let mut note_span = MultiSpan::from_span(def_span);
1276             if !first && binding.vis == ty::Visibility::Public {
1277                 note_span.push_span_label(def_span, "consider importing it directly".into());
1278             }
1279             err.span_note(note_span, &msg);
1280         }
1281
1282         err.emit();
1283     }
1284
1285     crate fn find_similarly_named_module_or_crate(
1286         &mut self,
1287         ident: Symbol,
1288         current_module: &Module<'a>,
1289     ) -> Option<Symbol> {
1290         let mut candidates = self
1291             .extern_prelude
1292             .iter()
1293             .map(|(ident, _)| ident.name)
1294             .chain(
1295                 self.module_map
1296                     .iter()
1297                     .filter(|(_, module)| {
1298                         current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1299                     })
1300                     .map(|(_, module)| module.kind.name())
1301                     .flatten(),
1302             )
1303             .filter(|c| !c.to_string().is_empty())
1304             .collect::<Vec<_>>();
1305         candidates.sort();
1306         candidates.dedup();
1307         match find_best_match_for_name(&candidates, ident, None) {
1308             Some(sugg) if sugg == ident => None,
1309             sugg => sugg,
1310         }
1311     }
1312 }
1313
1314 impl<'a, 'b> ImportResolver<'a, 'b> {
1315     /// Adds suggestions for a path that cannot be resolved.
1316     pub(crate) fn make_path_suggestion(
1317         &mut self,
1318         span: Span,
1319         mut path: Vec<Segment>,
1320         parent_scope: &ParentScope<'b>,
1321     ) -> Option<(Vec<Segment>, Vec<String>)> {
1322         debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1323
1324         match (path.get(0), path.get(1)) {
1325             // `{{root}}::ident::...` on both editions.
1326             // On 2015 `{{root}}` is usually added implicitly.
1327             (Some(fst), Some(snd))
1328                 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1329             // `ident::...` on 2018.
1330             (Some(fst), _)
1331                 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1332             {
1333                 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1334                 path.insert(0, Segment::from_ident(Ident::empty()));
1335             }
1336             _ => return None,
1337         }
1338
1339         self.make_missing_self_suggestion(span, path.clone(), parent_scope)
1340             .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
1341             .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
1342             .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1343     }
1344
1345     /// Suggest a missing `self::` if that resolves to an correct module.
1346     ///
1347     /// ```text
1348     ///    |
1349     /// LL | use foo::Bar;
1350     ///    |     ^^^ did you mean `self::foo`?
1351     /// ```
1352     fn make_missing_self_suggestion(
1353         &mut self,
1354         span: Span,
1355         mut path: Vec<Segment>,
1356         parent_scope: &ParentScope<'b>,
1357     ) -> Option<(Vec<Segment>, Vec<String>)> {
1358         // Replace first ident with `self` and check if that is valid.
1359         path[0].ident.name = kw::SelfLower;
1360         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1361         debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1362         if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1363     }
1364
1365     /// Suggests a missing `crate::` if that resolves to an correct module.
1366     ///
1367     /// ```text
1368     ///    |
1369     /// LL | use foo::Bar;
1370     ///    |     ^^^ did you mean `crate::foo`?
1371     /// ```
1372     fn make_missing_crate_suggestion(
1373         &mut self,
1374         span: Span,
1375         mut path: Vec<Segment>,
1376         parent_scope: &ParentScope<'b>,
1377     ) -> Option<(Vec<Segment>, Vec<String>)> {
1378         // Replace first ident with `crate` and check if that is valid.
1379         path[0].ident.name = kw::Crate;
1380         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1381         debug!("make_missing_crate_suggestion:  path={:?} result={:?}", path, result);
1382         if let PathResult::Module(..) = result {
1383             Some((
1384                 path,
1385                 vec![
1386                     "`use` statements changed in Rust 2018; read more at \
1387                      <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1388                      clarity.html>"
1389                         .to_string(),
1390                 ],
1391             ))
1392         } else {
1393             None
1394         }
1395     }
1396
1397     /// Suggests a missing `super::` if that resolves to an correct module.
1398     ///
1399     /// ```text
1400     ///    |
1401     /// LL | use foo::Bar;
1402     ///    |     ^^^ did you mean `super::foo`?
1403     /// ```
1404     fn make_missing_super_suggestion(
1405         &mut self,
1406         span: Span,
1407         mut path: Vec<Segment>,
1408         parent_scope: &ParentScope<'b>,
1409     ) -> Option<(Vec<Segment>, Vec<String>)> {
1410         // Replace first ident with `crate` and check if that is valid.
1411         path[0].ident.name = kw::Super;
1412         let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1413         debug!("make_missing_super_suggestion:  path={:?} result={:?}", path, result);
1414         if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1415     }
1416
1417     /// Suggests a missing external crate name if that resolves to an correct module.
1418     ///
1419     /// ```text
1420     ///    |
1421     /// LL | use foobar::Baz;
1422     ///    |     ^^^^^^ did you mean `baz::foobar`?
1423     /// ```
1424     ///
1425     /// Used when importing a submodule of an external crate but missing that crate's
1426     /// name as the first part of path.
1427     fn make_external_crate_suggestion(
1428         &mut self,
1429         span: Span,
1430         mut path: Vec<Segment>,
1431         parent_scope: &ParentScope<'b>,
1432     ) -> Option<(Vec<Segment>, Vec<String>)> {
1433         if path[1].ident.span.rust_2015() {
1434             return None;
1435         }
1436
1437         // Sort extern crate names in reverse order to get
1438         // 1) some consistent ordering for emitted diagnostics, and
1439         // 2) `std` suggestions before `core` suggestions.
1440         let mut extern_crate_names =
1441             self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1442         extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
1443
1444         for name in extern_crate_names.into_iter() {
1445             // Replace first ident with a crate name and check if that is valid.
1446             path[0].ident.name = name;
1447             let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1448             debug!(
1449                 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1450                 name, path, result
1451             );
1452             if let PathResult::Module(..) = result {
1453                 return Some((path, Vec::new()));
1454             }
1455         }
1456
1457         None
1458     }
1459
1460     /// Suggests importing a macro from the root of the crate rather than a module within
1461     /// the crate.
1462     ///
1463     /// ```text
1464     /// help: a macro with this name exists at the root of the crate
1465     ///    |
1466     /// LL | use issue_59764::makro;
1467     ///    |     ^^^^^^^^^^^^^^^^^^
1468     ///    |
1469     ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
1470     ///            at the root of the crate instead of the module where it is defined
1471     /// ```
1472     pub(crate) fn check_for_module_export_macro(
1473         &mut self,
1474         import: &'b Import<'b>,
1475         module: ModuleOrUniformRoot<'b>,
1476         ident: Ident,
1477     ) -> Option<(Option<Suggestion>, Vec<String>)> {
1478         let ModuleOrUniformRoot::Module(mut crate_module) = module else {
1479             return None;
1480         };
1481
1482         while let Some(parent) = crate_module.parent {
1483             crate_module = parent;
1484         }
1485
1486         if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1487             // Don't make a suggestion if the import was already from the root of the
1488             // crate.
1489             return None;
1490         }
1491
1492         let resolutions = self.r.resolutions(crate_module).borrow();
1493         let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1494         let binding = resolution.borrow().binding()?;
1495         if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1496             let module_name = crate_module.kind.name().unwrap();
1497             let import_snippet = match import.kind {
1498                 ImportKind::Single { source, target, .. } if source != target => {
1499                     format!("{} as {}", source, target)
1500                 }
1501                 _ => format!("{}", ident),
1502             };
1503
1504             let mut corrections: Vec<(Span, String)> = Vec::new();
1505             if !import.is_nested() {
1506                 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1507                 // intermediate segments.
1508                 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
1509             } else {
1510                 // Find the binding span (and any trailing commas and spaces).
1511                 //   ie. `use a::b::{c, d, e};`
1512                 //                      ^^^
1513                 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1514                     self.r.session,
1515                     import.span,
1516                     import.use_span,
1517                 );
1518                 debug!(
1519                     "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1520                     found_closing_brace, binding_span
1521                 );
1522
1523                 let mut removal_span = binding_span;
1524                 if found_closing_brace {
1525                     // If the binding span ended with a closing brace, as in the below example:
1526                     //   ie. `use a::b::{c, d};`
1527                     //                      ^
1528                     // Then expand the span of characters to remove to include the previous
1529                     // binding's trailing comma.
1530                     //   ie. `use a::b::{c, d};`
1531                     //                    ^^^
1532                     if let Some(previous_span) =
1533                         extend_span_to_previous_binding(self.r.session, binding_span)
1534                     {
1535                         debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1536                         removal_span = removal_span.with_lo(previous_span.lo());
1537                     }
1538                 }
1539                 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1540
1541                 // Remove the `removal_span`.
1542                 corrections.push((removal_span, "".to_string()));
1543
1544                 // Find the span after the crate name and if it has nested imports immediatately
1545                 // after the crate name already.
1546                 //   ie. `use a::b::{c, d};`
1547                 //               ^^^^^^^^^
1548                 //   or  `use a::{b, c, d}};`
1549                 //               ^^^^^^^^^^^
1550                 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1551                     self.r.session,
1552                     module_name,
1553                     import.use_span,
1554                 );
1555                 debug!(
1556                     "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1557                     has_nested, after_crate_name
1558                 );
1559
1560                 let source_map = self.r.session.source_map();
1561
1562                 // Add the import to the start, with a `{` if required.
1563                 let start_point = source_map.start_point(after_crate_name);
1564                 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1565                     corrections.push((
1566                         start_point,
1567                         if has_nested {
1568                             // In this case, `start_snippet` must equal '{'.
1569                             format!("{}{}, ", start_snippet, import_snippet)
1570                         } else {
1571                             // In this case, add a `{`, then the moved import, then whatever
1572                             // was there before.
1573                             format!("{{{}, {}", import_snippet, start_snippet)
1574                         },
1575                     ));
1576                 }
1577
1578                 // Add a `};` to the end if nested, matching the `{` added at the start.
1579                 if !has_nested {
1580                     corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1581                 }
1582             }
1583
1584             let suggestion = Some((
1585                 corrections,
1586                 String::from("a macro with this name exists at the root of the crate"),
1587                 Applicability::MaybeIncorrect,
1588             ));
1589             let note = vec![
1590                 "this could be because a macro annotated with `#[macro_export]` will be exported \
1591                  at the root of the crate instead of the module where it is defined"
1592                     .to_string(),
1593             ];
1594             Some((suggestion, note))
1595         } else {
1596             None
1597         }
1598     }
1599 }
1600
1601 /// Given a `binding_span` of a binding within a use statement:
1602 ///
1603 /// ```
1604 /// use foo::{a, b, c};
1605 ///              ^
1606 /// ```
1607 ///
1608 /// then return the span until the next binding or the end of the statement:
1609 ///
1610 /// ```
1611 /// use foo::{a, b, c};
1612 ///              ^^^
1613 /// ```
1614 pub(crate) fn find_span_of_binding_until_next_binding(
1615     sess: &Session,
1616     binding_span: Span,
1617     use_span: Span,
1618 ) -> (bool, Span) {
1619     let source_map = sess.source_map();
1620
1621     // Find the span of everything after the binding.
1622     //   ie. `a, e};` or `a};`
1623     let binding_until_end = binding_span.with_hi(use_span.hi());
1624
1625     // Find everything after the binding but not including the binding.
1626     //   ie. `, e};` or `};`
1627     let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1628
1629     // Keep characters in the span until we encounter something that isn't a comma or
1630     // whitespace.
1631     //   ie. `, ` or ``.
1632     //
1633     // Also note whether a closing brace character was encountered. If there
1634     // was, then later go backwards to remove any trailing commas that are left.
1635     let mut found_closing_brace = false;
1636     let after_binding_until_next_binding =
1637         source_map.span_take_while(after_binding_until_end, |&ch| {
1638             if ch == '}' {
1639                 found_closing_brace = true;
1640             }
1641             ch == ' ' || ch == ','
1642         });
1643
1644     // Combine the two spans.
1645     //   ie. `a, ` or `a`.
1646     //
1647     // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1648     let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1649
1650     (found_closing_brace, span)
1651 }
1652
1653 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1654 /// binding.
1655 ///
1656 /// ```
1657 /// use foo::a::{a, b, c};
1658 ///               ^^--- binding span
1659 ///               |
1660 ///               returned span
1661 ///
1662 /// use foo::{a, b, c};
1663 ///           --- binding span
1664 /// ```
1665 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1666     let source_map = sess.source_map();
1667
1668     // `prev_source` will contain all of the source that came before the span.
1669     // Then split based on a command and take the first (ie. closest to our span)
1670     // snippet. In the example, this is a space.
1671     let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1672
1673     let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1674     let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1675     if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1676         return None;
1677     }
1678
1679     let prev_comma = prev_comma.first().unwrap();
1680     let prev_starting_brace = prev_starting_brace.first().unwrap();
1681
1682     // If the amount of source code before the comma is greater than
1683     // the amount of source code before the starting brace then we've only
1684     // got one item in the nested item (eg. `issue_52891::{self}`).
1685     if prev_comma.len() > prev_starting_brace.len() {
1686         return None;
1687     }
1688
1689     Some(binding_span.with_lo(BytePos(
1690         // Take away the number of bytes for the characters we've found and an
1691         // extra for the comma.
1692         binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1693     )))
1694 }
1695
1696 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1697 /// it is a nested use tree.
1698 ///
1699 /// ```
1700 /// use foo::a::{b, c};
1701 ///          ^^^^^^^^^^ // false
1702 ///
1703 /// use foo::{a, b, c};
1704 ///          ^^^^^^^^^^ // true
1705 ///
1706 /// use foo::{a, b::{c, d}};
1707 ///          ^^^^^^^^^^^^^^^ // true
1708 /// ```
1709 fn find_span_immediately_after_crate_name(
1710     sess: &Session,
1711     module_name: Symbol,
1712     use_span: Span,
1713 ) -> (bool, Span) {
1714     debug!(
1715         "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1716         module_name, use_span
1717     );
1718     let source_map = sess.source_map();
1719
1720     // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1721     let mut num_colons = 0;
1722     // Find second colon.. `use issue_59764:`
1723     let until_second_colon = source_map.span_take_while(use_span, |c| {
1724         if *c == ':' {
1725             num_colons += 1;
1726         }
1727         !matches!(c, ':' if num_colons == 2)
1728     });
1729     // Find everything after the second colon.. `foo::{baz, makro};`
1730     let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1731
1732     let mut found_a_non_whitespace_character = false;
1733     // Find the first non-whitespace character in `from_second_colon`.. `f`
1734     let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1735         if found_a_non_whitespace_character {
1736             return false;
1737         }
1738         if !c.is_whitespace() {
1739             found_a_non_whitespace_character = true;
1740         }
1741         true
1742     });
1743
1744     // Find the first `{` in from_second_colon.. `foo::{`
1745     let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1746
1747     (next_left_bracket == after_second_colon, from_second_colon)
1748 }
1749
1750 /// When an entity with a given name is not available in scope, we search for
1751 /// entities with that name in all crates. This method allows outputting the
1752 /// results of this search in a programmer-friendly way
1753 crate fn show_candidates(
1754     definitions: &rustc_hir::definitions::Definitions,
1755     session: &Session,
1756     err: &mut DiagnosticBuilder<'_>,
1757     // This is `None` if all placement locations are inside expansions
1758     use_placement_span: Option<Span>,
1759     candidates: &[ImportSuggestion],
1760     instead: bool,
1761     found_use: bool,
1762 ) {
1763     if candidates.is_empty() {
1764         return;
1765     }
1766
1767     let mut accessible_path_strings: Vec<(String, &str, Option<DefId>)> = Vec::new();
1768     let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>)> = Vec::new();
1769
1770     candidates.iter().for_each(|c| {
1771         (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
1772             .push((path_names_to_string(&c.path), c.descr, c.did))
1773     });
1774
1775     // we want consistent results across executions, but candidates are produced
1776     // by iterating through a hash map, so make sure they are ordered:
1777     for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
1778         path_strings.sort_by(|a, b| a.0.cmp(&b.0));
1779         let core_path_strings =
1780             path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
1781         path_strings.extend(core_path_strings);
1782         path_strings.dedup_by(|a, b| a.0 == b.0);
1783     }
1784
1785     if !accessible_path_strings.is_empty() {
1786         let (determiner, kind) = if accessible_path_strings.len() == 1 {
1787             ("this", accessible_path_strings[0].1)
1788         } else {
1789             ("one of these", "items")
1790         };
1791
1792         let instead = if instead { " instead" } else { "" };
1793         let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
1794
1795         if let Some(span) = use_placement_span {
1796             for candidate in &mut accessible_path_strings {
1797                 // produce an additional newline to separate the new use statement
1798                 // from the directly following item.
1799                 let additional_newline = if found_use { "" } else { "\n" };
1800                 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
1801             }
1802
1803             err.span_suggestions(
1804                 span,
1805                 &msg,
1806                 accessible_path_strings.into_iter().map(|a| a.0),
1807                 Applicability::Unspecified,
1808             );
1809         } else {
1810             msg.push(':');
1811
1812             for candidate in accessible_path_strings {
1813                 msg.push('\n');
1814                 msg.push_str(&candidate.0);
1815             }
1816
1817             err.note(&msg);
1818         }
1819     } else {
1820         assert!(!inaccessible_path_strings.is_empty());
1821
1822         if inaccessible_path_strings.len() == 1 {
1823             let (name, descr, def_id) = &inaccessible_path_strings[0];
1824             let msg = format!("{} `{}` exists but is inaccessible", descr, name);
1825
1826             if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1827                 let span = definitions.def_span(local_def_id);
1828                 let span = session.source_map().guess_head_span(span);
1829                 let mut multi_span = MultiSpan::from_span(span);
1830                 multi_span.push_span_label(span, "not accessible".to_string());
1831                 err.span_note(multi_span, &msg);
1832             } else {
1833                 err.note(&msg);
1834             }
1835         } else {
1836             let (_, descr_first, _) = &inaccessible_path_strings[0];
1837             let descr = if inaccessible_path_strings
1838                 .iter()
1839                 .skip(1)
1840                 .all(|(_, descr, _)| descr == descr_first)
1841             {
1842                 descr_first.to_string()
1843             } else {
1844                 "item".to_string()
1845             };
1846
1847             let mut msg = format!("these {}s exist but are inaccessible", descr);
1848             let mut has_colon = false;
1849
1850             let mut spans = Vec::new();
1851             for (name, _, def_id) in &inaccessible_path_strings {
1852                 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1853                     let span = definitions.def_span(local_def_id);
1854                     let span = session.source_map().guess_head_span(span);
1855                     spans.push((name, span));
1856                 } else {
1857                     if !has_colon {
1858                         msg.push(':');
1859                         has_colon = true;
1860                     }
1861                     msg.push('\n');
1862                     msg.push_str(name);
1863                 }
1864             }
1865
1866             let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
1867             for (name, span) in spans {
1868                 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
1869             }
1870
1871             err.span_note(multi_span, &msg);
1872         }
1873     }
1874 }