rustc_resolve/
diagnostics.rs

1use rustc_ast::visit::{self, Visitor};
2use rustc_ast::{
3    self as ast, CRATE_NODE_ID, Crate, ItemKind, ModKind, NodeId, Path, join_path_idents,
4};
5use rustc_ast_pretty::pprust;
6use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7use rustc_data_structures::unord::{UnordMap, UnordSet};
8use rustc_errors::codes::*;
9use rustc_errors::{
10    Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, MultiSpan, SuggestionStyle,
11    report_ambiguity_error, struct_span_code_err,
12};
13use rustc_feature::BUILTIN_ATTRIBUTES;
14use rustc_hir::attrs::{AttributeKind, CfgEntry, StrippedCfgItem};
15use rustc_hir::def::Namespace::{self, *};
16use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS};
17use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
18use rustc_hir::{PrimTy, Stability, StabilityLevel, find_attr};
19use rustc_middle::bug;
20use rustc_middle::ty::TyCtxt;
21use rustc_session::Session;
22use rustc_session::lint::builtin::{
23    ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS,
24    MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
25};
26use rustc_session::lint::{AmbiguityErrorDiag, BuiltinLintDiag};
27use rustc_session::utils::was_invoked_from_cargo;
28use rustc_span::edit_distance::find_best_match_for_name;
29use rustc_span::edition::Edition;
30use rustc_span::hygiene::MacroKind;
31use rustc_span::source_map::SourceMap;
32use rustc_span::{BytePos, Ident, Macros20NormalizedIdent, Span, Symbol, SyntaxContext, kw, sym};
33use thin_vec::{ThinVec, thin_vec};
34use tracing::{debug, instrument};
35
36use crate::errors::{
37    self, AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion, ConsiderAddingADerive,
38    ExplicitUnsafeTraits, MacroDefinedLater, MacroRulesNot, MacroSuggMovePosition,
39    MaybeMissingMacroRulesName,
40};
41use crate::imports::{Import, ImportKind};
42use crate::late::{PatternSource, Rib};
43use crate::{
44    AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, BindingKey, Finalize,
45    ForwardGenericParamBanReason, HasGenericParams, LexicalScopeBinding, MacroRulesScope, Module,
46    ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult,
47    PrivacyError, ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used,
48    VisResolutionError, errors as errs, path_names_to_string,
49};
50
51type Res = def::Res<ast::NodeId>;
52
53/// A vector of spans and replacements, a message and applicability.
54pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
55
56/// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
57/// similarly named label and whether or not it is reachable.
58pub(crate) type LabelSuggestion = (Ident, bool);
59
60#[derive(Debug)]
61pub(crate) enum SuggestionTarget {
62    /// The target has a similar name as the name used by the programmer (probably a typo)
63    SimilarlyNamed,
64    /// The target is the only valid item that can be used in the corresponding context
65    SingleItem,
66}
67
68#[derive(Debug)]
69pub(crate) struct TypoSuggestion {
70    pub candidate: Symbol,
71    /// The source location where the name is defined; None if the name is not defined
72    /// in source e.g. primitives
73    pub span: Option<Span>,
74    pub res: Res,
75    pub target: SuggestionTarget,
76}
77
78impl TypoSuggestion {
79    pub(crate) fn typo_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
80        Self {
81            candidate: ident.name,
82            span: Some(ident.span),
83            res,
84            target: SuggestionTarget::SimilarlyNamed,
85        }
86    }
87    pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
88        Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
89    }
90    pub(crate) fn single_item_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
91        Self {
92            candidate: ident.name,
93            span: Some(ident.span),
94            res,
95            target: SuggestionTarget::SingleItem,
96        }
97    }
98}
99
100/// A free importable items suggested in case of resolution failure.
101#[derive(Debug, Clone)]
102pub(crate) struct ImportSuggestion {
103    pub did: Option<DefId>,
104    pub descr: &'static str,
105    pub path: Path,
106    pub accessible: bool,
107    // false if the path traverses a foreign `#[doc(hidden)]` item.
108    pub doc_visible: bool,
109    pub via_import: bool,
110    /// An extra note that should be issued if this item is suggested
111    pub note: Option<String>,
112    pub is_stable: bool,
113}
114
115/// Adjust the impl span so that just the `impl` keyword is taken by removing
116/// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
117/// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
118///
119/// *Attention*: the method used is very fragile since it essentially duplicates the work of the
120/// parser. If you need to use this function or something similar, please consider updating the
121/// `source_map` functions and this function to something more robust.
122fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
123    let impl_span = sm.span_until_char(impl_span, '<');
124    sm.span_until_whitespace(impl_span)
125}
126
127impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
128    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
129        self.tcx.dcx()
130    }
131
132    pub(crate) fn report_errors(&mut self, krate: &Crate) {
133        self.report_with_use_injections(krate);
134
135        for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
136            self.lint_buffer.buffer_lint(
137                MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
138                CRATE_NODE_ID,
139                span_use,
140                BuiltinLintDiag::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
141            );
142        }
143
144        for ambiguity_error in &self.ambiguity_errors {
145            let diag = self.ambiguity_diagnostics(ambiguity_error);
146            if ambiguity_error.warning {
147                let NameBindingKind::Import { import, .. } = ambiguity_error.b1.0.kind else {
148                    unreachable!()
149                };
150                self.lint_buffer.buffer_lint(
151                    AMBIGUOUS_GLOB_IMPORTS,
152                    import.root_id,
153                    ambiguity_error.ident.span,
154                    BuiltinLintDiag::AmbiguousGlobImports { diag },
155                );
156            } else {
157                let mut err = struct_span_code_err!(self.dcx(), diag.span, E0659, "{}", diag.msg);
158                report_ambiguity_error(&mut err, diag);
159                err.emit();
160            }
161        }
162
163        let mut reported_spans = FxHashSet::default();
164        for error in std::mem::take(&mut self.privacy_errors) {
165            if reported_spans.insert(error.dedup_span) {
166                self.report_privacy_error(&error);
167            }
168        }
169    }
170
171    fn report_with_use_injections(&mut self, krate: &Crate) {
172        for UseError { mut err, candidates, def_id, instead, suggestion, path, is_call } in
173            std::mem::take(&mut self.use_injections)
174        {
175            let (span, found_use) = if let Some(def_id) = def_id.as_local() {
176                UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id))
177            } else {
178                (None, FoundUse::No)
179            };
180
181            if !candidates.is_empty() {
182                show_candidates(
183                    self.tcx,
184                    &mut err,
185                    span,
186                    &candidates,
187                    if instead { Instead::Yes } else { Instead::No },
188                    found_use,
189                    DiagMode::Normal,
190                    path,
191                    "",
192                );
193                err.emit();
194            } else if let Some((span, msg, sugg, appl)) = suggestion {
195                err.span_suggestion_verbose(span, msg, sugg, appl);
196                err.emit();
197            } else if let [segment] = path.as_slice()
198                && is_call
199            {
200                err.stash(segment.ident.span, rustc_errors::StashKey::CallIntoMethod);
201            } else {
202                err.emit();
203            }
204        }
205    }
206
207    pub(crate) fn report_conflict(
208        &mut self,
209        parent: Module<'_>,
210        ident: Ident,
211        ns: Namespace,
212        new_binding: NameBinding<'ra>,
213        old_binding: NameBinding<'ra>,
214    ) {
215        // Error on the second of two conflicting names
216        if old_binding.span.lo() > new_binding.span.lo() {
217            return self.report_conflict(parent, ident, ns, old_binding, new_binding);
218        }
219
220        let container = match parent.kind {
221            // Avoid using TyCtxt::def_kind_descr in the resolver, because it
222            // indirectly *calls* the resolver, and would cause a query cycle.
223            ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
224            ModuleKind::Block => "block",
225        };
226
227        let (name, span) =
228            (ident.name, self.tcx.sess.source_map().guess_head_span(new_binding.span));
229
230        if self.name_already_seen.get(&name) == Some(&span) {
231            return;
232        }
233
234        let old_kind = match (ns, old_binding.res()) {
235            (ValueNS, _) => "value",
236            (MacroNS, _) => "macro",
237            (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
238            (TypeNS, Res::Def(DefKind::Mod, _)) => "module",
239            (TypeNS, Res::Def(DefKind::Trait, _)) => "trait",
240            (TypeNS, _) => "type",
241        };
242
243        let code = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
244            (true, true) => E0259,
245            (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
246                true => E0254,
247                false => E0260,
248            },
249            _ => match (old_binding.is_import_user_facing(), new_binding.is_import_user_facing()) {
250                (false, false) => E0428,
251                (true, true) => E0252,
252                _ => E0255,
253            },
254        };
255
256        let label = match new_binding.is_import_user_facing() {
257            true => errors::NameDefinedMultipleTimeLabel::Reimported { span },
258            false => errors::NameDefinedMultipleTimeLabel::Redefined { span },
259        };
260
261        let old_binding_label =
262            (!old_binding.span.is_dummy() && old_binding.span != span).then(|| {
263                let span = self.tcx.sess.source_map().guess_head_span(old_binding.span);
264                match old_binding.is_import_user_facing() {
265                    true => {
266                        errors::NameDefinedMultipleTimeOldBindingLabel::Import { span, old_kind }
267                    }
268                    false => errors::NameDefinedMultipleTimeOldBindingLabel::Definition {
269                        span,
270                        old_kind,
271                    },
272                }
273            });
274
275        let mut err = self
276            .dcx()
277            .create_err(errors::NameDefinedMultipleTime {
278                span,
279                name,
280                descr: ns.descr(),
281                container,
282                label,
283                old_binding_label,
284            })
285            .with_code(code);
286
287        // See https://github.com/rust-lang/rust/issues/32354
288        use NameBindingKind::Import;
289        let can_suggest = |binding: NameBinding<'_>, import: self::Import<'_>| {
290            !binding.span.is_dummy()
291                && !matches!(import.kind, ImportKind::MacroUse { .. } | ImportKind::MacroExport)
292        };
293        let import = match (&new_binding.kind, &old_binding.kind) {
294            // If there are two imports where one or both have attributes then prefer removing the
295            // import without attributes.
296            (Import { import: new, .. }, Import { import: old, .. })
297                if {
298                    (new.has_attributes || old.has_attributes)
299                        && can_suggest(old_binding, *old)
300                        && can_suggest(new_binding, *new)
301                } =>
302            {
303                if old.has_attributes {
304                    Some((*new, new_binding.span, true))
305                } else {
306                    Some((*old, old_binding.span, true))
307                }
308            }
309            // Otherwise prioritize the new binding.
310            (Import { import, .. }, other) if can_suggest(new_binding, *import) => {
311                Some((*import, new_binding.span, other.is_import()))
312            }
313            (other, Import { import, .. }) if can_suggest(old_binding, *import) => {
314                Some((*import, old_binding.span, other.is_import()))
315            }
316            _ => None,
317        };
318
319        // Check if the target of the use for both bindings is the same.
320        let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
321        let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
322        let from_item = self
323            .extern_prelude
324            .get(&Macros20NormalizedIdent::new(ident))
325            .is_none_or(|entry| entry.introduced_by_item);
326        // Only suggest removing an import if both bindings are to the same def, if both spans
327        // aren't dummy spans. Further, if both bindings are imports, then the ident must have
328        // been introduced by an item.
329        let should_remove_import = duplicate
330            && !has_dummy_span
331            && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
332
333        match import {
334            Some((import, span, true)) if should_remove_import && import.is_nested() => {
335                self.add_suggestion_for_duplicate_nested_use(&mut err, import, span);
336            }
337            Some((import, _, true)) if should_remove_import && !import.is_glob() => {
338                // Simple case - remove the entire import. Due to the above match arm, this can
339                // only be a single use so just remove it entirely.
340                err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport {
341                    span: import.use_span_with_attributes,
342                });
343            }
344            Some((import, span, _)) => {
345                self.add_suggestion_for_rename_of_use(&mut err, name, import, span);
346            }
347            _ => {}
348        }
349
350        err.emit();
351        self.name_already_seen.insert(name, span);
352    }
353
354    /// This function adds a suggestion to change the binding name of a new import that conflicts
355    /// with an existing import.
356    ///
357    /// ```text,ignore (diagnostic)
358    /// help: you can use `as` to change the binding name of the import
359    ///    |
360    /// LL | use foo::bar as other_bar;
361    ///    |     ^^^^^^^^^^^^^^^^^^^^^
362    /// ```
363    fn add_suggestion_for_rename_of_use(
364        &self,
365        err: &mut Diag<'_>,
366        name: Symbol,
367        import: Import<'_>,
368        binding_span: Span,
369    ) {
370        let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
371            format!("Other{name}")
372        } else {
373            format!("other_{name}")
374        };
375
376        let mut suggestion = None;
377        let mut span = binding_span;
378        match import.kind {
379            ImportKind::Single { type_ns_only: true, .. } => {
380                suggestion = Some(format!("self as {suggested_name}"))
381            }
382            ImportKind::Single { source, .. } => {
383                if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
384                    && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(binding_span)
385                    && pos as usize <= snippet.len()
386                {
387                    span = binding_span.with_lo(binding_span.lo() + BytePos(pos)).with_hi(
388                        binding_span.hi() - BytePos(if snippet.ends_with(';') { 1 } else { 0 }),
389                    );
390                    suggestion = Some(format!(" as {suggested_name}"));
391                }
392            }
393            ImportKind::ExternCrate { source, target, .. } => {
394                suggestion = Some(format!(
395                    "extern crate {} as {};",
396                    source.unwrap_or(target.name),
397                    suggested_name,
398                ))
399            }
400            _ => unreachable!(),
401        }
402
403        if let Some(suggestion) = suggestion {
404            err.subdiagnostic(ChangeImportBindingSuggestion { span, suggestion });
405        } else {
406            err.subdiagnostic(ChangeImportBinding { span });
407        }
408    }
409
410    /// This function adds a suggestion to remove an unnecessary binding from an import that is
411    /// nested. In the following example, this function will be invoked to remove the `a` binding
412    /// in the second use statement:
413    ///
414    /// ```ignore (diagnostic)
415    /// use issue_52891::a;
416    /// use issue_52891::{d, a, e};
417    /// ```
418    ///
419    /// The following suggestion will be added:
420    ///
421    /// ```ignore (diagnostic)
422    /// use issue_52891::{d, a, e};
423    ///                      ^-- help: remove unnecessary import
424    /// ```
425    ///
426    /// If the nested use contains only one import then the suggestion will remove the entire
427    /// line.
428    ///
429    /// It is expected that the provided import is nested - this isn't checked by the
430    /// function. If this invariant is not upheld, this function's behaviour will be unexpected
431    /// as characters expected by span manipulations won't be present.
432    fn add_suggestion_for_duplicate_nested_use(
433        &self,
434        err: &mut Diag<'_>,
435        import: Import<'_>,
436        binding_span: Span,
437    ) {
438        assert!(import.is_nested());
439
440        // Two examples will be used to illustrate the span manipulations we're doing:
441        //
442        // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
443        //   `a` and `import.use_span` is `issue_52891::{d, a, e};`.
444        // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
445        //   `a` and `import.use_span` is `issue_52891::{d, e, a};`.
446
447        let (found_closing_brace, span) =
448            find_span_of_binding_until_next_binding(self.tcx.sess, binding_span, import.use_span);
449
450        // If there was a closing brace then identify the span to remove any trailing commas from
451        // previous imports.
452        if found_closing_brace {
453            if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) {
454                err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport { span });
455            } else {
456                // Remove the entire line if we cannot extend the span back, this indicates an
457                // `issue_52891::{self}` case.
458                err.subdiagnostic(errors::RemoveUnnecessaryImport {
459                    span: import.use_span_with_attributes,
460                });
461            }
462
463            return;
464        }
465
466        err.subdiagnostic(errors::RemoveUnnecessaryImport { span });
467    }
468
469    pub(crate) fn lint_if_path_starts_with_module(
470        &mut self,
471        finalize: Finalize,
472        path: &[Segment],
473        second_binding: Option<NameBinding<'_>>,
474    ) {
475        let Finalize { node_id, root_span, .. } = finalize;
476
477        let first_name = match path.get(0) {
478            // In the 2018 edition this lint is a hard error, so nothing to do
479            Some(seg) if seg.ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015() => {
480                seg.ident.name
481            }
482            _ => return,
483        };
484
485        // We're only interested in `use` paths which should start with
486        // `{{root}}` currently.
487        if first_name != kw::PathRoot {
488            return;
489        }
490
491        match path.get(1) {
492            // If this import looks like `crate::...` it's already good
493            Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
494            // Otherwise go below to see if it's an extern crate
495            Some(_) => {}
496            // If the path has length one (and it's `PathRoot` most likely)
497            // then we don't know whether we're gonna be importing a crate or an
498            // item in our crate. Defer this lint to elsewhere
499            None => return,
500        }
501
502        // If the first element of our path was actually resolved to an
503        // `ExternCrate` (also used for `crate::...`) then no need to issue a
504        // warning, this looks all good!
505        if let Some(binding) = second_binding
506            && let NameBindingKind::Import { import, .. } = binding.kind
507            // Careful: we still want to rewrite paths from renamed extern crates.
508            && let ImportKind::ExternCrate { source: None, .. } = import.kind
509        {
510            return;
511        }
512
513        let diag = BuiltinLintDiag::AbsPathWithModule(root_span);
514        self.lint_buffer.buffer_lint(
515            ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
516            node_id,
517            root_span,
518            diag,
519        );
520    }
521
522    pub(crate) fn add_module_candidates(
523        &self,
524        module: Module<'ra>,
525        names: &mut Vec<TypoSuggestion>,
526        filter_fn: &impl Fn(Res) -> bool,
527        ctxt: Option<SyntaxContext>,
528    ) {
529        module.for_each_child(self, |_this, ident, _ns, binding| {
530            let res = binding.res();
531            if filter_fn(res) && ctxt.is_none_or(|ctxt| ctxt == ident.span.ctxt()) {
532                names.push(TypoSuggestion::typo_from_ident(ident.0, res));
533            }
534        });
535    }
536
537    /// Combines an error with provided span and emits it.
538    ///
539    /// This takes the error provided, combines it with the span and any additional spans inside the
540    /// error and emits it.
541    pub(crate) fn report_error(
542        &mut self,
543        span: Span,
544        resolution_error: ResolutionError<'ra>,
545    ) -> ErrorGuaranteed {
546        self.into_struct_error(span, resolution_error).emit()
547    }
548
549    pub(crate) fn into_struct_error(
550        &mut self,
551        span: Span,
552        resolution_error: ResolutionError<'ra>,
553    ) -> Diag<'_> {
554        match resolution_error {
555            ResolutionError::GenericParamsFromOuterItem(
556                outer_res,
557                has_generic_params,
558                def_kind,
559            ) => {
560                use errs::GenericParamsFromOuterItemLabel as Label;
561                let static_or_const = match def_kind {
562                    DefKind::Static { .. } => {
563                        Some(errs::GenericParamsFromOuterItemStaticOrConst::Static)
564                    }
565                    DefKind::Const => Some(errs::GenericParamsFromOuterItemStaticOrConst::Const),
566                    _ => None,
567                };
568                let is_self =
569                    matches!(outer_res, Res::SelfTyParam { .. } | Res::SelfTyAlias { .. });
570                let mut err = errs::GenericParamsFromOuterItem {
571                    span,
572                    label: None,
573                    refer_to_type_directly: None,
574                    sugg: None,
575                    static_or_const,
576                    is_self,
577                };
578
579                let sm = self.tcx.sess.source_map();
580                let def_id = match outer_res {
581                    Res::SelfTyParam { .. } => {
582                        err.label = Some(Label::SelfTyParam(span));
583                        return self.dcx().create_err(err);
584                    }
585                    Res::SelfTyAlias { alias_to: def_id, .. } => {
586                        err.label = Some(Label::SelfTyAlias(reduce_impl_span_to_impl_keyword(
587                            sm,
588                            self.def_span(def_id),
589                        )));
590                        err.refer_to_type_directly = Some(span);
591                        return self.dcx().create_err(err);
592                    }
593                    Res::Def(DefKind::TyParam, def_id) => {
594                        err.label = Some(Label::TyParam(self.def_span(def_id)));
595                        def_id
596                    }
597                    Res::Def(DefKind::ConstParam, def_id) => {
598                        err.label = Some(Label::ConstParam(self.def_span(def_id)));
599                        def_id
600                    }
601                    _ => {
602                        bug!(
603                            "GenericParamsFromOuterItem should only be used with \
604                            Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
605                            DefKind::ConstParam"
606                        );
607                    }
608                };
609
610                if let HasGenericParams::Yes(span) = has_generic_params {
611                    let name = self.tcx.item_name(def_id);
612                    let (span, snippet) = if span.is_empty() {
613                        let snippet = format!("<{name}>");
614                        (span, snippet)
615                    } else {
616                        let span = sm.span_through_char(span, '<').shrink_to_hi();
617                        let snippet = format!("{name}, ");
618                        (span, snippet)
619                    };
620                    err.sugg = Some(errs::GenericParamsFromOuterItemSugg { span, snippet });
621                }
622
623                self.dcx().create_err(err)
624            }
625            ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
626                .dcx()
627                .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
628            ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
629                self.dcx().create_err(errs::MethodNotMemberOfTrait {
630                    span,
631                    method,
632                    trait_,
633                    sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
634                        span: method.span,
635                        candidate: c,
636                    }),
637                })
638            }
639            ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
640                self.dcx().create_err(errs::TypeNotMemberOfTrait {
641                    span,
642                    type_,
643                    trait_,
644                    sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
645                        span: type_.span,
646                        candidate: c,
647                    }),
648                })
649            }
650            ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
651                self.dcx().create_err(errs::ConstNotMemberOfTrait {
652                    span,
653                    const_,
654                    trait_,
655                    sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
656                        span: const_.span,
657                        candidate: c,
658                    }),
659                })
660            }
661            ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
662                let BindingError { name, target, origin, could_be_path } = binding_error;
663
664                let target_sp = target.iter().copied().collect::<Vec<_>>();
665                let origin_sp = origin.iter().copied().collect::<Vec<_>>();
666
667                let msp = MultiSpan::from_spans(target_sp.clone());
668                let mut err = self
669                    .dcx()
670                    .create_err(errors::VariableIsNotBoundInAllPatterns { multispan: msp, name });
671                for sp in target_sp {
672                    err.subdiagnostic(errors::PatternDoesntBindName { span: sp, name });
673                }
674                for sp in origin_sp {
675                    err.subdiagnostic(errors::VariableNotInAllPatterns { span: sp });
676                }
677                if could_be_path {
678                    let import_suggestions = self.lookup_import_candidates(
679                        name,
680                        Namespace::ValueNS,
681                        &parent_scope,
682                        &|res: Res| {
683                            matches!(
684                                res,
685                                Res::Def(
686                                    DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
687                                        | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
688                                        | DefKind::Const
689                                        | DefKind::AssocConst,
690                                    _,
691                                )
692                            )
693                        },
694                    );
695
696                    if import_suggestions.is_empty() {
697                        let help_msg = format!(
698                            "if you meant to match on a variant or a `const` item, consider \
699                             making the path in the pattern qualified: `path::to::ModOrType::{name}`",
700                        );
701                        err.span_help(span, help_msg);
702                    }
703                    show_candidates(
704                        self.tcx,
705                        &mut err,
706                        Some(span),
707                        &import_suggestions,
708                        Instead::No,
709                        FoundUse::Yes,
710                        DiagMode::Pattern,
711                        vec![],
712                        "",
713                    );
714                }
715                err
716            }
717            ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
718                self.dcx().create_err(errs::VariableBoundWithDifferentMode {
719                    span,
720                    first_binding_span,
721                    variable_name,
722                })
723            }
724            ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
725                .dcx()
726                .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
727            ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
728                .dcx()
729                .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
730            ResolutionError::UndeclaredLabel { name, suggestion } => {
731                let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
732                {
733                    // A reachable label with a similar name exists.
734                    Some((ident, true)) => (
735                        (
736                            Some(errs::LabelWithSimilarNameReachable(ident.span)),
737                            Some(errs::TryUsingSimilarlyNamedLabel {
738                                span,
739                                ident_name: ident.name,
740                            }),
741                        ),
742                        None,
743                    ),
744                    // An unreachable label with a similar name exists.
745                    Some((ident, false)) => (
746                        (None, None),
747                        Some(errs::UnreachableLabelWithSimilarNameExists {
748                            ident_span: ident.span,
749                        }),
750                    ),
751                    // No similarly-named labels exist.
752                    None => ((None, None), None),
753                };
754                self.dcx().create_err(errs::UndeclaredLabel {
755                    span,
756                    name,
757                    sub_reachable,
758                    sub_reachable_suggestion,
759                    sub_unreachable,
760                })
761            }
762            ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
763                // None of the suggestions below would help with a case like `use self`.
764                let (suggestion, mpart_suggestion) = if root {
765                    (None, None)
766                } else {
767                    // use foo::bar::self        -> foo::bar
768                    // use foo::bar::self as abc -> foo::bar as abc
769                    let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
770
771                    // use foo::bar::self        -> foo::bar::{self}
772                    // use foo::bar::self as abc -> foo::bar::{self as abc}
773                    let mpart_suggestion = errs::SelfImportsOnlyAllowedWithinMultipartSuggestion {
774                        multipart_start: span_with_rename.shrink_to_lo(),
775                        multipart_end: span_with_rename.shrink_to_hi(),
776                    };
777                    (Some(suggestion), Some(mpart_suggestion))
778                };
779                self.dcx().create_err(errs::SelfImportsOnlyAllowedWithin {
780                    span,
781                    suggestion,
782                    mpart_suggestion,
783                })
784            }
785            ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
786                self.dcx().create_err(errs::SelfImportCanOnlyAppearOnceInTheList { span })
787            }
788            ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
789                self.dcx().create_err(errs::SelfImportOnlyInImportListWithNonEmptyPrefix { span })
790            }
791            ResolutionError::FailedToResolve { segment, label, suggestion, module } => {
792                let mut err =
793                    struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {label}");
794                err.span_label(span, label);
795
796                if let Some((suggestions, msg, applicability)) = suggestion {
797                    if suggestions.is_empty() {
798                        err.help(msg);
799                        return err;
800                    }
801                    err.multipart_suggestion(msg, suggestions, applicability);
802                }
803
804                if let Some(segment) = segment {
805                    let module = match module {
806                        Some(ModuleOrUniformRoot::Module(m)) if let Some(id) = m.opt_def_id() => id,
807                        _ => CRATE_DEF_ID.to_def_id(),
808                    };
809                    self.find_cfg_stripped(&mut err, &segment, module);
810                }
811
812                err
813            }
814            ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
815                self.dcx().create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
816            }
817            ResolutionError::AttemptToUseNonConstantValueInConstant {
818                ident,
819                suggestion,
820                current,
821                type_span,
822            } => {
823                // let foo =...
824                //     ^^^ given this Span
825                // ------- get this Span to have an applicable suggestion
826
827                // edit:
828                // only do this if the const and usage of the non-constant value are on the same line
829                // the further the two are apart, the higher the chance of the suggestion being wrong
830
831                let sp = self
832                    .tcx
833                    .sess
834                    .source_map()
835                    .span_extend_to_prev_str(ident.span, current, true, false);
836
837                let ((with, with_label), without) = match sp {
838                    Some(sp) if !self.tcx.sess.source_map().is_multiline(sp) => {
839                        let sp = sp
840                            .with_lo(BytePos(sp.lo().0 - (current.len() as u32)))
841                            .until(ident.span);
842                        (
843                        (Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
844                                span: sp,
845                                suggestion,
846                                current,
847                                type_span,
848                            }), Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion {span})),
849                            None,
850                        )
851                    }
852                    _ => (
853                        (None, None),
854                        Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
855                            ident_span: ident.span,
856                            suggestion,
857                        }),
858                    ),
859                };
860
861                self.dcx().create_err(errs::AttemptToUseNonConstantValueInConstant {
862                    span,
863                    with,
864                    with_label,
865                    without,
866                })
867            }
868            ResolutionError::BindingShadowsSomethingUnacceptable {
869                shadowing_binding,
870                name,
871                participle,
872                article,
873                shadowed_binding,
874                shadowed_binding_span,
875            } => self.dcx().create_err(errs::BindingShadowsSomethingUnacceptable {
876                span,
877                shadowing_binding,
878                shadowed_binding,
879                article,
880                sub_suggestion: match (shadowing_binding, shadowed_binding) {
881                    (
882                        PatternSource::Match,
883                        Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
884                    ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
885                    _ => None,
886                },
887                shadowed_binding_span,
888                participle,
889                name,
890            }),
891            ResolutionError::ForwardDeclaredGenericParam(param, reason) => match reason {
892                ForwardGenericParamBanReason::Default => {
893                    self.dcx().create_err(errs::ForwardDeclaredGenericParam { param, span })
894                }
895                ForwardGenericParamBanReason::ConstParamTy => self
896                    .dcx()
897                    .create_err(errs::ForwardDeclaredGenericInConstParamTy { param, span }),
898            },
899            ResolutionError::ParamInTyOfConstParam { name } => {
900                self.dcx().create_err(errs::ParamInTyOfConstParam { span, name })
901            }
902            ResolutionError::ParamInNonTrivialAnonConst { name, param_kind: is_type } => {
903                self.dcx().create_err(errs::ParamInNonTrivialAnonConst {
904                    span,
905                    name,
906                    param_kind: is_type,
907                    help: self
908                        .tcx
909                        .sess
910                        .is_nightly_build()
911                        .then_some(errs::ParamInNonTrivialAnonConstHelp),
912                })
913            }
914            ResolutionError::ParamInEnumDiscriminant { name, param_kind: is_type } => self
915                .dcx()
916                .create_err(errs::ParamInEnumDiscriminant { span, name, param_kind: is_type }),
917            ResolutionError::ForwardDeclaredSelf(reason) => match reason {
918                ForwardGenericParamBanReason::Default => {
919                    self.dcx().create_err(errs::SelfInGenericParamDefault { span })
920                }
921                ForwardGenericParamBanReason::ConstParamTy => {
922                    self.dcx().create_err(errs::SelfInConstGenericTy { span })
923                }
924            },
925            ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
926                let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
927                    match suggestion {
928                        // A reachable label with a similar name exists.
929                        Some((ident, true)) => (
930                            (
931                                Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
932                                Some(errs::UnreachableLabelSubSuggestion {
933                                    span,
934                                    // intentionally taking 'ident.name' instead of 'ident' itself, as this
935                                    // could be used in suggestion context
936                                    ident_name: ident.name,
937                                }),
938                            ),
939                            None,
940                        ),
941                        // An unreachable label with a similar name exists.
942                        Some((ident, false)) => (
943                            (None, None),
944                            Some(errs::UnreachableLabelSubLabelUnreachable {
945                                ident_span: ident.span,
946                            }),
947                        ),
948                        // No similarly-named labels exist.
949                        None => ((None, None), None),
950                    };
951                self.dcx().create_err(errs::UnreachableLabel {
952                    span,
953                    name,
954                    definition_span,
955                    sub_suggestion,
956                    sub_suggestion_label,
957                    sub_unreachable_label,
958                })
959            }
960            ResolutionError::TraitImplMismatch {
961                name,
962                kind,
963                code,
964                trait_item_span,
965                trait_path,
966            } => self
967                .dcx()
968                .create_err(errors::TraitImplMismatch {
969                    span,
970                    name,
971                    kind,
972                    trait_path,
973                    trait_item_span,
974                })
975                .with_code(code),
976            ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
977                .dcx()
978                .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
979            ResolutionError::InvalidAsmSym => self.dcx().create_err(errs::InvalidAsmSym { span }),
980            ResolutionError::LowercaseSelf => self.dcx().create_err(errs::LowercaseSelf { span }),
981            ResolutionError::BindingInNeverPattern => {
982                self.dcx().create_err(errs::BindingInNeverPattern { span })
983            }
984        }
985    }
986
987    pub(crate) fn report_vis_error(
988        &mut self,
989        vis_resolution_error: VisResolutionError<'_>,
990    ) -> ErrorGuaranteed {
991        match vis_resolution_error {
992            VisResolutionError::Relative2018(span, path) => {
993                self.dcx().create_err(errs::Relative2018 {
994                    span,
995                    path_span: path.span,
996                    // intentionally converting to String, as the text would also be used as
997                    // in suggestion context
998                    path_str: pprust::path_to_string(path),
999                })
1000            }
1001            VisResolutionError::AncestorOnly(span) => {
1002                self.dcx().create_err(errs::AncestorOnly(span))
1003            }
1004            VisResolutionError::FailedToResolve(span, label, suggestion) => self.into_struct_error(
1005                span,
1006                ResolutionError::FailedToResolve { segment: None, label, suggestion, module: None },
1007            ),
1008            VisResolutionError::ExpectedFound(span, path_str, res) => {
1009                self.dcx().create_err(errs::ExpectedModuleFound { span, res, path_str })
1010            }
1011            VisResolutionError::Indeterminate(span) => {
1012                self.dcx().create_err(errs::Indeterminate(span))
1013            }
1014            VisResolutionError::ModuleOnly(span) => self.dcx().create_err(errs::ModuleOnly(span)),
1015        }
1016        .emit()
1017    }
1018
1019    /// Lookup typo candidate in scope for a macro or import.
1020    fn early_lookup_typo_candidate(
1021        &mut self,
1022        scope_set: ScopeSet<'ra>,
1023        parent_scope: &ParentScope<'ra>,
1024        ident: Ident,
1025        filter_fn: &impl Fn(Res) -> bool,
1026    ) -> Option<TypoSuggestion> {
1027        let mut suggestions = Vec::new();
1028        let ctxt = ident.span.ctxt();
1029        self.cm().visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
1030            match scope {
1031                Scope::DeriveHelpers(expn_id) => {
1032                    let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1033                    if filter_fn(res) {
1034                        suggestions.extend(
1035                            this.helper_attrs
1036                                .get(&expn_id)
1037                                .into_iter()
1038                                .flatten()
1039                                .map(|(ident, _)| TypoSuggestion::typo_from_ident(*ident, res)),
1040                        );
1041                    }
1042                }
1043                Scope::DeriveHelpersCompat => {
1044                    let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1045                    if filter_fn(res) {
1046                        for derive in parent_scope.derives {
1047                            let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1048                            let Ok((Some(ext), _)) = this.reborrow().resolve_macro_path(
1049                                derive,
1050                                Some(MacroKind::Derive),
1051                                parent_scope,
1052                                false,
1053                                false,
1054                                None,
1055                                None,
1056                            ) else {
1057                                continue;
1058                            };
1059                            suggestions.extend(
1060                                ext.helper_attrs
1061                                    .iter()
1062                                    .map(|name| TypoSuggestion::typo_from_name(*name, res)),
1063                            );
1064                        }
1065                    }
1066                }
1067                Scope::MacroRules(macro_rules_scope) => {
1068                    if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1069                        let res = macro_rules_binding.binding.res();
1070                        if filter_fn(res) {
1071                            suggestions.push(TypoSuggestion::typo_from_ident(
1072                                macro_rules_binding.ident,
1073                                res,
1074                            ))
1075                        }
1076                    }
1077                }
1078                Scope::Module(module, _) => {
1079                    this.add_module_candidates(module, &mut suggestions, filter_fn, None);
1080                }
1081                Scope::MacroUsePrelude => {
1082                    suggestions.extend(this.macro_use_prelude.iter().filter_map(
1083                        |(name, binding)| {
1084                            let res = binding.res();
1085                            filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1086                        },
1087                    ));
1088                }
1089                Scope::BuiltinAttrs => {
1090                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(sym::dummy));
1091                    if filter_fn(res) {
1092                        suggestions.extend(
1093                            BUILTIN_ATTRIBUTES
1094                                .iter()
1095                                .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1096                        );
1097                    }
1098                }
1099                Scope::ExternPrelude => {
1100                    suggestions.extend(this.extern_prelude.keys().filter_map(|ident| {
1101                        let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1102                        filter_fn(res).then_some(TypoSuggestion::typo_from_ident(ident.0, res))
1103                    }));
1104                }
1105                Scope::ToolPrelude => {
1106                    let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1107                    suggestions.extend(
1108                        this.registered_tools
1109                            .iter()
1110                            .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
1111                    );
1112                }
1113                Scope::StdLibPrelude => {
1114                    if let Some(prelude) = this.prelude {
1115                        let mut tmp_suggestions = Vec::new();
1116                        this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1117                        suggestions.extend(
1118                            tmp_suggestions
1119                                .into_iter()
1120                                .filter(|s| use_prelude.into() || this.is_builtin_macro(s.res)),
1121                        );
1122                    }
1123                }
1124                Scope::BuiltinTypes => {
1125                    suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1126                        let res = Res::PrimTy(*prim_ty);
1127                        filter_fn(res)
1128                            .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1129                    }))
1130                }
1131            }
1132
1133            None::<()>
1134        });
1135
1136        // Make sure error reporting is deterministic.
1137        suggestions.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
1138
1139        match find_best_match_for_name(
1140            &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1141            ident.name,
1142            None,
1143        ) {
1144            Some(found) if found != ident.name => {
1145                suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1146            }
1147            _ => None,
1148        }
1149    }
1150
1151    fn lookup_import_candidates_from_module<FilterFn>(
1152        &self,
1153        lookup_ident: Ident,
1154        namespace: Namespace,
1155        parent_scope: &ParentScope<'ra>,
1156        start_module: Module<'ra>,
1157        crate_path: ThinVec<ast::PathSegment>,
1158        filter_fn: FilterFn,
1159    ) -> Vec<ImportSuggestion>
1160    where
1161        FilterFn: Fn(Res) -> bool,
1162    {
1163        let mut candidates = Vec::new();
1164        let mut seen_modules = FxHashSet::default();
1165        let start_did = start_module.def_id();
1166        let mut worklist = vec![(
1167            start_module,
1168            ThinVec::<ast::PathSegment>::new(),
1169            true,
1170            start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
1171            true,
1172        )];
1173        let mut worklist_via_import = vec![];
1174
1175        while let Some((in_module, path_segments, accessible, doc_visible, is_stable)) =
1176            match worklist.pop() {
1177                None => worklist_via_import.pop(),
1178                Some(x) => Some(x),
1179            }
1180        {
1181            let in_module_is_extern = !in_module.def_id().is_local();
1182            in_module.for_each_child(self, |this, ident, ns, name_binding| {
1183                // Avoid non-importable candidates.
1184                if name_binding.is_assoc_item()
1185                    && !this.tcx.features().import_trait_associated_functions()
1186                {
1187                    return;
1188                }
1189
1190                if ident.name == kw::Underscore {
1191                    return;
1192                }
1193
1194                let child_accessible =
1195                    accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1196
1197                // do not venture inside inaccessible items of other crates
1198                if in_module_is_extern && !child_accessible {
1199                    return;
1200                }
1201
1202                let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1203
1204                // There is an assumption elsewhere that paths of variants are in the enum's
1205                // declaration and not imported. With this assumption, the variant component is
1206                // chopped and the rest of the path is assumed to be the enum's own path. For
1207                // errors where a variant is used as the type instead of the enum, this causes
1208                // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1209                if via_import && name_binding.is_possibly_imported_variant() {
1210                    return;
1211                }
1212
1213                // #90113: Do not count an inaccessible reexported item as a candidate.
1214                if let NameBindingKind::Import { binding, .. } = name_binding.kind
1215                    && this.is_accessible_from(binding.vis, parent_scope.module)
1216                    && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1217                {
1218                    return;
1219                }
1220
1221                let res = name_binding.res();
1222                let did = match res {
1223                    Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1224                    _ => res.opt_def_id(),
1225                };
1226                let child_doc_visible = doc_visible
1227                    && did.is_none_or(|did| did.is_local() || !this.tcx.is_doc_hidden(did));
1228
1229                // collect results based on the filter function
1230                // avoid suggesting anything from the same module in which we are resolving
1231                // avoid suggesting anything with a hygienic name
1232                if ident.name == lookup_ident.name
1233                    && ns == namespace
1234                    && in_module != parent_scope.module
1235                    && !ident.span.normalize_to_macros_2_0().from_expansion()
1236                    && filter_fn(res)
1237                {
1238                    // create the path
1239                    let mut segms = if lookup_ident.span.at_least_rust_2018() {
1240                        // crate-local absolute paths start with `crate::` in edition 2018
1241                        // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1242                        crate_path.clone()
1243                    } else {
1244                        ThinVec::new()
1245                    };
1246                    segms.append(&mut path_segments.clone());
1247
1248                    segms.push(ast::PathSegment::from_ident(ident.0));
1249                    let path = Path { span: name_binding.span, segments: segms, tokens: None };
1250
1251                    if child_accessible
1252                        // Remove invisible match if exists
1253                        && let Some(idx) = candidates
1254                            .iter()
1255                            .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1256                    {
1257                        candidates.remove(idx);
1258                    }
1259
1260                    let is_stable = if is_stable
1261                        && let Some(did) = did
1262                        && this.is_stable(did, path.span)
1263                    {
1264                        true
1265                    } else {
1266                        false
1267                    };
1268
1269                    // Rreplace unstable suggestions if we meet a new stable one,
1270                    // and do nothing if any other situation. For example, if we
1271                    // meet `std::ops::Range` after `std::range::legacy::Range`,
1272                    // we will remove the latter and then insert the former.
1273                    if is_stable
1274                        && let Some(idx) = candidates
1275                            .iter()
1276                            .position(|v: &ImportSuggestion| v.did == did && !v.is_stable)
1277                    {
1278                        candidates.remove(idx);
1279                    }
1280
1281                    if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1282                        // See if we're recommending TryFrom, TryInto, or FromIterator and add
1283                        // a note about editions
1284                        let note = if let Some(did) = did {
1285                            let requires_note = !did.is_local()
1286                                && this.tcx.get_attrs(did, sym::rustc_diagnostic_item).any(
1287                                    |attr| {
1288                                        [sym::TryInto, sym::TryFrom, sym::FromIterator]
1289                                            .map(|x| Some(x))
1290                                            .contains(&attr.value_str())
1291                                    },
1292                                );
1293
1294                            requires_note.then(|| {
1295                                format!(
1296                                    "'{}' is included in the prelude starting in Edition 2021",
1297                                    path_names_to_string(&path)
1298                                )
1299                            })
1300                        } else {
1301                            None
1302                        };
1303
1304                        candidates.push(ImportSuggestion {
1305                            did,
1306                            descr: res.descr(),
1307                            path,
1308                            accessible: child_accessible,
1309                            doc_visible: child_doc_visible,
1310                            note,
1311                            via_import,
1312                            is_stable,
1313                        });
1314                    }
1315                }
1316
1317                // collect submodules to explore
1318                if let Some(def_id) = name_binding.res().module_like_def_id() {
1319                    // form the path
1320                    let mut path_segments = path_segments.clone();
1321                    path_segments.push(ast::PathSegment::from_ident(ident.0));
1322
1323                    let alias_import = if let NameBindingKind::Import { import, .. } =
1324                        name_binding.kind
1325                        && let ImportKind::ExternCrate { source: Some(_), .. } = import.kind
1326                        && import.parent_scope.expansion == parent_scope.expansion
1327                    {
1328                        true
1329                    } else {
1330                        false
1331                    };
1332
1333                    let is_extern_crate_that_also_appears_in_prelude =
1334                        name_binding.is_extern_crate() && lookup_ident.span.at_least_rust_2018();
1335
1336                    if !is_extern_crate_that_also_appears_in_prelude || alias_import {
1337                        // add the module to the lookup
1338                        if seen_modules.insert(def_id) {
1339                            if via_import { &mut worklist_via_import } else { &mut worklist }.push(
1340                                (
1341                                    this.expect_module(def_id),
1342                                    path_segments,
1343                                    child_accessible,
1344                                    child_doc_visible,
1345                                    is_stable && this.is_stable(def_id, name_binding.span),
1346                                ),
1347                            );
1348                        }
1349                    }
1350                }
1351            })
1352        }
1353
1354        candidates
1355    }
1356
1357    fn is_stable(&self, did: DefId, span: Span) -> bool {
1358        if did.is_local() {
1359            return true;
1360        }
1361
1362        match self.tcx.lookup_stability(did) {
1363            Some(Stability {
1364                level: StabilityLevel::Unstable { implied_by, .. }, feature, ..
1365            }) => {
1366                if span.allows_unstable(feature) {
1367                    true
1368                } else if self.tcx.features().enabled(feature) {
1369                    true
1370                } else if let Some(implied_by) = implied_by
1371                    && self.tcx.features().enabled(implied_by)
1372                {
1373                    true
1374                } else {
1375                    false
1376                }
1377            }
1378            Some(_) => true,
1379            None => false,
1380        }
1381    }
1382
1383    /// When name resolution fails, this method can be used to look up candidate
1384    /// entities with the expected name. It allows filtering them using the
1385    /// supplied predicate (which should be used to only accept the types of
1386    /// definitions expected, e.g., traits). The lookup spans across all crates.
1387    ///
1388    /// N.B., the method does not look into imports, but this is not a problem,
1389    /// since we report the definitions (thus, the de-aliased imports).
1390    pub(crate) fn lookup_import_candidates<FilterFn>(
1391        &mut self,
1392        lookup_ident: Ident,
1393        namespace: Namespace,
1394        parent_scope: &ParentScope<'ra>,
1395        filter_fn: FilterFn,
1396    ) -> Vec<ImportSuggestion>
1397    where
1398        FilterFn: Fn(Res) -> bool,
1399    {
1400        let crate_path = thin_vec![ast::PathSegment::from_ident(Ident::with_dummy_span(kw::Crate))];
1401        let mut suggestions = self.lookup_import_candidates_from_module(
1402            lookup_ident,
1403            namespace,
1404            parent_scope,
1405            self.graph_root,
1406            crate_path,
1407            &filter_fn,
1408        );
1409
1410        if lookup_ident.span.at_least_rust_2018() {
1411            for &ident in self.extern_prelude.keys() {
1412                if ident.span.from_expansion() {
1413                    // Idents are adjusted to the root context before being
1414                    // resolved in the extern prelude, so reporting this to the
1415                    // user is no help. This skips the injected
1416                    // `extern crate std` in the 2018 edition, which would
1417                    // otherwise cause duplicate suggestions.
1418                    continue;
1419                }
1420                let Some(crate_id) =
1421                    self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
1422                else {
1423                    continue;
1424                };
1425
1426                let crate_def_id = crate_id.as_def_id();
1427                let crate_root = self.expect_module(crate_def_id);
1428
1429                // Check if there's already an item in scope with the same name as the crate.
1430                // If so, we have to disambiguate the potential import suggestions by making
1431                // the paths *global* (i.e., by prefixing them with `::`).
1432                let needs_disambiguation =
1433                    self.resolutions(parent_scope.module).borrow().iter().any(
1434                        |(key, name_resolution)| {
1435                            if key.ns == TypeNS
1436                                && key.ident == ident
1437                                && let Some(binding) = name_resolution.borrow().best_binding()
1438                            {
1439                                match binding.res() {
1440                                    // No disambiguation needed if the identically named item we
1441                                    // found in scope actually refers to the crate in question.
1442                                    Res::Def(_, def_id) => def_id != crate_def_id,
1443                                    Res::PrimTy(_) => true,
1444                                    _ => false,
1445                                }
1446                            } else {
1447                                false
1448                            }
1449                        },
1450                    );
1451                let mut crate_path = ThinVec::new();
1452                if needs_disambiguation {
1453                    crate_path.push(ast::PathSegment::path_root(rustc_span::DUMMY_SP));
1454                }
1455                crate_path.push(ast::PathSegment::from_ident(ident.0));
1456
1457                suggestions.extend(self.lookup_import_candidates_from_module(
1458                    lookup_ident,
1459                    namespace,
1460                    parent_scope,
1461                    crate_root,
1462                    crate_path,
1463                    &filter_fn,
1464                ));
1465            }
1466        }
1467
1468        suggestions
1469    }
1470
1471    pub(crate) fn unresolved_macro_suggestions(
1472        &mut self,
1473        err: &mut Diag<'_>,
1474        macro_kind: MacroKind,
1475        parent_scope: &ParentScope<'ra>,
1476        ident: Ident,
1477        krate: &Crate,
1478        sugg_span: Option<Span>,
1479    ) {
1480        // Bring imported but unused `derive` macros into `macro_map` so we ensure they can be used
1481        // for suggestions.
1482        self.cm().visit_scopes(
1483            ScopeSet::Macro(MacroKind::Derive),
1484            &parent_scope,
1485            ident.span.ctxt(),
1486            |this, scope, _use_prelude, _ctxt| {
1487                let Scope::Module(m, _) = scope else {
1488                    return None;
1489                };
1490                for (_, resolution) in this.resolutions(m).borrow().iter() {
1491                    let Some(binding) = resolution.borrow().best_binding() else {
1492                        continue;
1493                    };
1494                    let Res::Def(DefKind::Macro(MacroKind::Derive | MacroKind::Attr), def_id) =
1495                        binding.res()
1496                    else {
1497                        continue;
1498                    };
1499                    // By doing this all *imported* macros get added to the `macro_map` even if they
1500                    // are *unused*, which makes the later suggestions find them and work.
1501                    let _ = this.get_macro_by_def_id(def_id);
1502                }
1503                None::<()>
1504            },
1505        );
1506
1507        let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1508        let suggestion = self.early_lookup_typo_candidate(
1509            ScopeSet::Macro(macro_kind),
1510            parent_scope,
1511            ident,
1512            is_expected,
1513        );
1514        if !self.add_typo_suggestion(err, suggestion, ident.span) {
1515            self.detect_derive_attribute(err, ident, parent_scope, sugg_span);
1516        }
1517
1518        let import_suggestions =
1519            self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1520        let (span, found_use) = match parent_scope.module.nearest_parent_mod().as_local() {
1521            Some(def_id) => UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id)),
1522            None => (None, FoundUse::No),
1523        };
1524        show_candidates(
1525            self.tcx,
1526            err,
1527            span,
1528            &import_suggestions,
1529            Instead::No,
1530            found_use,
1531            DiagMode::Normal,
1532            vec![],
1533            "",
1534        );
1535
1536        if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1537            let label_span = ident.span.shrink_to_hi();
1538            let mut spans = MultiSpan::from_span(label_span);
1539            spans.push_span_label(label_span, "put a macro name here");
1540            err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1541            return;
1542        }
1543
1544        if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1545            err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1546            return;
1547        }
1548
1549        let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1550            if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1551        });
1552
1553        if let Some((def_id, unused_ident)) = unused_macro {
1554            let scope = self.local_macro_def_scopes[&def_id];
1555            let parent_nearest = parent_scope.module.nearest_parent_mod();
1556            if Some(parent_nearest) == scope.opt_def_id() {
1557                match macro_kind {
1558                    MacroKind::Bang => {
1559                        err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1560                        err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1561                    }
1562                    MacroKind::Attr => {
1563                        err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1564                    }
1565                    MacroKind::Derive => {
1566                        err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1567                    }
1568                }
1569
1570                return;
1571            }
1572        }
1573
1574        if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1575            err.subdiagnostic(AddedMacroUse);
1576            return;
1577        }
1578
1579        if ident.name == kw::Default
1580            && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1581        {
1582            let span = self.def_span(def_id);
1583            let source_map = self.tcx.sess.source_map();
1584            let head_span = source_map.guess_head_span(span);
1585            err.subdiagnostic(ConsiderAddingADerive {
1586                span: head_span.shrink_to_lo(),
1587                suggestion: "#[derive(Default)]\n".to_string(),
1588            });
1589        }
1590        for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1591            let Ok(binding) = self.cm().early_resolve_ident_in_lexical_scope(
1592                ident,
1593                ScopeSet::All(ns),
1594                parent_scope,
1595                None,
1596                false,
1597                None,
1598                None,
1599            ) else {
1600                continue;
1601            };
1602
1603            let desc = match binding.res() {
1604                Res::Def(DefKind::Macro(MacroKind::Bang), _) => "a function-like macro".to_string(),
1605                Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1606                    format!("an attribute: `#[{ident}]`")
1607                }
1608                Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1609                    format!("a derive macro: `#[derive({ident})]`")
1610                }
1611                Res::ToolMod => {
1612                    // Don't confuse the user with tool modules.
1613                    continue;
1614                }
1615                Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1616                    "only a trait, without a derive macro".to_string()
1617                }
1618                res => format!(
1619                    "{} {}, not {} {}",
1620                    res.article(),
1621                    res.descr(),
1622                    macro_kind.article(),
1623                    macro_kind.descr_expected(),
1624                ),
1625            };
1626            if let crate::NameBindingKind::Import { import, .. } = binding.kind
1627                && !import.span.is_dummy()
1628            {
1629                let note = errors::IdentImporterHereButItIsDesc {
1630                    span: import.span,
1631                    imported_ident: ident,
1632                    imported_ident_desc: &desc,
1633                };
1634                err.subdiagnostic(note);
1635                // Silence the 'unused import' warning we might get,
1636                // since this diagnostic already covers that import.
1637                self.record_use(ident, binding, Used::Other);
1638                return;
1639            }
1640            let note = errors::IdentInScopeButItIsDesc {
1641                imported_ident: ident,
1642                imported_ident_desc: &desc,
1643            };
1644            err.subdiagnostic(note);
1645            return;
1646        }
1647    }
1648
1649    /// Given an attribute macro that failed to be resolved, look for `derive` macros that could
1650    /// provide it, either as-is or with small typos.
1651    fn detect_derive_attribute(
1652        &self,
1653        err: &mut Diag<'_>,
1654        ident: Ident,
1655        parent_scope: &ParentScope<'ra>,
1656        sugg_span: Option<Span>,
1657    ) {
1658        // Find all of the `derive`s in scope and collect their corresponding declared
1659        // attributes.
1660        // FIXME: this only works if the crate that owns the macro that has the helper_attr
1661        // has already been imported.
1662        let mut derives = vec![];
1663        let mut all_attrs: UnordMap<Symbol, Vec<_>> = UnordMap::default();
1664        // We're collecting these in a hashmap, and handle ordering the output further down.
1665        #[allow(rustc::potential_query_instability)]
1666        for (def_id, data) in self
1667            .local_macro_map
1668            .iter()
1669            .map(|(local_id, data)| (local_id.to_def_id(), data))
1670            .chain(self.extern_macro_map.borrow().iter().map(|(id, d)| (*id, d)))
1671        {
1672            for helper_attr in &data.ext.helper_attrs {
1673                let item_name = self.tcx.item_name(def_id);
1674                all_attrs.entry(*helper_attr).or_default().push(item_name);
1675                if helper_attr == &ident.name {
1676                    derives.push(item_name);
1677                }
1678            }
1679        }
1680        let kind = MacroKind::Derive.descr();
1681        if !derives.is_empty() {
1682            // We found an exact match for the missing attribute in a `derive` macro. Suggest it.
1683            let mut derives: Vec<String> = derives.into_iter().map(|d| d.to_string()).collect();
1684            derives.sort();
1685            derives.dedup();
1686            let msg = match &derives[..] {
1687                [derive] => format!(" `{derive}`"),
1688                [start @ .., last] => format!(
1689                    "s {} and `{last}`",
1690                    start.iter().map(|d| format!("`{d}`")).collect::<Vec<_>>().join(", ")
1691                ),
1692                [] => unreachable!("we checked for this to be non-empty 10 lines above!?"),
1693            };
1694            let msg = format!(
1695                "`{}` is an attribute that can be used by the {kind}{msg}, you might be \
1696                     missing a `derive` attribute",
1697                ident.name,
1698            );
1699            let sugg_span = if let ModuleKind::Def(DefKind::Enum, id, _) = parent_scope.module.kind
1700            {
1701                let span = self.def_span(id);
1702                if span.from_expansion() {
1703                    None
1704                } else {
1705                    // For enum variants sugg_span is empty but we can get the enum's Span.
1706                    Some(span.shrink_to_lo())
1707                }
1708            } else {
1709                // For items this `Span` will be populated, everything else it'll be None.
1710                sugg_span
1711            };
1712            match sugg_span {
1713                Some(span) => {
1714                    err.span_suggestion_verbose(
1715                        span,
1716                        msg,
1717                        format!("#[derive({})]\n", derives.join(", ")),
1718                        Applicability::MaybeIncorrect,
1719                    );
1720                }
1721                None => {
1722                    err.note(msg);
1723                }
1724            }
1725        } else {
1726            // We didn't find an exact match. Look for close matches. If any, suggest fixing typo.
1727            let all_attr_names = all_attrs.keys().map(|s| *s).into_sorted_stable_ord();
1728            if let Some(best_match) = find_best_match_for_name(&all_attr_names, ident.name, None)
1729                && let Some(macros) = all_attrs.get(&best_match)
1730            {
1731                let mut macros: Vec<String> = macros.into_iter().map(|d| d.to_string()).collect();
1732                macros.sort();
1733                macros.dedup();
1734                let msg = match &macros[..] {
1735                    [] => return,
1736                    [name] => format!(" `{name}` accepts"),
1737                    [start @ .., end] => format!(
1738                        "s {} and `{end}` accept",
1739                        start.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", "),
1740                    ),
1741                };
1742                let msg = format!("the {kind}{msg} the similarly named `{best_match}` attribute");
1743                err.span_suggestion_verbose(
1744                    ident.span,
1745                    msg,
1746                    best_match,
1747                    Applicability::MaybeIncorrect,
1748                );
1749            }
1750        }
1751    }
1752
1753    pub(crate) fn add_typo_suggestion(
1754        &self,
1755        err: &mut Diag<'_>,
1756        suggestion: Option<TypoSuggestion>,
1757        span: Span,
1758    ) -> bool {
1759        let suggestion = match suggestion {
1760            None => return false,
1761            // We shouldn't suggest underscore.
1762            Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1763            Some(suggestion) => suggestion,
1764        };
1765
1766        let mut did_label_def_span = false;
1767
1768        if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1769            if span.overlaps(def_span) {
1770                // Don't suggest typo suggestion for itself like in the following:
1771                // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1772                //   --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1773                //    |
1774                // LL | struct X {}
1775                //    | ----------- `X` defined here
1776                // LL |
1777                // LL | const Y: X = X("ö");
1778                //    | -------------^^^^^^- similarly named constant `Y` defined here
1779                //    |
1780                // help: use struct literal syntax instead
1781                //    |
1782                // LL | const Y: X = X {};
1783                //    |              ^^^^
1784                // help: a constant with a similar name exists
1785                //    |
1786                // LL | const Y: X = Y("ö");
1787                //    |              ^
1788                return false;
1789            }
1790            let span = self.tcx.sess.source_map().guess_head_span(def_span);
1791            let candidate_descr = suggestion.res.descr();
1792            let candidate = suggestion.candidate;
1793            let label = match suggestion.target {
1794                SuggestionTarget::SimilarlyNamed => {
1795                    errors::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
1796                }
1797                SuggestionTarget::SingleItem => {
1798                    errors::DefinedHere::SingleItem { span, candidate_descr, candidate }
1799                }
1800            };
1801            did_label_def_span = true;
1802            err.subdiagnostic(label);
1803        }
1804
1805        let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
1806            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1807            && let Some(span) = suggestion.span
1808            && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
1809            && snippet == candidate
1810        {
1811            let candidate = suggestion.candidate;
1812            // When the suggested binding change would be from `x` to `_x`, suggest changing the
1813            // original binding definition instead. (#60164)
1814            let msg = format!(
1815                "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
1816            );
1817            if !did_label_def_span {
1818                err.span_label(span, format!("`{candidate}` defined here"));
1819            }
1820            (span, msg, snippet)
1821        } else {
1822            let msg = match suggestion.target {
1823                SuggestionTarget::SimilarlyNamed => format!(
1824                    "{} {} with a similar name exists",
1825                    suggestion.res.article(),
1826                    suggestion.res.descr()
1827                ),
1828                SuggestionTarget::SingleItem => {
1829                    format!("maybe you meant this {}", suggestion.res.descr())
1830                }
1831            };
1832            (span, msg, suggestion.candidate.to_ident_string())
1833        };
1834        err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1835        true
1836    }
1837
1838    fn binding_description(&self, b: NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1839        let res = b.res();
1840        if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
1841            // These already contain the "built-in" prefix or look bad with it.
1842            let add_built_in =
1843                !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1844            let (built_in, from) = if from_prelude {
1845                ("", " from prelude")
1846            } else if b.is_extern_crate()
1847                && !b.is_import()
1848                && self.tcx.sess.opts.externs.get(ident.as_str()).is_some()
1849            {
1850                ("", " passed with `--extern`")
1851            } else if add_built_in {
1852                (" built-in", "")
1853            } else {
1854                ("", "")
1855            };
1856
1857            let a = if built_in.is_empty() { res.article() } else { "a" };
1858            format!("{a}{built_in} {thing}{from}", thing = res.descr())
1859        } else {
1860            let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1861            format!("the {thing} {introduced} here", thing = res.descr())
1862        }
1863    }
1864
1865    fn ambiguity_diagnostics(&self, ambiguity_error: &AmbiguityError<'_>) -> AmbiguityErrorDiag {
1866        let AmbiguityError { kind, ident, b1, b2, misc1, misc2, .. } = *ambiguity_error;
1867        let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1868            // We have to print the span-less alternative first, otherwise formatting looks bad.
1869            (b2, b1, misc2, misc1, true)
1870        } else {
1871            (b1, b2, misc1, misc2, false)
1872        };
1873        let could_refer_to = |b: NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1874            let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1875            let note_msg = format!("`{ident}` could{also} refer to {what}");
1876
1877            let thing = b.res().descr();
1878            let mut help_msgs = Vec::new();
1879            if b.is_glob_import()
1880                && (kind == AmbiguityKind::GlobVsGlob
1881                    || kind == AmbiguityKind::GlobVsExpanded
1882                    || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1883            {
1884                help_msgs.push(format!(
1885                    "consider adding an explicit import of `{ident}` to disambiguate"
1886                ))
1887            }
1888            if b.is_extern_crate() && ident.span.at_least_rust_2018() {
1889                help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1890            }
1891            match misc {
1892                AmbiguityErrorMisc::SuggestCrate => help_msgs
1893                    .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously")),
1894                AmbiguityErrorMisc::SuggestSelf => help_msgs
1895                    .push(format!("use `self::{ident}` to refer to this {thing} unambiguously")),
1896                AmbiguityErrorMisc::FromPrelude | AmbiguityErrorMisc::None => {}
1897            }
1898
1899            (
1900                b.span,
1901                note_msg,
1902                help_msgs
1903                    .iter()
1904                    .enumerate()
1905                    .map(|(i, help_msg)| {
1906                        let or = if i == 0 { "" } else { "or " };
1907                        format!("{or}{help_msg}")
1908                    })
1909                    .collect::<Vec<_>>(),
1910            )
1911        };
1912        let (b1_span, b1_note_msg, b1_help_msgs) = could_refer_to(b1, misc1, "");
1913        let (b2_span, b2_note_msg, b2_help_msgs) = could_refer_to(b2, misc2, " also");
1914
1915        AmbiguityErrorDiag {
1916            msg: format!("`{ident}` is ambiguous"),
1917            span: ident.span,
1918            label_span: ident.span,
1919            label_msg: "ambiguous name".to_string(),
1920            note_msg: format!("ambiguous because of {}", kind.descr()),
1921            b1_span,
1922            b1_note_msg,
1923            b1_help_msgs,
1924            b2_span,
1925            b2_note_msg,
1926            b2_help_msgs,
1927        }
1928    }
1929
1930    /// If the binding refers to a tuple struct constructor with fields,
1931    /// returns the span of its fields.
1932    fn ctor_fields_span(&self, binding: NameBinding<'_>) -> Option<Span> {
1933        let NameBindingKind::Res(Res::Def(
1934            DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
1935            ctor_def_id,
1936        )) = binding.kind
1937        else {
1938            return None;
1939        };
1940
1941        let def_id = self.tcx.parent(ctor_def_id);
1942        self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) // None for `struct Foo()`
1943    }
1944
1945    fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
1946        let PrivacyError { ident, binding, outermost_res, parent_scope, single_nested, dedup_span } =
1947            *privacy_error;
1948
1949        let res = binding.res();
1950        let ctor_fields_span = self.ctor_fields_span(binding);
1951        let plain_descr = res.descr().to_string();
1952        let nonimport_descr =
1953            if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1954        let import_descr = nonimport_descr.clone() + " import";
1955        let get_descr =
1956            |b: NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1957
1958        // Print the primary message.
1959        let ident_descr = get_descr(binding);
1960        let mut err =
1961            self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
1962
1963        let mut not_publicly_reexported = false;
1964        if let Some((this_res, outer_ident)) = outermost_res {
1965            let import_suggestions = self.lookup_import_candidates(
1966                outer_ident,
1967                this_res.ns().unwrap_or(Namespace::TypeNS),
1968                &parent_scope,
1969                &|res: Res| res == this_res,
1970            );
1971            let point_to_def = !show_candidates(
1972                self.tcx,
1973                &mut err,
1974                Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
1975                &import_suggestions,
1976                Instead::Yes,
1977                FoundUse::Yes,
1978                DiagMode::Import { append: single_nested, unresolved_import: false },
1979                vec![],
1980                "",
1981            );
1982            // If we suggest importing a public re-export, don't point at the definition.
1983            if point_to_def && ident.span != outer_ident.span {
1984                not_publicly_reexported = true;
1985                let label = errors::OuterIdentIsNotPubliclyReexported {
1986                    span: outer_ident.span,
1987                    outer_ident_descr: this_res.descr(),
1988                    outer_ident,
1989                };
1990                err.subdiagnostic(label);
1991            }
1992        }
1993
1994        let mut non_exhaustive = None;
1995        // If an ADT is foreign and marked as `non_exhaustive`, then that's
1996        // probably why we have the privacy error.
1997        // Otherwise, point out if the struct has any private fields.
1998        if let Some(def_id) = res.opt_def_id()
1999            && !def_id.is_local()
2000            && let Some(attr_span) = find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::NonExhaustive(span) => *span)
2001        {
2002            non_exhaustive = Some(attr_span);
2003        } else if let Some(span) = ctor_fields_span {
2004            let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
2005            err.subdiagnostic(label);
2006            if let Res::Def(_, d) = res
2007                && let Some(fields) = self.field_visibility_spans.get(&d)
2008            {
2009                let spans = fields.iter().map(|span| *span).collect();
2010                let sugg =
2011                    errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
2012                err.subdiagnostic(sugg);
2013            }
2014        }
2015
2016        let mut sugg_paths: Vec<(Vec<Ident>, bool)> = vec![];
2017        if let Some(mut def_id) = res.opt_def_id() {
2018            // We can't use `def_path_str` in resolve.
2019            let mut path = vec![def_id];
2020            while let Some(parent) = self.tcx.opt_parent(def_id) {
2021                def_id = parent;
2022                if !def_id.is_top_level_module() {
2023                    path.push(def_id);
2024                } else {
2025                    break;
2026                }
2027            }
2028            // We will only suggest importing directly if it is accessible through that path.
2029            let path_names: Option<Vec<Ident>> = path
2030                .iter()
2031                .rev()
2032                .map(|def_id| {
2033                    self.tcx.opt_item_name(*def_id).map(|name| {
2034                        Ident::with_dummy_span(if def_id.is_top_level_module() {
2035                            kw::Crate
2036                        } else {
2037                            name
2038                        })
2039                    })
2040                })
2041                .collect();
2042            if let Some(def_id) = path.get(0)
2043                && let Some(path) = path_names
2044            {
2045                if let Some(def_id) = def_id.as_local() {
2046                    if self.effective_visibilities.is_directly_public(def_id) {
2047                        sugg_paths.push((path, false));
2048                    }
2049                } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
2050                {
2051                    sugg_paths.push((path, false));
2052                }
2053            }
2054        }
2055
2056        // Print the whole import chain to make it easier to see what happens.
2057        let first_binding = binding;
2058        let mut next_binding = Some(binding);
2059        let mut next_ident = ident;
2060        let mut path = vec![];
2061        while let Some(binding) = next_binding {
2062            let name = next_ident;
2063            next_binding = match binding.kind {
2064                _ if res == Res::Err => None,
2065                NameBindingKind::Import { binding, import, .. } => match import.kind {
2066                    _ if binding.span.is_dummy() => None,
2067                    ImportKind::Single { source, .. } => {
2068                        next_ident = source;
2069                        Some(binding)
2070                    }
2071                    ImportKind::Glob { .. }
2072                    | ImportKind::MacroUse { .. }
2073                    | ImportKind::MacroExport => Some(binding),
2074                    ImportKind::ExternCrate { .. } => None,
2075                },
2076                _ => None,
2077            };
2078
2079            match binding.kind {
2080                NameBindingKind::Import { import, .. } => {
2081                    for segment in import.module_path.iter().skip(1) {
2082                        path.push(segment.ident);
2083                    }
2084                    sugg_paths.push((
2085                        path.iter().cloned().chain(std::iter::once(ident)).collect::<Vec<_>>(),
2086                        true, // re-export
2087                    ));
2088                }
2089                NameBindingKind::Res(_) => {}
2090            }
2091            let first = binding == first_binding;
2092            let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
2093            let mut note_span = MultiSpan::from_span(def_span);
2094            if !first && binding.vis.is_public() {
2095                let desc = match binding.kind {
2096                    NameBindingKind::Import { .. } => "re-export",
2097                    _ => "directly",
2098                };
2099                note_span.push_span_label(def_span, format!("you could import this {desc}"));
2100            }
2101            // Final step in the import chain, point out if the ADT is `non_exhaustive`
2102            // which is probably why this privacy violation occurred.
2103            if next_binding.is_none()
2104                && let Some(span) = non_exhaustive
2105            {
2106                note_span.push_span_label(
2107                    span,
2108                    "cannot be constructed because it is `#[non_exhaustive]`",
2109                );
2110            }
2111            let note = errors::NoteAndRefersToTheItemDefinedHere {
2112                span: note_span,
2113                binding_descr: get_descr(binding),
2114                binding_name: name,
2115                first,
2116                dots: next_binding.is_some(),
2117            };
2118            err.subdiagnostic(note);
2119        }
2120        // We prioritize shorter paths, non-core imports and direct imports over the alternatives.
2121        sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0].name == sym::core, *reexport));
2122        for (sugg, reexport) in sugg_paths {
2123            if not_publicly_reexported {
2124                break;
2125            }
2126            if sugg.len() <= 1 {
2127                // A single path segment suggestion is wrong. This happens on circular imports.
2128                // `tests/ui/imports/issue-55884-2.rs`
2129                continue;
2130            }
2131            let path = join_path_idents(sugg);
2132            let sugg = if reexport {
2133                errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
2134            } else {
2135                errors::ImportIdent::Directly { span: dedup_span, ident, path }
2136            };
2137            err.subdiagnostic(sugg);
2138            break;
2139        }
2140
2141        err.emit();
2142    }
2143
2144    pub(crate) fn find_similarly_named_module_or_crate(
2145        &self,
2146        ident: Symbol,
2147        current_module: Module<'ra>,
2148    ) -> Option<Symbol> {
2149        let mut candidates = self
2150            .extern_prelude
2151            .keys()
2152            .map(|ident| ident.name)
2153            .chain(
2154                self.local_module_map
2155                    .iter()
2156                    .filter(|(_, module)| {
2157                        current_module.is_ancestor_of(**module) && current_module != **module
2158                    })
2159                    .flat_map(|(_, module)| module.kind.name()),
2160            )
2161            .chain(
2162                self.extern_module_map
2163                    .borrow()
2164                    .iter()
2165                    .filter(|(_, module)| {
2166                        current_module.is_ancestor_of(**module) && current_module != **module
2167                    })
2168                    .flat_map(|(_, module)| module.kind.name()),
2169            )
2170            .filter(|c| !c.to_string().is_empty())
2171            .collect::<Vec<_>>();
2172        candidates.sort();
2173        candidates.dedup();
2174        find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
2175    }
2176
2177    pub(crate) fn report_path_resolution_error(
2178        &mut self,
2179        path: &[Segment],
2180        opt_ns: Option<Namespace>, // `None` indicates a module path in import
2181        parent_scope: &ParentScope<'ra>,
2182        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
2183        ignore_binding: Option<NameBinding<'ra>>,
2184        ignore_import: Option<Import<'ra>>,
2185        module: Option<ModuleOrUniformRoot<'ra>>,
2186        failed_segment_idx: usize,
2187        ident: Ident,
2188    ) -> (String, Option<Suggestion>) {
2189        let is_last = failed_segment_idx == path.len() - 1;
2190        let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2191        let module_res = match module {
2192            Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2193            _ => None,
2194        };
2195        if module_res == self.graph_root.res() {
2196            let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
2197            let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2198            candidates
2199                .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2200            if let Some(candidate) = candidates.get(0) {
2201                let path = {
2202                    // remove the possible common prefix of the path
2203                    let len = candidate.path.segments.len();
2204                    let start_index = (0..=failed_segment_idx.min(len - 1))
2205                        .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2206                        .unwrap_or_default();
2207                    let segments =
2208                        (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2209                    Path { segments, span: Span::default(), tokens: None }
2210                };
2211                (
2212                    String::from("unresolved import"),
2213                    Some((
2214                        vec![(ident.span, pprust::path_to_string(&path))],
2215                        String::from("a similar path exists"),
2216                        Applicability::MaybeIncorrect,
2217                    )),
2218                )
2219            } else if ident.name == sym::core {
2220                (
2221                    format!("you might be missing crate `{ident}`"),
2222                    Some((
2223                        vec![(ident.span, "std".to_string())],
2224                        "try using `std` instead of `core`".to_string(),
2225                        Applicability::MaybeIncorrect,
2226                    )),
2227                )
2228            } else if ident.name == kw::Underscore {
2229                (format!("`_` is not a valid crate or module name"), None)
2230            } else if self.tcx.sess.is_rust_2015() {
2231                (
2232                    format!("use of unresolved module or unlinked crate `{ident}`"),
2233                    Some((
2234                        vec![(
2235                            self.current_crate_outer_attr_insert_span,
2236                            format!("extern crate {ident};\n"),
2237                        )],
2238                        if was_invoked_from_cargo() {
2239                            format!(
2240                                "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2241                             to add it to your `Cargo.toml` and import it in your code",
2242                            )
2243                        } else {
2244                            format!(
2245                                "you might be missing a crate named `{ident}`, add it to your \
2246                                 project and import it in your code",
2247                            )
2248                        },
2249                        Applicability::MaybeIncorrect,
2250                    )),
2251                )
2252            } else {
2253                (format!("could not find `{ident}` in the crate root"), None)
2254            }
2255        } else if failed_segment_idx > 0 {
2256            let parent = path[failed_segment_idx - 1].ident.name;
2257            let parent = match parent {
2258                // ::foo is mounted at the crate root for 2015, and is the extern
2259                // prelude for 2018+
2260                kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2261                    "the list of imported crates".to_owned()
2262                }
2263                kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2264                _ => format!("`{parent}`"),
2265            };
2266
2267            let mut msg = format!("could not find `{ident}` in {parent}");
2268            if ns == TypeNS || ns == ValueNS {
2269                let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2270                let binding = if let Some(module) = module {
2271                    self.cm()
2272                        .resolve_ident_in_module(
2273                            module,
2274                            ident,
2275                            ns_to_try,
2276                            parent_scope,
2277                            None,
2278                            ignore_binding,
2279                            ignore_import,
2280                        )
2281                        .ok()
2282                } else if let Some(ribs) = ribs
2283                    && let Some(TypeNS | ValueNS) = opt_ns
2284                {
2285                    assert!(ignore_import.is_none());
2286                    match self.resolve_ident_in_lexical_scope(
2287                        ident,
2288                        ns_to_try,
2289                        parent_scope,
2290                        None,
2291                        &ribs[ns_to_try],
2292                        ignore_binding,
2293                    ) {
2294                        // we found a locally-imported or available item/module
2295                        Some(LexicalScopeBinding::Item(binding)) => Some(binding),
2296                        _ => None,
2297                    }
2298                } else {
2299                    self.cm()
2300                        .early_resolve_ident_in_lexical_scope(
2301                            ident,
2302                            ScopeSet::All(ns_to_try),
2303                            parent_scope,
2304                            None,
2305                            false,
2306                            ignore_binding,
2307                            ignore_import,
2308                        )
2309                        .ok()
2310                };
2311                if let Some(binding) = binding {
2312                    msg = format!(
2313                        "expected {}, found {} `{ident}` in {parent}",
2314                        ns.descr(),
2315                        binding.res().descr(),
2316                    );
2317                };
2318            }
2319            (msg, None)
2320        } else if ident.name == kw::SelfUpper {
2321            // As mentioned above, `opt_ns` being `None` indicates a module path in import.
2322            // We can use this to improve a confusing error for, e.g. `use Self::Variant` in an
2323            // impl
2324            if opt_ns.is_none() {
2325                ("`Self` cannot be used in imports".to_string(), None)
2326            } else {
2327                (
2328                    "`Self` is only available in impls, traits, and type definitions".to_string(),
2329                    None,
2330                )
2331            }
2332        } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2333            // Check whether the name refers to an item in the value namespace.
2334            let binding = if let Some(ribs) = ribs {
2335                assert!(ignore_import.is_none());
2336                self.resolve_ident_in_lexical_scope(
2337                    ident,
2338                    ValueNS,
2339                    parent_scope,
2340                    None,
2341                    &ribs[ValueNS],
2342                    ignore_binding,
2343                )
2344            } else {
2345                None
2346            };
2347            let match_span = match binding {
2348                // Name matches a local variable. For example:
2349                // ```
2350                // fn f() {
2351                //     let Foo: &str = "";
2352                //     println!("{}", Foo::Bar); // Name refers to local
2353                //                               // variable `Foo`.
2354                // }
2355                // ```
2356                Some(LexicalScopeBinding::Res(Res::Local(id))) => {
2357                    Some(*self.pat_span_map.get(&id).unwrap())
2358                }
2359                // Name matches item from a local name binding
2360                // created by `use` declaration. For example:
2361                // ```
2362                // pub Foo: &str = "";
2363                //
2364                // mod submod {
2365                //     use super::Foo;
2366                //     println!("{}", Foo::Bar); // Name refers to local
2367                //                               // binding `Foo`.
2368                // }
2369                // ```
2370                Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
2371                _ => None,
2372            };
2373            let suggestion = match_span.map(|span| {
2374                (
2375                    vec![(span, String::from(""))],
2376                    format!("`{ident}` is defined here, but is not a type"),
2377                    Applicability::MaybeIncorrect,
2378                )
2379            });
2380
2381            (format!("use of undeclared type `{ident}`"), suggestion)
2382        } else {
2383            let mut suggestion = None;
2384            if ident.name == sym::alloc {
2385                suggestion = Some((
2386                    vec![],
2387                    String::from("add `extern crate alloc` to use the `alloc` crate"),
2388                    Applicability::MaybeIncorrect,
2389                ))
2390            }
2391
2392            suggestion = suggestion.or_else(|| {
2393                self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2394                    |sugg| {
2395                        (
2396                            vec![(ident.span, sugg.to_string())],
2397                            String::from("there is a crate or module with a similar name"),
2398                            Applicability::MaybeIncorrect,
2399                        )
2400                    },
2401                )
2402            });
2403            if let Ok(binding) = self.cm().early_resolve_ident_in_lexical_scope(
2404                ident,
2405                ScopeSet::All(ValueNS),
2406                parent_scope,
2407                None,
2408                false,
2409                ignore_binding,
2410                ignore_import,
2411            ) {
2412                let descr = binding.res().descr();
2413                (format!("{descr} `{ident}` is not a crate or module"), suggestion)
2414            } else {
2415                let suggestion = if suggestion.is_some() {
2416                    suggestion
2417                } else if let Some(m) = self.undeclared_module_exists(ident) {
2418                    self.undeclared_module_suggest_declare(ident, m)
2419                } else if was_invoked_from_cargo() {
2420                    Some((
2421                        vec![],
2422                        format!(
2423                            "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2424                             to add it to your `Cargo.toml`",
2425                        ),
2426                        Applicability::MaybeIncorrect,
2427                    ))
2428                } else {
2429                    Some((
2430                        vec![],
2431                        format!("you might be missing a crate named `{ident}`",),
2432                        Applicability::MaybeIncorrect,
2433                    ))
2434                };
2435                (format!("use of unresolved module or unlinked crate `{ident}`"), suggestion)
2436            }
2437        }
2438    }
2439
2440    fn undeclared_module_suggest_declare(
2441        &self,
2442        ident: Ident,
2443        path: std::path::PathBuf,
2444    ) -> Option<(Vec<(Span, String)>, String, Applicability)> {
2445        Some((
2446            vec![(self.current_crate_outer_attr_insert_span, format!("mod {ident};\n"))],
2447            format!(
2448                "to make use of source file {}, use `mod {ident}` \
2449                 in this file to declare the module",
2450                path.display()
2451            ),
2452            Applicability::MaybeIncorrect,
2453        ))
2454    }
2455
2456    fn undeclared_module_exists(&self, ident: Ident) -> Option<std::path::PathBuf> {
2457        let map = self.tcx.sess.source_map();
2458
2459        let src = map.span_to_filename(ident.span).into_local_path()?;
2460        let i = ident.as_str();
2461        // FIXME: add case where non parent using undeclared module (hard?)
2462        let dir = src.parent()?;
2463        let src = src.file_stem()?.to_str()?;
2464        for file in [
2465            // …/x.rs
2466            dir.join(i).with_extension("rs"),
2467            // …/x/mod.rs
2468            dir.join(i).join("mod.rs"),
2469        ] {
2470            if file.exists() {
2471                return Some(file);
2472            }
2473        }
2474        if !matches!(src, "main" | "lib" | "mod") {
2475            for file in [
2476                // …/x/y.rs
2477                dir.join(src).join(i).with_extension("rs"),
2478                // …/x/y/mod.rs
2479                dir.join(src).join(i).join("mod.rs"),
2480            ] {
2481                if file.exists() {
2482                    return Some(file);
2483                }
2484            }
2485        }
2486        None
2487    }
2488
2489    /// Adds suggestions for a path that cannot be resolved.
2490    #[instrument(level = "debug", skip(self, parent_scope))]
2491    pub(crate) fn make_path_suggestion(
2492        &mut self,
2493        mut path: Vec<Segment>,
2494        parent_scope: &ParentScope<'ra>,
2495    ) -> Option<(Vec<Segment>, Option<String>)> {
2496        match path[..] {
2497            // `{{root}}::ident::...` on both editions.
2498            // On 2015 `{{root}}` is usually added implicitly.
2499            [first, second, ..]
2500                if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2501            // `ident::...` on 2018.
2502            [first, ..]
2503                if first.ident.span.at_least_rust_2018()
2504                    && !first.ident.is_path_segment_keyword() =>
2505            {
2506                // Insert a placeholder that's later replaced by `self`/`super`/etc.
2507                path.insert(0, Segment::from_ident(Ident::dummy()));
2508            }
2509            _ => return None,
2510        }
2511
2512        self.make_missing_self_suggestion(path.clone(), parent_scope)
2513            .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2514            .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2515            .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2516    }
2517
2518    /// Suggest a missing `self::` if that resolves to an correct module.
2519    ///
2520    /// ```text
2521    ///    |
2522    /// LL | use foo::Bar;
2523    ///    |     ^^^ did you mean `self::foo`?
2524    /// ```
2525    #[instrument(level = "debug", skip(self, parent_scope))]
2526    fn make_missing_self_suggestion(
2527        &mut self,
2528        mut path: Vec<Segment>,
2529        parent_scope: &ParentScope<'ra>,
2530    ) -> Option<(Vec<Segment>, Option<String>)> {
2531        // Replace first ident with `self` and check if that is valid.
2532        path[0].ident.name = kw::SelfLower;
2533        let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2534        debug!(?path, ?result);
2535        if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2536    }
2537
2538    /// Suggests a missing `crate::` if that resolves to an correct module.
2539    ///
2540    /// ```text
2541    ///    |
2542    /// LL | use foo::Bar;
2543    ///    |     ^^^ did you mean `crate::foo`?
2544    /// ```
2545    #[instrument(level = "debug", skip(self, parent_scope))]
2546    fn make_missing_crate_suggestion(
2547        &mut self,
2548        mut path: Vec<Segment>,
2549        parent_scope: &ParentScope<'ra>,
2550    ) -> Option<(Vec<Segment>, Option<String>)> {
2551        // Replace first ident with `crate` and check if that is valid.
2552        path[0].ident.name = kw::Crate;
2553        let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2554        debug!(?path, ?result);
2555        if let PathResult::Module(..) = result {
2556            Some((
2557                path,
2558                Some(
2559                    "`use` statements changed in Rust 2018; read more at \
2560                     <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2561                     clarity.html>"
2562                        .to_string(),
2563                ),
2564            ))
2565        } else {
2566            None
2567        }
2568    }
2569
2570    /// Suggests a missing `super::` if that resolves to an correct module.
2571    ///
2572    /// ```text
2573    ///    |
2574    /// LL | use foo::Bar;
2575    ///    |     ^^^ did you mean `super::foo`?
2576    /// ```
2577    #[instrument(level = "debug", skip(self, parent_scope))]
2578    fn make_missing_super_suggestion(
2579        &mut self,
2580        mut path: Vec<Segment>,
2581        parent_scope: &ParentScope<'ra>,
2582    ) -> Option<(Vec<Segment>, Option<String>)> {
2583        // Replace first ident with `crate` and check if that is valid.
2584        path[0].ident.name = kw::Super;
2585        let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2586        debug!(?path, ?result);
2587        if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2588    }
2589
2590    /// Suggests a missing external crate name if that resolves to an correct module.
2591    ///
2592    /// ```text
2593    ///    |
2594    /// LL | use foobar::Baz;
2595    ///    |     ^^^^^^ did you mean `baz::foobar`?
2596    /// ```
2597    ///
2598    /// Used when importing a submodule of an external crate but missing that crate's
2599    /// name as the first part of path.
2600    #[instrument(level = "debug", skip(self, parent_scope))]
2601    fn make_external_crate_suggestion(
2602        &mut self,
2603        mut path: Vec<Segment>,
2604        parent_scope: &ParentScope<'ra>,
2605    ) -> Option<(Vec<Segment>, Option<String>)> {
2606        if path[1].ident.span.is_rust_2015() {
2607            return None;
2608        }
2609
2610        // Sort extern crate names in *reverse* order to get
2611        // 1) some consistent ordering for emitted diagnostics, and
2612        // 2) `std` suggestions before `core` suggestions.
2613        let mut extern_crate_names =
2614            self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2615        extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
2616
2617        for name in extern_crate_names.into_iter() {
2618            // Replace first ident with a crate name and check if that is valid.
2619            path[0].ident.name = name;
2620            let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2621            debug!(?path, ?name, ?result);
2622            if let PathResult::Module(..) = result {
2623                return Some((path, None));
2624            }
2625        }
2626
2627        None
2628    }
2629
2630    /// Suggests importing a macro from the root of the crate rather than a module within
2631    /// the crate.
2632    ///
2633    /// ```text
2634    /// help: a macro with this name exists at the root of the crate
2635    ///    |
2636    /// LL | use issue_59764::makro;
2637    ///    |     ^^^^^^^^^^^^^^^^^^
2638    ///    |
2639    ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
2640    ///            at the root of the crate instead of the module where it is defined
2641    /// ```
2642    pub(crate) fn check_for_module_export_macro(
2643        &mut self,
2644        import: Import<'ra>,
2645        module: ModuleOrUniformRoot<'ra>,
2646        ident: Ident,
2647    ) -> Option<(Option<Suggestion>, Option<String>)> {
2648        let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2649            return None;
2650        };
2651
2652        while let Some(parent) = crate_module.parent {
2653            crate_module = parent;
2654        }
2655
2656        if module == ModuleOrUniformRoot::Module(crate_module) {
2657            // Don't make a suggestion if the import was already from the root of the crate.
2658            return None;
2659        }
2660
2661        let binding_key = BindingKey::new(ident, MacroNS);
2662        let binding = self.resolution(crate_module, binding_key)?.binding()?;
2663        let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() else {
2664            return None;
2665        };
2666        let module_name = crate_module.kind.name().unwrap_or(kw::Crate);
2667        let import_snippet = match import.kind {
2668            ImportKind::Single { source, target, .. } if source != target => {
2669                format!("{source} as {target}")
2670            }
2671            _ => format!("{ident}"),
2672        };
2673
2674        let mut corrections: Vec<(Span, String)> = Vec::new();
2675        if !import.is_nested() {
2676            // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2677            // intermediate segments.
2678            corrections.push((import.span, format!("{module_name}::{import_snippet}")));
2679        } else {
2680            // Find the binding span (and any trailing commas and spaces).
2681            //   ie. `use a::b::{c, d, e};`
2682            //                      ^^^
2683            let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2684                self.tcx.sess,
2685                import.span,
2686                import.use_span,
2687            );
2688            debug!(found_closing_brace, ?binding_span);
2689
2690            let mut removal_span = binding_span;
2691
2692            // If the binding span ended with a closing brace, as in the below example:
2693            //   ie. `use a::b::{c, d};`
2694            //                      ^
2695            // Then expand the span of characters to remove to include the previous
2696            // binding's trailing comma.
2697            //   ie. `use a::b::{c, d};`
2698            //                    ^^^
2699            if found_closing_brace
2700                && let Some(previous_span) =
2701                    extend_span_to_previous_binding(self.tcx.sess, binding_span)
2702            {
2703                debug!(?previous_span);
2704                removal_span = removal_span.with_lo(previous_span.lo());
2705            }
2706            debug!(?removal_span);
2707
2708            // Remove the `removal_span`.
2709            corrections.push((removal_span, "".to_string()));
2710
2711            // Find the span after the crate name and if it has nested imports immediately
2712            // after the crate name already.
2713            //   ie. `use a::b::{c, d};`
2714            //               ^^^^^^^^^
2715            //   or  `use a::{b, c, d}};`
2716            //               ^^^^^^^^^^^
2717            let (has_nested, after_crate_name) =
2718                find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
2719            debug!(has_nested, ?after_crate_name);
2720
2721            let source_map = self.tcx.sess.source_map();
2722
2723            // Make sure this is actually crate-relative.
2724            let is_definitely_crate = import
2725                .module_path
2726                .first()
2727                .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
2728
2729            // Add the import to the start, with a `{` if required.
2730            let start_point = source_map.start_point(after_crate_name);
2731            if is_definitely_crate
2732                && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
2733            {
2734                corrections.push((
2735                    start_point,
2736                    if has_nested {
2737                        // In this case, `start_snippet` must equal '{'.
2738                        format!("{start_snippet}{import_snippet}, ")
2739                    } else {
2740                        // In this case, add a `{`, then the moved import, then whatever
2741                        // was there before.
2742                        format!("{{{import_snippet}, {start_snippet}")
2743                    },
2744                ));
2745
2746                // Add a `};` to the end if nested, matching the `{` added at the start.
2747                if !has_nested {
2748                    corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2749                }
2750            } else {
2751                // If the root import is module-relative, add the import separately
2752                corrections.push((
2753                    import.use_span.shrink_to_lo(),
2754                    format!("use {module_name}::{import_snippet};\n"),
2755                ));
2756            }
2757        }
2758
2759        let suggestion = Some((
2760            corrections,
2761            String::from("a macro with this name exists at the root of the crate"),
2762            Applicability::MaybeIncorrect,
2763        ));
2764        Some((
2765            suggestion,
2766            Some(
2767                "this could be because a macro annotated with `#[macro_export]` will be exported \
2768            at the root of the crate instead of the module where it is defined"
2769                    .to_string(),
2770            ),
2771        ))
2772    }
2773
2774    /// Finds a cfg-ed out item inside `module` with the matching name.
2775    pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
2776        let local_items;
2777        let symbols = if module.is_local() {
2778            local_items = self
2779                .stripped_cfg_items
2780                .iter()
2781                .filter_map(|item| {
2782                    let parent_module = self.opt_local_def_id(item.parent_module)?.to_def_id();
2783                    Some(StrippedCfgItem {
2784                        parent_module,
2785                        ident: item.ident,
2786                        cfg: item.cfg.clone(),
2787                    })
2788                })
2789                .collect::<Vec<_>>();
2790            local_items.as_slice()
2791        } else {
2792            self.tcx.stripped_cfg_items(module.krate)
2793        };
2794
2795        for &StrippedCfgItem { parent_module, ident, ref cfg } in symbols {
2796            if ident.name != *segment {
2797                continue;
2798            }
2799
2800            fn comes_from_same_module_for_glob(
2801                r: &Resolver<'_, '_>,
2802                parent_module: DefId,
2803                module: DefId,
2804                visited: &mut FxHashMap<DefId, bool>,
2805            ) -> bool {
2806                if let Some(&cached) = visited.get(&parent_module) {
2807                    // this branch is prevent from being called recursively infinity,
2808                    // because there has some cycles in globs imports,
2809                    // see more spec case at `tests/ui/cfg/diagnostics-reexport-2.rs#reexport32`
2810                    return cached;
2811                }
2812                visited.insert(parent_module, false);
2813                let m = r.expect_module(parent_module);
2814                let mut res = false;
2815                for importer in m.glob_importers.borrow().iter() {
2816                    if let Some(next_parent_module) = importer.parent_scope.module.opt_def_id() {
2817                        if next_parent_module == module
2818                            || comes_from_same_module_for_glob(
2819                                r,
2820                                next_parent_module,
2821                                module,
2822                                visited,
2823                            )
2824                        {
2825                            res = true;
2826                            break;
2827                        }
2828                    }
2829                }
2830                visited.insert(parent_module, res);
2831                res
2832            }
2833
2834            let comes_from_same_module = parent_module == module
2835                || comes_from_same_module_for_glob(
2836                    self,
2837                    parent_module,
2838                    module,
2839                    &mut Default::default(),
2840                );
2841            if !comes_from_same_module {
2842                continue;
2843            }
2844
2845            let item_was = if let CfgEntry::NameValue { value: Some((feature, _)), .. } = cfg.0 {
2846                errors::ItemWas::BehindFeature { feature, span: cfg.1 }
2847            } else {
2848                errors::ItemWas::CfgOut { span: cfg.1 }
2849            };
2850            let note = errors::FoundItemConfigureOut { span: ident.span, item_was };
2851            err.subdiagnostic(note);
2852        }
2853    }
2854}
2855
2856/// Given a `binding_span` of a binding within a use statement:
2857///
2858/// ```ignore (illustrative)
2859/// use foo::{a, b, c};
2860/// //           ^
2861/// ```
2862///
2863/// then return the span until the next binding or the end of the statement:
2864///
2865/// ```ignore (illustrative)
2866/// use foo::{a, b, c};
2867/// //           ^^^
2868/// ```
2869fn find_span_of_binding_until_next_binding(
2870    sess: &Session,
2871    binding_span: Span,
2872    use_span: Span,
2873) -> (bool, Span) {
2874    let source_map = sess.source_map();
2875
2876    // Find the span of everything after the binding.
2877    //   ie. `a, e};` or `a};`
2878    let binding_until_end = binding_span.with_hi(use_span.hi());
2879
2880    // Find everything after the binding but not including the binding.
2881    //   ie. `, e};` or `};`
2882    let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2883
2884    // Keep characters in the span until we encounter something that isn't a comma or
2885    // whitespace.
2886    //   ie. `, ` or ``.
2887    //
2888    // Also note whether a closing brace character was encountered. If there
2889    // was, then later go backwards to remove any trailing commas that are left.
2890    let mut found_closing_brace = false;
2891    let after_binding_until_next_binding =
2892        source_map.span_take_while(after_binding_until_end, |&ch| {
2893            if ch == '}' {
2894                found_closing_brace = true;
2895            }
2896            ch == ' ' || ch == ','
2897        });
2898
2899    // Combine the two spans.
2900    //   ie. `a, ` or `a`.
2901    //
2902    // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2903    let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2904
2905    (found_closing_brace, span)
2906}
2907
2908/// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2909/// binding.
2910///
2911/// ```ignore (illustrative)
2912/// use foo::a::{a, b, c};
2913/// //            ^^--- binding span
2914/// //            |
2915/// //            returned span
2916///
2917/// use foo::{a, b, c};
2918/// //        --- binding span
2919/// ```
2920fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2921    let source_map = sess.source_map();
2922
2923    // `prev_source` will contain all of the source that came before the span.
2924    // Then split based on a command and take the first (ie. closest to our span)
2925    // snippet. In the example, this is a space.
2926    let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2927
2928    let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2929    let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2930    if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2931        return None;
2932    }
2933
2934    let prev_comma = prev_comma.first().unwrap();
2935    let prev_starting_brace = prev_starting_brace.first().unwrap();
2936
2937    // If the amount of source code before the comma is greater than
2938    // the amount of source code before the starting brace then we've only
2939    // got one item in the nested item (eg. `issue_52891::{self}`).
2940    if prev_comma.len() > prev_starting_brace.len() {
2941        return None;
2942    }
2943
2944    Some(binding_span.with_lo(BytePos(
2945        // Take away the number of bytes for the characters we've found and an
2946        // extra for the comma.
2947        binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2948    )))
2949}
2950
2951/// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2952/// it is a nested use tree.
2953///
2954/// ```ignore (illustrative)
2955/// use foo::a::{b, c};
2956/// //       ^^^^^^^^^^ -- false
2957///
2958/// use foo::{a, b, c};
2959/// //       ^^^^^^^^^^ -- true
2960///
2961/// use foo::{a, b::{c, d}};
2962/// //       ^^^^^^^^^^^^^^^ -- true
2963/// ```
2964#[instrument(level = "debug", skip(sess))]
2965fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
2966    let source_map = sess.source_map();
2967
2968    // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2969    let mut num_colons = 0;
2970    // Find second colon.. `use issue_59764:`
2971    let until_second_colon = source_map.span_take_while(use_span, |c| {
2972        if *c == ':' {
2973            num_colons += 1;
2974        }
2975        !matches!(c, ':' if num_colons == 2)
2976    });
2977    // Find everything after the second colon.. `foo::{baz, makro};`
2978    let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2979
2980    let mut found_a_non_whitespace_character = false;
2981    // Find the first non-whitespace character in `from_second_colon`.. `f`
2982    let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2983        if found_a_non_whitespace_character {
2984            return false;
2985        }
2986        if !c.is_whitespace() {
2987            found_a_non_whitespace_character = true;
2988        }
2989        true
2990    });
2991
2992    // Find the first `{` in from_second_colon.. `foo::{`
2993    let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2994
2995    (next_left_bracket == after_second_colon, from_second_colon)
2996}
2997
2998/// A suggestion has already been emitted, change the wording slightly to clarify that both are
2999/// independent options.
3000enum Instead {
3001    Yes,
3002    No,
3003}
3004
3005/// Whether an existing place with an `use` item was found.
3006enum FoundUse {
3007    Yes,
3008    No,
3009}
3010
3011/// Whether a binding is part of a pattern or a use statement. Used for diagnostics.
3012pub(crate) enum DiagMode {
3013    Normal,
3014    /// The binding is part of a pattern
3015    Pattern,
3016    /// The binding is part of a use statement
3017    Import {
3018        /// `true` means diagnostics is for unresolved import
3019        unresolved_import: bool,
3020        /// `true` mean add the tips afterward for case `use a::{b,c}`,
3021        /// rather than replacing within.
3022        append: bool,
3023    },
3024}
3025
3026pub(crate) fn import_candidates(
3027    tcx: TyCtxt<'_>,
3028    err: &mut Diag<'_>,
3029    // This is `None` if all placement locations are inside expansions
3030    use_placement_span: Option<Span>,
3031    candidates: &[ImportSuggestion],
3032    mode: DiagMode,
3033    append: &str,
3034) {
3035    show_candidates(
3036        tcx,
3037        err,
3038        use_placement_span,
3039        candidates,
3040        Instead::Yes,
3041        FoundUse::Yes,
3042        mode,
3043        vec![],
3044        append,
3045    );
3046}
3047
3048type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
3049
3050/// When an entity with a given name is not available in scope, we search for
3051/// entities with that name in all crates. This method allows outputting the
3052/// results of this search in a programmer-friendly way. If any entities are
3053/// found and suggested, returns `true`, otherwise returns `false`.
3054fn show_candidates(
3055    tcx: TyCtxt<'_>,
3056    err: &mut Diag<'_>,
3057    // This is `None` if all placement locations are inside expansions
3058    use_placement_span: Option<Span>,
3059    candidates: &[ImportSuggestion],
3060    instead: Instead,
3061    found_use: FoundUse,
3062    mode: DiagMode,
3063    path: Vec<Segment>,
3064    append: &str,
3065) -> bool {
3066    if candidates.is_empty() {
3067        return false;
3068    }
3069
3070    let mut showed = false;
3071    let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
3072    let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
3073
3074    candidates.iter().for_each(|c| {
3075        if c.accessible {
3076            // Don't suggest `#[doc(hidden)]` items from other crates
3077            if c.doc_visible {
3078                accessible_path_strings.push((
3079                    pprust::path_to_string(&c.path),
3080                    c.descr,
3081                    c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3082                    &c.note,
3083                    c.via_import,
3084                ))
3085            }
3086        } else {
3087            inaccessible_path_strings.push((
3088                pprust::path_to_string(&c.path),
3089                c.descr,
3090                c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3091                &c.note,
3092                c.via_import,
3093            ))
3094        }
3095    });
3096
3097    // we want consistent results across executions, but candidates are produced
3098    // by iterating through a hash map, so make sure they are ordered:
3099    for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
3100        path_strings.sort_by(|a, b| a.0.cmp(&b.0));
3101        path_strings.dedup_by(|a, b| a.0 == b.0);
3102        let core_path_strings =
3103            path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
3104        let std_path_strings =
3105            path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
3106        let foreign_crate_path_strings =
3107            path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
3108
3109        // We list the `crate` local paths first.
3110        // Then we list the `std`/`core` paths.
3111        if std_path_strings.len() == core_path_strings.len() {
3112            // Do not list `core::` paths if we are already listing the `std::` ones.
3113            path_strings.extend(std_path_strings);
3114        } else {
3115            path_strings.extend(std_path_strings);
3116            path_strings.extend(core_path_strings);
3117        }
3118        // List all paths from foreign crates last.
3119        path_strings.extend(foreign_crate_path_strings);
3120    }
3121
3122    if !accessible_path_strings.is_empty() {
3123        let (determiner, kind, s, name, through) =
3124            if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
3125                (
3126                    "this",
3127                    *descr,
3128                    "",
3129                    format!(" `{name}`"),
3130                    if *via_import { " through its public re-export" } else { "" },
3131                )
3132            } else {
3133                // Get the unique item kinds and if there's only one, we use the right kind name
3134                // instead of the more generic "items".
3135                let kinds = accessible_path_strings
3136                    .iter()
3137                    .map(|(_, descr, _, _, _)| *descr)
3138                    .collect::<UnordSet<&str>>();
3139                let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
3140                let s = if kind.ends_with('s') { "es" } else { "s" };
3141
3142                ("one of these", kind, s, String::new(), "")
3143            };
3144
3145        let instead = if let Instead::Yes = instead { " instead" } else { "" };
3146        let mut msg = if let DiagMode::Pattern = mode {
3147            format!(
3148                "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
3149                 pattern",
3150            )
3151        } else {
3152            format!("consider importing {determiner} {kind}{s}{through}{instead}")
3153        };
3154
3155        for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3156            err.note(note.clone());
3157        }
3158
3159        let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
3160            msg.push(':');
3161
3162            for candidate in accessible_path_strings {
3163                msg.push('\n');
3164                msg.push_str(&candidate.0);
3165            }
3166        };
3167
3168        if let Some(span) = use_placement_span {
3169            let (add_use, trailing) = match mode {
3170                DiagMode::Pattern => {
3171                    err.span_suggestions(
3172                        span,
3173                        msg,
3174                        accessible_path_strings.into_iter().map(|a| a.0),
3175                        Applicability::MaybeIncorrect,
3176                    );
3177                    return true;
3178                }
3179                DiagMode::Import { .. } => ("", ""),
3180                DiagMode::Normal => ("use ", ";\n"),
3181            };
3182            for candidate in &mut accessible_path_strings {
3183                // produce an additional newline to separate the new use statement
3184                // from the directly following item.
3185                let additional_newline = if let FoundUse::No = found_use
3186                    && let DiagMode::Normal = mode
3187                {
3188                    "\n"
3189                } else {
3190                    ""
3191                };
3192                candidate.0 =
3193                    format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
3194            }
3195
3196            match mode {
3197                DiagMode::Import { append: true, .. } => {
3198                    append_candidates(&mut msg, accessible_path_strings);
3199                    err.span_help(span, msg);
3200                }
3201                _ => {
3202                    err.span_suggestions_with_style(
3203                        span,
3204                        msg,
3205                        accessible_path_strings.into_iter().map(|a| a.0),
3206                        Applicability::MaybeIncorrect,
3207                        SuggestionStyle::ShowAlways,
3208                    );
3209                }
3210            }
3211
3212            if let [first, .., last] = &path[..] {
3213                let sp = first.ident.span.until(last.ident.span);
3214                // Our suggestion is empty, so make sure the span is not empty (or we'd ICE).
3215                // Can happen for derive-generated spans.
3216                if sp.can_be_used_for_suggestions() && !sp.is_empty() {
3217                    err.span_suggestion_verbose(
3218                        sp,
3219                        format!("if you import `{}`, refer to it directly", last.ident),
3220                        "",
3221                        Applicability::Unspecified,
3222                    );
3223                }
3224            }
3225        } else {
3226            append_candidates(&mut msg, accessible_path_strings);
3227            err.help(msg);
3228        }
3229        showed = true;
3230    }
3231    if !inaccessible_path_strings.is_empty()
3232        && (!matches!(mode, DiagMode::Import { unresolved_import: false, .. }))
3233    {
3234        let prefix =
3235            if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
3236        if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
3237            let msg = format!(
3238                "{prefix}{descr} `{name}`{} exists but is inaccessible",
3239                if let DiagMode::Pattern = mode { ", which" } else { "" }
3240            );
3241
3242            if let Some(source_span) = source_span {
3243                let span = tcx.sess.source_map().guess_head_span(*source_span);
3244                let mut multi_span = MultiSpan::from_span(span);
3245                multi_span.push_span_label(span, "not accessible");
3246                err.span_note(multi_span, msg);
3247            } else {
3248                err.note(msg);
3249            }
3250            if let Some(note) = (*note).as_deref() {
3251                err.note(note.to_string());
3252            }
3253        } else {
3254            let (_, descr_first, _, _, _) = &inaccessible_path_strings[0];
3255            let descr = if inaccessible_path_strings
3256                .iter()
3257                .skip(1)
3258                .all(|(_, descr, _, _, _)| descr == descr_first)
3259            {
3260                descr_first
3261            } else {
3262                "item"
3263            };
3264            let plural_descr =
3265                if descr.ends_with('s') { format!("{descr}es") } else { format!("{descr}s") };
3266
3267            let mut msg = format!("{prefix}these {plural_descr} exist but are inaccessible");
3268            let mut has_colon = false;
3269
3270            let mut spans = Vec::new();
3271            for (name, _, source_span, _, _) in &inaccessible_path_strings {
3272                if let Some(source_span) = source_span {
3273                    let span = tcx.sess.source_map().guess_head_span(*source_span);
3274                    spans.push((name, span));
3275                } else {
3276                    if !has_colon {
3277                        msg.push(':');
3278                        has_colon = true;
3279                    }
3280                    msg.push('\n');
3281                    msg.push_str(name);
3282                }
3283            }
3284
3285            let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3286            for (name, span) in spans {
3287                multi_span.push_span_label(span, format!("`{name}`: not accessible"));
3288            }
3289
3290            for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3291                err.note(note.clone());
3292            }
3293
3294            err.span_note(multi_span, msg);
3295        }
3296        showed = true;
3297    }
3298    showed
3299}
3300
3301#[derive(Debug)]
3302struct UsePlacementFinder {
3303    target_module: NodeId,
3304    first_legal_span: Option<Span>,
3305    first_use_span: Option<Span>,
3306}
3307
3308impl UsePlacementFinder {
3309    fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3310        let mut finder =
3311            UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3312        finder.visit_crate(krate);
3313        if let Some(use_span) = finder.first_use_span {
3314            (Some(use_span), FoundUse::Yes)
3315        } else {
3316            (finder.first_legal_span, FoundUse::No)
3317        }
3318    }
3319}
3320
3321impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
3322    fn visit_crate(&mut self, c: &Crate) {
3323        if self.target_module == CRATE_NODE_ID {
3324            let inject = c.spans.inject_use_span;
3325            if is_span_suitable_for_use_injection(inject) {
3326                self.first_legal_span = Some(inject);
3327            }
3328            self.first_use_span = search_for_any_use_in_items(&c.items);
3329        } else {
3330            visit::walk_crate(self, c);
3331        }
3332    }
3333
3334    fn visit_item(&mut self, item: &'tcx ast::Item) {
3335        if self.target_module == item.id {
3336            if let ItemKind::Mod(_, _, ModKind::Loaded(items, _inline, mod_spans, _)) = &item.kind {
3337                let inject = mod_spans.inject_use_span;
3338                if is_span_suitable_for_use_injection(inject) {
3339                    self.first_legal_span = Some(inject);
3340                }
3341                self.first_use_span = search_for_any_use_in_items(items);
3342            }
3343        } else {
3344            visit::walk_item(self, item);
3345        }
3346    }
3347}
3348
3349fn search_for_any_use_in_items(items: &[Box<ast::Item>]) -> Option<Span> {
3350    for item in items {
3351        if let ItemKind::Use(..) = item.kind
3352            && is_span_suitable_for_use_injection(item.span)
3353        {
3354            let mut lo = item.span.lo();
3355            for attr in &item.attrs {
3356                if attr.span.eq_ctxt(item.span) {
3357                    lo = std::cmp::min(lo, attr.span.lo());
3358                }
3359            }
3360            return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3361        }
3362    }
3363    None
3364}
3365
3366fn is_span_suitable_for_use_injection(s: Span) -> bool {
3367    // don't suggest placing a use before the prelude
3368    // import or other generated ones
3369    !s.from_expansion()
3370}