Skip to main content

rustc_resolve/
diagnostics.rs

1use std::ops::ControlFlow;
2
3use itertools::Itertools as _;
4use rustc_ast::visit::{self, Visitor};
5use rustc_ast::{
6    self as ast, CRATE_NODE_ID, Crate, ItemKind, ModKind, NodeId, Path, join_path_idents,
7};
8use rustc_ast_pretty::pprust;
9use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10use rustc_data_structures::unord::{UnordMap, UnordSet};
11use rustc_errors::codes::*;
12use rustc_errors::{
13    Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, MultiSpan, SuggestionStyle,
14    struct_span_code_err,
15};
16use rustc_feature::BUILTIN_ATTRIBUTES;
17use rustc_hir::attrs::{CfgEntry, StrippedCfgItem};
18use rustc_hir::def::Namespace::{self, *};
19use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, MacroKinds, NonMacroAttrKind, PerNS};
20use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
21use rustc_hir::{PrimTy, Stability, StabilityLevel, find_attr};
22use rustc_middle::bug;
23use rustc_middle::ty::TyCtxt;
24use rustc_session::Session;
25use rustc_session::lint::BuiltinLintDiag;
26use rustc_session::lint::builtin::{
27    ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS, AMBIGUOUS_IMPORT_VISIBILITIES,
28    AMBIGUOUS_PANIC_IMPORTS, MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
29};
30use rustc_session::utils::was_invoked_from_cargo;
31use rustc_span::edit_distance::find_best_match_for_name;
32use rustc_span::edition::Edition;
33use rustc_span::hygiene::MacroKind;
34use rustc_span::source_map::{SourceMap, Spanned};
35use rustc_span::{BytePos, Ident, RemapPathScopeComponents, Span, Symbol, SyntaxContext, kw, sym};
36use thin_vec::{ThinVec, thin_vec};
37use tracing::{debug, instrument};
38
39use crate::errors::{
40    self, AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion, ConsiderAddingADerive,
41    ExplicitUnsafeTraits, MacroDefinedLater, MacroRulesNot, MacroSuggMovePosition,
42    MaybeMissingMacroRulesName,
43};
44use crate::hygiene::Macros20NormalizedSyntaxContext;
45use crate::imports::{Import, ImportKind};
46use crate::late::{DiagMetadata, PatternSource, Rib};
47use crate::{
48    AmbiguityError, AmbiguityKind, AmbiguityWarning, BindingError, BindingKey, Decl, DeclKind,
49    Finalize, ForwardGenericParamBanReason, HasGenericParams, IdentKey, LateDecl, MacroRulesScope,
50    Module, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, PrivacyError,
51    ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used, VisResolutionError,
52    errors as errs, path_names_to_string,
53};
54
55type Res = def::Res<ast::NodeId>;
56
57/// A vector of spans and replacements, a message and applicability.
58pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
59
60/// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
61/// similarly named label and whether or not it is reachable.
62pub(crate) type LabelSuggestion = (Ident, bool);
63
64#[derive(#[automatically_derived]
impl ::core::fmt::Debug for SuggestionTarget {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                SuggestionTarget::SimilarlyNamed => "SimilarlyNamed",
                SuggestionTarget::SingleItem => "SingleItem",
            })
    }
}Debug)]
65pub(crate) enum SuggestionTarget {
66    /// The target has a similar name as the name used by the programmer (probably a typo)
67    SimilarlyNamed,
68    /// The target is the only valid item that can be used in the corresponding context
69    SingleItem,
70}
71
72#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TypoSuggestion {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "TypoSuggestion", "candidate", &self.candidate, "span",
            &self.span, "res", &self.res, "target", &&self.target)
    }
}Debug)]
73pub(crate) struct TypoSuggestion {
74    pub candidate: Symbol,
75    /// The source location where the name is defined; None if the name is not defined
76    /// in source e.g. primitives
77    pub span: Option<Span>,
78    pub res: Res,
79    pub target: SuggestionTarget,
80}
81
82impl TypoSuggestion {
83    pub(crate) fn new(candidate: Symbol, span: Span, res: Res) -> TypoSuggestion {
84        Self { candidate, span: Some(span), res, target: SuggestionTarget::SimilarlyNamed }
85    }
86    pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
87        Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
88    }
89    pub(crate) fn single_item(candidate: Symbol, span: Span, res: Res) -> TypoSuggestion {
90        Self { candidate, span: Some(span), res, target: SuggestionTarget::SingleItem }
91    }
92}
93
94/// A free importable items suggested in case of resolution failure.
95#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ImportSuggestion {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["did", "descr", "path", "accessible", "doc_visible",
                        "via_import", "note", "is_stable"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.did, &self.descr, &self.path, &self.accessible,
                        &self.doc_visible, &self.via_import, &self.note,
                        &&self.is_stable];
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "ImportSuggestion", names, values)
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for ImportSuggestion {
    #[inline]
    fn clone(&self) -> ImportSuggestion {
        ImportSuggestion {
            did: ::core::clone::Clone::clone(&self.did),
            descr: ::core::clone::Clone::clone(&self.descr),
            path: ::core::clone::Clone::clone(&self.path),
            accessible: ::core::clone::Clone::clone(&self.accessible),
            doc_visible: ::core::clone::Clone::clone(&self.doc_visible),
            via_import: ::core::clone::Clone::clone(&self.via_import),
            note: ::core::clone::Clone::clone(&self.note),
            is_stable: ::core::clone::Clone::clone(&self.is_stable),
        }
    }
}Clone)]
96pub(crate) struct ImportSuggestion {
97    pub did: Option<DefId>,
98    pub descr: &'static str,
99    pub path: Path,
100    pub accessible: bool,
101    // false if the path traverses a foreign `#[doc(hidden)]` item.
102    pub doc_visible: bool,
103    pub via_import: bool,
104    /// An extra note that should be issued if this item is suggested
105    pub note: Option<String>,
106    pub is_stable: bool,
107}
108
109/// Adjust the impl span so that just the `impl` keyword is taken by removing
110/// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
111/// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
112///
113/// *Attention*: the method used is very fragile since it essentially duplicates the work of the
114/// parser. If you need to use this function or something similar, please consider updating the
115/// `source_map` functions and this function to something more robust.
116fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
117    let impl_span = sm.span_until_char(impl_span, '<');
118    sm.span_until_whitespace(impl_span)
119}
120
121impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
122    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
123        self.tcx.dcx()
124    }
125
126    pub(crate) fn report_errors(&mut self, krate: &Crate) {
127        self.report_with_use_injections(krate);
128
129        for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
130            self.lint_buffer.buffer_lint(
131                MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
132                CRATE_NODE_ID,
133                span_use,
134                errors::MacroExpandedMacroExportsAccessedByAbsolutePaths { definition: span_def },
135            );
136        }
137
138        for ambiguity_error in &self.ambiguity_errors {
139            let diag = self.ambiguity_diagnostic(ambiguity_error);
140
141            if let Some(ambiguity_warning) = ambiguity_error.warning {
142                let node_id = match ambiguity_error.b1.0.kind {
143                    DeclKind::Import { import, .. } => import.root_id,
144                    DeclKind::Def(_) => CRATE_NODE_ID,
145                };
146
147                let lint = match ambiguity_warning {
148                    _ if ambiguity_error.ambig_vis.is_some() => AMBIGUOUS_IMPORT_VISIBILITIES,
149                    AmbiguityWarning::GlobImport => AMBIGUOUS_GLOB_IMPORTS,
150                    AmbiguityWarning::PanicImport => AMBIGUOUS_PANIC_IMPORTS,
151                };
152
153                self.lint_buffer.buffer_lint(lint, node_id, diag.ident.span, diag);
154            } else {
155                self.dcx().emit_err(diag);
156            }
157        }
158
159        let mut reported_spans = FxHashSet::default();
160        for error in std::mem::take(&mut self.privacy_errors) {
161            if reported_spans.insert(error.dedup_span) {
162                self.report_privacy_error(&error);
163            }
164        }
165    }
166
167    fn report_with_use_injections(&mut self, krate: &Crate) {
168        for UseError { mut err, candidates, def_id, instead, suggestion, path, is_call } in
169            std::mem::take(&mut self.use_injections)
170        {
171            let (span, found_use) = if let Some(def_id) = def_id.as_local() {
172                UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id))
173            } else {
174                (None, FoundUse::No)
175            };
176
177            if !candidates.is_empty() {
178                show_candidates(
179                    self.tcx,
180                    &mut err,
181                    span,
182                    &candidates,
183                    if instead { Instead::Yes } else { Instead::No },
184                    found_use,
185                    DiagMode::Normal,
186                    path,
187                    "",
188                );
189                err.emit();
190            } else if let Some((span, msg, sugg, appl)) = suggestion {
191                err.span_suggestion_verbose(span, msg, sugg, appl);
192                err.emit();
193            } else if let [segment] = path.as_slice()
194                && is_call
195            {
196                err.stash(segment.ident.span, rustc_errors::StashKey::CallIntoMethod);
197            } else {
198                err.emit();
199            }
200        }
201    }
202
203    pub(crate) fn report_conflict(
204        &mut self,
205        ident: IdentKey,
206        ns: Namespace,
207        old_binding: Decl<'ra>,
208        new_binding: Decl<'ra>,
209    ) {
210        // Error on the second of two conflicting names
211        if old_binding.span.lo() > new_binding.span.lo() {
212            return self.report_conflict(ident, ns, new_binding, old_binding);
213        }
214
215        let container = match old_binding.parent_module.unwrap().kind {
216            // Avoid using TyCtxt::def_kind_descr in the resolver, because it
217            // indirectly *calls* the resolver, and would cause a query cycle.
218            ModuleKind::Def(kind, def_id, _) => kind.descr(def_id),
219            ModuleKind::Block => "block",
220        };
221
222        let (name, span) =
223            (ident.name, self.tcx.sess.source_map().guess_head_span(new_binding.span));
224
225        if self.name_already_seen.get(&name) == Some(&span) {
226            return;
227        }
228
229        let old_kind = match (ns, old_binding.res()) {
230            (ValueNS, _) => "value",
231            (MacroNS, _) => "macro",
232            (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
233            (TypeNS, Res::Def(DefKind::Mod, _)) => "module",
234            (TypeNS, Res::Def(DefKind::Trait, _)) => "trait",
235            (TypeNS, _) => "type",
236        };
237
238        let code = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
239            (true, true) => E0259,
240            (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
241                true => E0254,
242                false => E0260,
243            },
244            _ => match (old_binding.is_import_user_facing(), new_binding.is_import_user_facing()) {
245                (false, false) => E0428,
246                (true, true) => E0252,
247                _ => E0255,
248            },
249        };
250
251        let label = match new_binding.is_import_user_facing() {
252            true => errors::NameDefinedMultipleTimeLabel::Reimported { span },
253            false => errors::NameDefinedMultipleTimeLabel::Redefined { span },
254        };
255
256        let old_binding_label =
257            (!old_binding.span.is_dummy() && old_binding.span != span).then(|| {
258                let span = self.tcx.sess.source_map().guess_head_span(old_binding.span);
259                match old_binding.is_import_user_facing() {
260                    true => {
261                        errors::NameDefinedMultipleTimeOldBindingLabel::Import { span, old_kind }
262                    }
263                    false => errors::NameDefinedMultipleTimeOldBindingLabel::Definition {
264                        span,
265                        old_kind,
266                    },
267                }
268            });
269
270        let mut err = self
271            .dcx()
272            .create_err(errors::NameDefinedMultipleTime {
273                span,
274                name,
275                descr: ns.descr(),
276                container,
277                label,
278                old_binding_label,
279            })
280            .with_code(code);
281
282        // See https://github.com/rust-lang/rust/issues/32354
283        use DeclKind::Import;
284        let can_suggest = |binding: Decl<'_>, import: self::Import<'_>| {
285            !binding.span.is_dummy()
286                && !#[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::MacroUse { .. } | ImportKind::MacroExport => true,
    _ => false,
}matches!(import.kind, ImportKind::MacroUse { .. } | ImportKind::MacroExport)
287        };
288        let import = match (&new_binding.kind, &old_binding.kind) {
289            // If there are two imports where one or both have attributes then prefer removing the
290            // import without attributes.
291            (Import { import: new, .. }, Import { import: old, .. })
292                if {
293                    (new.has_attributes || old.has_attributes)
294                        && can_suggest(old_binding, *old)
295                        && can_suggest(new_binding, *new)
296                } =>
297            {
298                if old.has_attributes {
299                    Some((*new, new_binding.span, true))
300                } else {
301                    Some((*old, old_binding.span, true))
302                }
303            }
304            // Otherwise prioritize the new binding.
305            (Import { import, .. }, other) if can_suggest(new_binding, *import) => {
306                Some((*import, new_binding.span, other.is_import()))
307            }
308            (other, Import { import, .. }) if can_suggest(old_binding, *import) => {
309                Some((*import, old_binding.span, other.is_import()))
310            }
311            _ => None,
312        };
313
314        // Check if the target of the use for both bindings is the same.
315        let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
316        let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
317        let from_item =
318            self.extern_prelude.get(&ident).is_none_or(|entry| entry.introduced_by_item());
319        // Only suggest removing an import if both bindings are to the same def, if both spans
320        // aren't dummy spans. Further, if both bindings are imports, then the ident must have
321        // been introduced by an item.
322        let should_remove_import = duplicate
323            && !has_dummy_span
324            && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
325
326        match import {
327            Some((import, span, true)) if should_remove_import && import.is_nested() => {
328                self.add_suggestion_for_duplicate_nested_use(&mut err, import, span);
329            }
330            Some((import, _, true)) if should_remove_import && !import.is_glob() => {
331                // Simple case - remove the entire import. Due to the above match arm, this can
332                // only be a single use so just remove it entirely.
333                err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport {
334                    span: import.use_span_with_attributes,
335                });
336            }
337            Some((import, span, _)) => {
338                self.add_suggestion_for_rename_of_use(&mut err, name, import, span);
339            }
340            _ => {}
341        }
342
343        err.emit();
344        self.name_already_seen.insert(name, span);
345    }
346
347    /// This function adds a suggestion to change the binding name of a new import that conflicts
348    /// with an existing import.
349    ///
350    /// ```text,ignore (diagnostic)
351    /// help: you can use `as` to change the binding name of the import
352    ///    |
353    /// LL | use foo::bar as other_bar;
354    ///    |     ^^^^^^^^^^^^^^^^^^^^^
355    /// ```
356    fn add_suggestion_for_rename_of_use(
357        &self,
358        err: &mut Diag<'_>,
359        name: Symbol,
360        import: Import<'_>,
361        binding_span: Span,
362    ) {
363        let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
364            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Other{0}", name))
    })format!("Other{name}")
365        } else {
366            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("other_{0}", name))
    })format!("other_{name}")
367        };
368
369        let mut suggestion = None;
370        let mut span = binding_span;
371        match import.kind {
372            ImportKind::Single { type_ns_only: true, .. } => {
373                suggestion = Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("self as {0}", suggested_name))
    })format!("self as {suggested_name}"))
374            }
375            ImportKind::Single { source, .. } => {
376                if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
377                    && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(binding_span)
378                    && pos as usize <= snippet.len()
379                {
380                    span = binding_span.with_lo(binding_span.lo() + BytePos(pos)).with_hi(
381                        binding_span.hi() - BytePos(if snippet.ends_with(';') { 1 } else { 0 }),
382                    );
383                    suggestion = Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" as {0}", suggested_name))
    })format!(" as {suggested_name}"));
384                }
385            }
386            ImportKind::ExternCrate { source, target, .. } => {
387                suggestion = Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("extern crate {0} as {1};",
                source.unwrap_or(target.name), suggested_name))
    })format!(
388                    "extern crate {} as {};",
389                    source.unwrap_or(target.name),
390                    suggested_name,
391                ))
392            }
393            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
394        }
395
396        if let Some(suggestion) = suggestion {
397            err.subdiagnostic(ChangeImportBindingSuggestion { span, suggestion });
398        } else {
399            err.subdiagnostic(ChangeImportBinding { span });
400        }
401    }
402
403    /// This function adds a suggestion to remove an unnecessary binding from an import that is
404    /// nested. In the following example, this function will be invoked to remove the `a` binding
405    /// in the second use statement:
406    ///
407    /// ```ignore (diagnostic)
408    /// use issue_52891::a;
409    /// use issue_52891::{d, a, e};
410    /// ```
411    ///
412    /// The following suggestion will be added:
413    ///
414    /// ```ignore (diagnostic)
415    /// use issue_52891::{d, a, e};
416    ///                      ^-- help: remove unnecessary import
417    /// ```
418    ///
419    /// If the nested use contains only one import then the suggestion will remove the entire
420    /// line.
421    ///
422    /// It is expected that the provided import is nested - this isn't checked by the
423    /// function. If this invariant is not upheld, this function's behaviour will be unexpected
424    /// as characters expected by span manipulations won't be present.
425    fn add_suggestion_for_duplicate_nested_use(
426        &self,
427        err: &mut Diag<'_>,
428        import: Import<'_>,
429        binding_span: Span,
430    ) {
431        if !import.is_nested() {
    ::core::panicking::panic("assertion failed: import.is_nested()")
};assert!(import.is_nested());
432
433        // Two examples will be used to illustrate the span manipulations we're doing:
434        //
435        // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
436        //   `a` and `import.use_span` is `issue_52891::{d, a, e};`.
437        // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
438        //   `a` and `import.use_span` is `issue_52891::{d, e, a};`.
439
440        let (found_closing_brace, span) =
441            find_span_of_binding_until_next_binding(self.tcx.sess, binding_span, import.use_span);
442
443        // If there was a closing brace then identify the span to remove any trailing commas from
444        // previous imports.
445        if found_closing_brace {
446            if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) {
447                err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport { span });
448            } else {
449                // Remove the entire line if we cannot extend the span back, this indicates an
450                // `issue_52891::{self}` case.
451                err.subdiagnostic(errors::RemoveUnnecessaryImport {
452                    span: import.use_span_with_attributes,
453                });
454            }
455
456            return;
457        }
458
459        err.subdiagnostic(errors::RemoveUnnecessaryImport { span });
460    }
461
462    pub(crate) fn lint_if_path_starts_with_module(
463        &mut self,
464        finalize: Finalize,
465        path: &[Segment],
466        second_binding: Option<Decl<'_>>,
467    ) {
468        let Finalize { node_id, root_span, .. } = finalize;
469
470        let first_name = match path.get(0) {
471            // In the 2018 edition this lint is a hard error, so nothing to do
472            Some(seg) if seg.ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015() => {
473                seg.ident.name
474            }
475            _ => return,
476        };
477
478        // We're only interested in `use` paths which should start with
479        // `{{root}}` currently.
480        if first_name != kw::PathRoot {
481            return;
482        }
483
484        match path.get(1) {
485            // If this import looks like `crate::...` it's already good
486            Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
487            // Otherwise go below to see if it's an extern crate
488            Some(_) => {}
489            // If the path has length one (and it's `PathRoot` most likely)
490            // then we don't know whether we're gonna be importing a crate or an
491            // item in our crate. Defer this lint to elsewhere
492            None => return,
493        }
494
495        // If the first element of our path was actually resolved to an
496        // `ExternCrate` (also used for `crate::...`) then no need to issue a
497        // warning, this looks all good!
498        if let Some(binding) = second_binding
499            && let DeclKind::Import { import, .. } = binding.kind
500            // Careful: we still want to rewrite paths from renamed extern crates.
501            && let ImportKind::ExternCrate { source: None, .. } = import.kind
502        {
503            return;
504        }
505
506        let diag = BuiltinLintDiag::AbsPathWithModule(root_span);
507        self.lint_buffer.buffer_lint(
508            ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
509            node_id,
510            root_span,
511            diag,
512        );
513    }
514
515    pub(crate) fn add_module_candidates(
516        &self,
517        module: Module<'ra>,
518        names: &mut Vec<TypoSuggestion>,
519        filter_fn: &impl Fn(Res) -> bool,
520        ctxt: Option<SyntaxContext>,
521    ) {
522        module.for_each_child(self, |_this, ident, orig_ident_span, _ns, binding| {
523            let res = binding.res();
524            if filter_fn(res) && ctxt.is_none_or(|ctxt| ctxt == *ident.ctxt) {
525                names.push(TypoSuggestion::new(ident.name, orig_ident_span, res));
526            }
527        });
528    }
529
530    /// Combines an error with provided span and emits it.
531    ///
532    /// This takes the error provided, combines it with the span and any additional spans inside the
533    /// error and emits it.
534    pub(crate) fn report_error(
535        &mut self,
536        span: Span,
537        resolution_error: ResolutionError<'ra>,
538    ) -> ErrorGuaranteed {
539        self.into_struct_error(span, resolution_error).emit()
540    }
541
542    pub(crate) fn into_struct_error(
543        &mut self,
544        span: Span,
545        resolution_error: ResolutionError<'ra>,
546    ) -> Diag<'_> {
547        match resolution_error {
548            ResolutionError::GenericParamsFromOuterItem {
549                outer_res,
550                has_generic_params,
551                def_kind,
552                inner_item,
553                current_self_ty,
554            } => {
555                use errs::GenericParamsFromOuterItemLabel as Label;
556                let static_or_const = match def_kind {
557                    DefKind::Static { .. } => {
558                        Some(errs::GenericParamsFromOuterItemStaticOrConst::Static)
559                    }
560                    DefKind::Const => Some(errs::GenericParamsFromOuterItemStaticOrConst::Const),
561                    _ => None,
562                };
563                let is_self =
564                    #[allow(non_exhaustive_omitted_patterns)] match outer_res {
    Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => true,
    _ => false,
}matches!(outer_res, Res::SelfTyParam { .. } | Res::SelfTyAlias { .. });
565                let mut err = errs::GenericParamsFromOuterItem {
566                    span,
567                    label: None,
568                    refer_to_type_directly: None,
569                    sugg: None,
570                    static_or_const,
571                    is_self,
572                    item: inner_item.as_ref().map(|(span, kind)| {
573                        errs::GenericParamsFromOuterItemInnerItem {
574                            span: *span,
575                            descr: kind.descr().to_string(),
576                        }
577                    }),
578                };
579
580                let sm = self.tcx.sess.source_map();
581                let def_id = match outer_res {
582                    Res::SelfTyParam { .. } => {
583                        err.label = Some(Label::SelfTyParam(span));
584                        return self.dcx().create_err(err);
585                    }
586                    Res::SelfTyAlias { alias_to: def_id, .. } => {
587                        err.label = Some(Label::SelfTyAlias(reduce_impl_span_to_impl_keyword(
588                            sm,
589                            self.def_span(def_id),
590                        )));
591                        err.refer_to_type_directly =
592                            current_self_ty.map(|snippet| errs::UseTypeDirectly { span, snippet });
593                        return self.dcx().create_err(err);
594                    }
595                    Res::Def(DefKind::TyParam, def_id) => {
596                        err.label = Some(Label::TyParam(self.def_span(def_id)));
597                        def_id
598                    }
599                    Res::Def(DefKind::ConstParam, def_id) => {
600                        err.label = Some(Label::ConstParam(self.def_span(def_id)));
601                        def_id
602                    }
603                    _ => {
604                        ::rustc_middle::util::bug::bug_fmt(format_args!("GenericParamsFromOuterItem should only be used with Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or DefKind::ConstParam"));bug!(
605                            "GenericParamsFromOuterItem should only be used with \
606                            Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
607                            DefKind::ConstParam"
608                        );
609                    }
610                };
611
612                if let HasGenericParams::Yes(span) = has_generic_params
613                    && !#[allow(non_exhaustive_omitted_patterns)] match inner_item {
    Some((_, ItemKind::Delegation(..))) => true,
    _ => false,
}matches!(inner_item, Some((_, ItemKind::Delegation(..))))
614                {
615                    let name = self.tcx.item_name(def_id);
616                    let (span, snippet) = if span.is_empty() {
617                        let snippet = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", name))
    })format!("<{name}>");
618                        (span, snippet)
619                    } else {
620                        let span = sm.span_through_char(span, '<').shrink_to_hi();
621                        let snippet = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, ", name))
    })format!("{name}, ");
622                        (span, snippet)
623                    };
624                    err.sugg = Some(errs::GenericParamsFromOuterItemSugg { span, snippet });
625                }
626
627                self.dcx().create_err(err)
628            }
629            ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
630                .dcx()
631                .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
632            ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
633                self.dcx().create_err(errs::MethodNotMemberOfTrait {
634                    span,
635                    method,
636                    trait_,
637                    sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
638                        span: method.span,
639                        candidate: c,
640                    }),
641                })
642            }
643            ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
644                self.dcx().create_err(errs::TypeNotMemberOfTrait {
645                    span,
646                    type_,
647                    trait_,
648                    sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
649                        span: type_.span,
650                        candidate: c,
651                    }),
652                })
653            }
654            ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
655                self.dcx().create_err(errs::ConstNotMemberOfTrait {
656                    span,
657                    const_,
658                    trait_,
659                    sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
660                        span: const_.span,
661                        candidate: c,
662                    }),
663                })
664            }
665            ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
666                let BindingError { name, target, origin, could_be_path } = binding_error;
667
668                let mut target_sp = target.iter().map(|pat| pat.span).collect::<Vec<_>>();
669                target_sp.sort();
670                target_sp.dedup();
671                let mut origin_sp = origin.iter().map(|(span, _)| *span).collect::<Vec<_>>();
672                origin_sp.sort();
673                origin_sp.dedup();
674
675                let msp = MultiSpan::from_spans(target_sp.clone());
676                let mut err = self
677                    .dcx()
678                    .create_err(errors::VariableIsNotBoundInAllPatterns { multispan: msp, name });
679                for sp in target_sp {
680                    err.subdiagnostic(errors::PatternDoesntBindName { span: sp, name });
681                }
682                for sp in &origin_sp {
683                    err.subdiagnostic(errors::VariableNotInAllPatterns { span: *sp });
684                }
685                let mut suggested_typo = false;
686                if !target.iter().all(|pat| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
    ast::PatKind::Ident(..) => true,
    _ => false,
}matches!(pat.kind, ast::PatKind::Ident(..)))
687                    && !origin.iter().all(|(_, pat)| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
    ast::PatKind::Ident(..) => true,
    _ => false,
}matches!(pat.kind, ast::PatKind::Ident(..)))
688                {
689                    // The check above is so that when we encounter `match foo { (a | b) => {} }`,
690                    // we don't suggest `(a | a) => {}`, which would never be what the user wants.
691                    let mut target_visitor = BindingVisitor::default();
692                    for pat in &target {
693                        target_visitor.visit_pat(pat);
694                    }
695                    target_visitor.identifiers.sort();
696                    target_visitor.identifiers.dedup();
697                    let mut origin_visitor = BindingVisitor::default();
698                    for (_, pat) in &origin {
699                        origin_visitor.visit_pat(pat);
700                    }
701                    origin_visitor.identifiers.sort();
702                    origin_visitor.identifiers.dedup();
703                    // Find if the binding could have been a typo
704                    if let Some(typo) =
705                        find_best_match_for_name(&target_visitor.identifiers, name.name, None)
706                        && !origin_visitor.identifiers.contains(&typo)
707                    {
708                        err.subdiagnostic(errors::PatternBindingTypo { spans: origin_sp, typo });
709                        suggested_typo = true;
710                    }
711                }
712                if could_be_path {
713                    let import_suggestions = self.lookup_import_candidates(
714                        name,
715                        Namespace::ValueNS,
716                        &parent_scope,
717                        &|res: Res| {
718                            #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Const) |
        DefKind::Ctor(CtorOf::Struct, CtorKind::Const) | DefKind::Const |
        DefKind::AssocConst, _) => true,
    _ => false,
}matches!(
719                                res,
720                                Res::Def(
721                                    DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
722                                        | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
723                                        | DefKind::Const
724                                        | DefKind::AssocConst,
725                                    _,
726                                )
727                            )
728                        },
729                    );
730
731                    if import_suggestions.is_empty() && !suggested_typo {
732                        let kinds = [
733                            DefKind::Ctor(CtorOf::Variant, CtorKind::Const),
734                            DefKind::Ctor(CtorOf::Struct, CtorKind::Const),
735                            DefKind::Const,
736                            DefKind::AssocConst,
737                        ];
738                        let mut local_names = ::alloc::vec::Vec::new()vec![];
739                        self.add_module_candidates(
740                            parent_scope.module,
741                            &mut local_names,
742                            &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(_, _) => true,
    _ => false,
}matches!(res, Res::Def(_, _)),
743                            None,
744                        );
745                        let local_names: FxHashSet<_> = local_names
746                            .into_iter()
747                            .filter_map(|s| match s.res {
748                                Res::Def(_, def_id) => Some(def_id),
749                                _ => None,
750                            })
751                            .collect();
752
753                        let mut local_suggestions = ::alloc::vec::Vec::new()vec![];
754                        let mut suggestions = ::alloc::vec::Vec::new()vec![];
755                        for kind in kinds {
756                            if let Some(suggestion) = self.early_lookup_typo_candidate(
757                                ScopeSet::All(Namespace::ValueNS),
758                                &parent_scope,
759                                name,
760                                &|res: Res| match res {
761                                    Res::Def(k, _) => k == kind,
762                                    _ => false,
763                                },
764                            ) && let Res::Def(kind, mut def_id) = suggestion.res
765                            {
766                                if let DefKind::Ctor(_, _) = kind {
767                                    def_id = self.tcx.parent(def_id);
768                                }
769                                let kind = kind.descr(def_id);
770                                if local_names.contains(&def_id) {
771                                    // The item is available in the current scope. Very likely to
772                                    // be a typo. Don't use the full path.
773                                    local_suggestions.push((
774                                        suggestion.candidate,
775                                        suggestion.candidate.to_string(),
776                                        kind,
777                                    ));
778                                } else {
779                                    suggestions.push((
780                                        suggestion.candidate,
781                                        self.def_path_str(def_id),
782                                        kind,
783                                    ));
784                                }
785                            }
786                        }
787                        let suggestions = if !local_suggestions.is_empty() {
788                            // There is at least one item available in the current scope that is a
789                            // likely typo. We only show those.
790                            local_suggestions
791                        } else {
792                            suggestions
793                        };
794                        for (name, sugg, kind) in suggestions {
795                            err.span_suggestion_verbose(
796                                span,
797                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant to use the similarly named {0} `{1}`",
                kind, name))
    })format!(
798                                    "you might have meant to use the similarly named {kind} `{name}`",
799                                ),
800                                sugg,
801                                Applicability::MaybeIncorrect,
802                            );
803                            suggested_typo = true;
804                        }
805                    }
806                    if import_suggestions.is_empty() && !suggested_typo {
807                        let help_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you meant to match on a unit struct, unit variant or a `const` item, consider making the path in the pattern qualified: `path::to::ModOrType::{0}`",
                name))
    })format!(
808                            "if you meant to match on a unit struct, unit variant or a `const` \
809                             item, consider making the path in the pattern qualified: \
810                             `path::to::ModOrType::{name}`",
811                        );
812                        err.span_help(span, help_msg);
813                    }
814                    show_candidates(
815                        self.tcx,
816                        &mut err,
817                        Some(span),
818                        &import_suggestions,
819                        Instead::No,
820                        FoundUse::Yes,
821                        DiagMode::Pattern,
822                        ::alloc::vec::Vec::new()vec![],
823                        "",
824                    );
825                }
826                err
827            }
828            ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
829                self.dcx().create_err(errs::VariableBoundWithDifferentMode {
830                    span,
831                    first_binding_span,
832                    variable_name,
833                })
834            }
835            ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
836                .dcx()
837                .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
838            ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
839                .dcx()
840                .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
841            ResolutionError::UndeclaredLabel { name, suggestion } => {
842                let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
843                {
844                    // A reachable label with a similar name exists.
845                    Some((ident, true)) => (
846                        (
847                            Some(errs::LabelWithSimilarNameReachable(ident.span)),
848                            Some(errs::TryUsingSimilarlyNamedLabel {
849                                span,
850                                ident_name: ident.name,
851                            }),
852                        ),
853                        None,
854                    ),
855                    // An unreachable label with a similar name exists.
856                    Some((ident, false)) => (
857                        (None, None),
858                        Some(errs::UnreachableLabelWithSimilarNameExists {
859                            ident_span: ident.span,
860                        }),
861                    ),
862                    // No similarly-named labels exist.
863                    None => ((None, None), None),
864                };
865                self.dcx().create_err(errs::UndeclaredLabel {
866                    span,
867                    name,
868                    sub_reachable,
869                    sub_reachable_suggestion,
870                    sub_unreachable,
871                })
872            }
873            ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
874                // None of the suggestions below would help with a case like `use self`.
875                let (suggestion, mpart_suggestion) = if root {
876                    (None, None)
877                } else {
878                    // use foo::bar::self        -> foo::bar
879                    // use foo::bar::self as abc -> foo::bar as abc
880                    let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
881
882                    // use foo::bar::self        -> foo::bar::{self}
883                    // use foo::bar::self as abc -> foo::bar::{self as abc}
884                    let mpart_suggestion = errs::SelfImportsOnlyAllowedWithinMultipartSuggestion {
885                        multipart_start: span_with_rename.shrink_to_lo(),
886                        multipart_end: span_with_rename.shrink_to_hi(),
887                    };
888                    (Some(suggestion), Some(mpart_suggestion))
889                };
890                self.dcx().create_err(errs::SelfImportsOnlyAllowedWithin {
891                    span,
892                    suggestion,
893                    mpart_suggestion,
894                })
895            }
896            ResolutionError::FailedToResolve { segment, label, suggestion, module, message } => {
897                let mut err = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0}", message))
                })).with_code(E0433)
}struct_span_code_err!(self.dcx(), span, E0433, "{message}");
898                err.span_label(span, label);
899
900                if let Some((suggestions, msg, applicability)) = suggestion {
901                    if suggestions.is_empty() {
902                        err.help(msg);
903                        return err;
904                    }
905                    err.multipart_suggestion(msg, suggestions, applicability);
906                }
907
908                let module = match module {
909                    Some(ModuleOrUniformRoot::Module(m)) if let Some(id) = m.opt_def_id() => id,
910                    _ => CRATE_DEF_ID.to_def_id(),
911                };
912                self.find_cfg_stripped(&mut err, &segment, module);
913
914                err
915            }
916            ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
917                self.dcx().create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
918            }
919            ResolutionError::AttemptToUseNonConstantValueInConstant {
920                ident,
921                suggestion,
922                current,
923                type_span,
924            } => {
925                // let foo =...
926                //     ^^^ given this Span
927                // ------- get this Span to have an applicable suggestion
928
929                // edit:
930                // only do this if the const and usage of the non-constant value are on the same line
931                // the further the two are apart, the higher the chance of the suggestion being wrong
932
933                let sp = self
934                    .tcx
935                    .sess
936                    .source_map()
937                    .span_extend_to_prev_str(ident.span, current, true, false);
938
939                let ((with, with_label), without) = match sp {
940                    Some(sp) if !self.tcx.sess.source_map().is_multiline(sp) => {
941                        let sp = sp
942                            .with_lo(BytePos(sp.lo().0 - (current.len() as u32)))
943                            .until(ident.span);
944                        (
945                        (Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
946                                span: sp,
947                                suggestion,
948                                current,
949                                type_span,
950                            }), Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion {span})),
951                            None,
952                        )
953                    }
954                    _ => (
955                        (None, None),
956                        Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
957                            ident_span: ident.span,
958                            suggestion,
959                        }),
960                    ),
961                };
962
963                self.dcx().create_err(errs::AttemptToUseNonConstantValueInConstant {
964                    span,
965                    with,
966                    with_label,
967                    without,
968                })
969            }
970            ResolutionError::BindingShadowsSomethingUnacceptable {
971                shadowing_binding,
972                name,
973                participle,
974                article,
975                shadowed_binding,
976                shadowed_binding_span,
977            } => self.dcx().create_err(errs::BindingShadowsSomethingUnacceptable {
978                span,
979                shadowing_binding,
980                shadowed_binding,
981                article,
982                sub_suggestion: match (shadowing_binding, shadowed_binding) {
983                    (
984                        PatternSource::Match,
985                        Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
986                    ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
987                    _ => None,
988                },
989                shadowed_binding_span,
990                participle,
991                name,
992            }),
993            ResolutionError::ForwardDeclaredGenericParam(param, reason) => match reason {
994                ForwardGenericParamBanReason::Default => {
995                    self.dcx().create_err(errs::ForwardDeclaredGenericParam { param, span })
996                }
997                ForwardGenericParamBanReason::ConstParamTy => self
998                    .dcx()
999                    .create_err(errs::ForwardDeclaredGenericInConstParamTy { param, span }),
1000            },
1001            ResolutionError::ParamInTyOfConstParam { name } => {
1002                self.dcx().create_err(errs::ParamInTyOfConstParam { span, name })
1003            }
1004            ResolutionError::ParamInNonTrivialAnonConst { is_ogca, name, param_kind: is_type } => {
1005                self.dcx().create_err(errs::ParamInNonTrivialAnonConst {
1006                    span,
1007                    name,
1008                    param_kind: is_type,
1009                    help: self.tcx.sess.is_nightly_build(),
1010                    is_ogca,
1011                    help_ogca: is_ogca,
1012                })
1013            }
1014            ResolutionError::ParamInEnumDiscriminant { name, param_kind: is_type } => self
1015                .dcx()
1016                .create_err(errs::ParamInEnumDiscriminant { span, name, param_kind: is_type }),
1017            ResolutionError::ForwardDeclaredSelf(reason) => match reason {
1018                ForwardGenericParamBanReason::Default => {
1019                    self.dcx().create_err(errs::SelfInGenericParamDefault { span })
1020                }
1021                ForwardGenericParamBanReason::ConstParamTy => {
1022                    self.dcx().create_err(errs::SelfInConstGenericTy { span })
1023                }
1024            },
1025            ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
1026                let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
1027                    match suggestion {
1028                        // A reachable label with a similar name exists.
1029                        Some((ident, true)) => (
1030                            (
1031                                Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
1032                                Some(errs::UnreachableLabelSubSuggestion {
1033                                    span,
1034                                    // intentionally taking 'ident.name' instead of 'ident' itself, as this
1035                                    // could be used in suggestion context
1036                                    ident_name: ident.name,
1037                                }),
1038                            ),
1039                            None,
1040                        ),
1041                        // An unreachable label with a similar name exists.
1042                        Some((ident, false)) => (
1043                            (None, None),
1044                            Some(errs::UnreachableLabelSubLabelUnreachable {
1045                                ident_span: ident.span,
1046                            }),
1047                        ),
1048                        // No similarly-named labels exist.
1049                        None => ((None, None), None),
1050                    };
1051                self.dcx().create_err(errs::UnreachableLabel {
1052                    span,
1053                    name,
1054                    definition_span,
1055                    sub_suggestion,
1056                    sub_suggestion_label,
1057                    sub_unreachable_label,
1058                })
1059            }
1060            ResolutionError::TraitImplMismatch {
1061                name,
1062                kind,
1063                code,
1064                trait_item_span,
1065                trait_path,
1066            } => self
1067                .dcx()
1068                .create_err(errors::TraitImplMismatch {
1069                    span,
1070                    name,
1071                    kind,
1072                    trait_path,
1073                    trait_item_span,
1074                })
1075                .with_code(code),
1076            ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
1077                .dcx()
1078                .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
1079            ResolutionError::InvalidAsmSym => self.dcx().create_err(errs::InvalidAsmSym { span }),
1080            ResolutionError::LowercaseSelf => self.dcx().create_err(errs::LowercaseSelf { span }),
1081            ResolutionError::BindingInNeverPattern => {
1082                self.dcx().create_err(errs::BindingInNeverPattern { span })
1083            }
1084        }
1085    }
1086
1087    pub(crate) fn report_vis_error(
1088        &mut self,
1089        vis_resolution_error: VisResolutionError<'_>,
1090    ) -> ErrorGuaranteed {
1091        match vis_resolution_error {
1092            VisResolutionError::Relative2018(span, path) => {
1093                self.dcx().create_err(errs::Relative2018 {
1094                    span,
1095                    path_span: path.span,
1096                    // intentionally converting to String, as the text would also be used as
1097                    // in suggestion context
1098                    path_str: pprust::path_to_string(path),
1099                })
1100            }
1101            VisResolutionError::AncestorOnly(span) => {
1102                self.dcx().create_err(errs::AncestorOnly(span))
1103            }
1104            VisResolutionError::FailedToResolve(span, segment, label, suggestion, message) => self
1105                .into_struct_error(
1106                    span,
1107                    ResolutionError::FailedToResolve {
1108                        segment,
1109                        label,
1110                        suggestion,
1111                        module: None,
1112                        message,
1113                    },
1114                ),
1115            VisResolutionError::ExpectedFound(span, path_str, res) => {
1116                self.dcx().create_err(errs::ExpectedModuleFound { span, res, path_str })
1117            }
1118            VisResolutionError::Indeterminate(span) => {
1119                self.dcx().create_err(errs::Indeterminate(span))
1120            }
1121            VisResolutionError::ModuleOnly(span) => self.dcx().create_err(errs::ModuleOnly(span)),
1122        }
1123        .emit()
1124    }
1125
1126    fn def_path_str(&self, mut def_id: DefId) -> String {
1127        // We can't use `def_path_str` in resolve.
1128        let mut path = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [def_id]))vec![def_id];
1129        while let Some(parent) = self.tcx.opt_parent(def_id) {
1130            def_id = parent;
1131            path.push(def_id);
1132            if def_id.is_top_level_module() {
1133                break;
1134            }
1135        }
1136        // We will only suggest importing directly if it is accessible through that path.
1137        path.into_iter()
1138            .rev()
1139            .map(|def_id| {
1140                self.tcx
1141                    .opt_item_name(def_id)
1142                    .map(|name| {
1143                        match (
1144                            def_id.is_top_level_module(),
1145                            def_id.is_local(),
1146                            self.tcx.sess.edition(),
1147                        ) {
1148                            (true, true, Edition::Edition2015) => String::new(),
1149                            (true, true, _) => kw::Crate.to_string(),
1150                            (true, false, _) | (false, _, _) => name.to_string(),
1151                        }
1152                    })
1153                    .unwrap_or_else(|| "_".to_string())
1154            })
1155            .collect::<Vec<String>>()
1156            .join("::")
1157    }
1158
1159    pub(crate) fn add_scope_set_candidates(
1160        &mut self,
1161        suggestions: &mut Vec<TypoSuggestion>,
1162        scope_set: ScopeSet<'ra>,
1163        ps: &ParentScope<'ra>,
1164        sp: Span,
1165        filter_fn: &impl Fn(Res) -> bool,
1166    ) {
1167        let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
1168        self.cm().visit_scopes(scope_set, ps, ctxt, sp, None, |this, scope, use_prelude, _| {
1169            match scope {
1170                Scope::DeriveHelpers(expn_id) => {
1171                    let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1172                    if filter_fn(res) {
1173                        suggestions.extend(
1174                            this.helper_attrs.get(&expn_id).into_iter().flatten().map(
1175                                |&(ident, orig_ident_span, _)| {
1176                                    TypoSuggestion::new(ident.name, orig_ident_span, res)
1177                                },
1178                            ),
1179                        );
1180                    }
1181                }
1182                Scope::DeriveHelpersCompat => {
1183                    // Never recommend deprecated helper attributes.
1184                }
1185                Scope::MacroRules(macro_rules_scope) => {
1186                    if let MacroRulesScope::Def(macro_rules_def) = macro_rules_scope.get() {
1187                        let res = macro_rules_def.decl.res();
1188                        if filter_fn(res) {
1189                            suggestions.push(TypoSuggestion::new(
1190                                macro_rules_def.ident.name,
1191                                macro_rules_def.orig_ident_span,
1192                                res,
1193                            ))
1194                        }
1195                    }
1196                }
1197                Scope::ModuleNonGlobs(module, _) => {
1198                    this.add_module_candidates(module, suggestions, filter_fn, None);
1199                }
1200                Scope::ModuleGlobs(..) => {
1201                    // Already handled in `ModuleNonGlobs`.
1202                }
1203                Scope::MacroUsePrelude => {
1204                    suggestions.extend(this.macro_use_prelude.iter().filter_map(
1205                        |(name, binding)| {
1206                            let res = binding.res();
1207                            filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1208                        },
1209                    ));
1210                }
1211                Scope::BuiltinAttrs => {
1212                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(sym::dummy));
1213                    if filter_fn(res) {
1214                        suggestions.extend(
1215                            BUILTIN_ATTRIBUTES
1216                                .iter()
1217                                .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1218                        );
1219                    }
1220                }
1221                Scope::ExternPreludeItems => {
1222                    // Add idents from both item and flag scopes.
1223                    suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, entry)| {
1224                        let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1225                        filter_fn(res).then_some(TypoSuggestion::new(ident.name, entry.span(), res))
1226                    }));
1227                }
1228                Scope::ExternPreludeFlags => {}
1229                Scope::ToolPrelude => {
1230                    let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1231                    suggestions.extend(
1232                        this.registered_tools
1233                            .iter()
1234                            .map(|ident| TypoSuggestion::new(ident.name, ident.span, res)),
1235                    );
1236                }
1237                Scope::StdLibPrelude => {
1238                    if let Some(prelude) = this.prelude {
1239                        let mut tmp_suggestions = Vec::new();
1240                        this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1241                        suggestions.extend(
1242                            tmp_suggestions
1243                                .into_iter()
1244                                .filter(|s| use_prelude.into() || this.is_builtin_macro(s.res)),
1245                        );
1246                    }
1247                }
1248                Scope::BuiltinTypes => {
1249                    suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1250                        let res = Res::PrimTy(*prim_ty);
1251                        filter_fn(res)
1252                            .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1253                    }))
1254                }
1255            }
1256
1257            ControlFlow::<()>::Continue(())
1258        });
1259    }
1260
1261    /// Lookup typo candidate in scope for a macro or import.
1262    fn early_lookup_typo_candidate(
1263        &mut self,
1264        scope_set: ScopeSet<'ra>,
1265        parent_scope: &ParentScope<'ra>,
1266        ident: Ident,
1267        filter_fn: &impl Fn(Res) -> bool,
1268    ) -> Option<TypoSuggestion> {
1269        let mut suggestions = Vec::new();
1270        self.add_scope_set_candidates(
1271            &mut suggestions,
1272            scope_set,
1273            parent_scope,
1274            ident.span,
1275            filter_fn,
1276        );
1277
1278        // Make sure error reporting is deterministic.
1279        suggestions.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
1280
1281        match find_best_match_for_name(
1282            &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1283            ident.name,
1284            None,
1285        ) {
1286            Some(found) if found != ident.name => {
1287                suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1288            }
1289            _ => None,
1290        }
1291    }
1292
1293    fn lookup_import_candidates_from_module<FilterFn>(
1294        &self,
1295        lookup_ident: Ident,
1296        namespace: Namespace,
1297        parent_scope: &ParentScope<'ra>,
1298        start_module: Module<'ra>,
1299        crate_path: ThinVec<ast::PathSegment>,
1300        filter_fn: FilterFn,
1301    ) -> Vec<ImportSuggestion>
1302    where
1303        FilterFn: Fn(Res) -> bool,
1304    {
1305        let mut candidates = Vec::new();
1306        let mut seen_modules = FxHashSet::default();
1307        let start_did = start_module.def_id();
1308        let mut worklist = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(start_module, ThinVec::<ast::PathSegment>::new(), true,
                    start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
                    true)]))vec![(
1309            start_module,
1310            ThinVec::<ast::PathSegment>::new(),
1311            true,
1312            start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
1313            true,
1314        )];
1315        let mut worklist_via_import = ::alloc::vec::Vec::new()vec![];
1316
1317        while let Some((in_module, path_segments, accessible, doc_visible, is_stable)) =
1318            match worklist.pop() {
1319                None => worklist_via_import.pop(),
1320                Some(x) => Some(x),
1321            }
1322        {
1323            let in_module_is_extern = !in_module.def_id().is_local();
1324            in_module.for_each_child(self, |this, ident, orig_ident_span, ns, name_binding| {
1325                // Avoid non-importable candidates.
1326                if name_binding.is_assoc_item()
1327                    && !this.tcx.features().import_trait_associated_functions()
1328                {
1329                    return;
1330                }
1331
1332                if ident.name == kw::Underscore {
1333                    return;
1334                }
1335
1336                let child_accessible =
1337                    accessible && this.is_accessible_from(name_binding.vis(), parent_scope.module);
1338
1339                // do not venture inside inaccessible items of other crates
1340                if in_module_is_extern && !child_accessible {
1341                    return;
1342                }
1343
1344                let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1345
1346                // There is an assumption elsewhere that paths of variants are in the enum's
1347                // declaration and not imported. With this assumption, the variant component is
1348                // chopped and the rest of the path is assumed to be the enum's own path. For
1349                // errors where a variant is used as the type instead of the enum, this causes
1350                // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1351                if via_import && name_binding.is_possibly_imported_variant() {
1352                    return;
1353                }
1354
1355                // #90113: Do not count an inaccessible reexported item as a candidate.
1356                if let DeclKind::Import { source_decl, .. } = name_binding.kind
1357                    && this.is_accessible_from(source_decl.vis(), parent_scope.module)
1358                    && !this.is_accessible_from(name_binding.vis(), parent_scope.module)
1359                {
1360                    return;
1361                }
1362
1363                let res = name_binding.res();
1364                let did = match res {
1365                    Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1366                    _ => res.opt_def_id(),
1367                };
1368                let child_doc_visible = doc_visible
1369                    && did.is_none_or(|did| did.is_local() || !this.tcx.is_doc_hidden(did));
1370
1371                // collect results based on the filter function
1372                // avoid suggesting anything from the same module in which we are resolving
1373                // avoid suggesting anything with a hygienic name
1374                if ident.name == lookup_ident.name
1375                    && ns == namespace
1376                    && in_module != parent_scope.module
1377                    && ident.ctxt.is_root()
1378                    && filter_fn(res)
1379                {
1380                    // create the path
1381                    let mut segms = if lookup_ident.span.at_least_rust_2018() {
1382                        // crate-local absolute paths start with `crate::` in edition 2018
1383                        // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1384                        crate_path.clone()
1385                    } else {
1386                        ThinVec::new()
1387                    };
1388                    segms.append(&mut path_segments.clone());
1389
1390                    segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
1391                    let path = Path { span: name_binding.span, segments: segms, tokens: None };
1392
1393                    if child_accessible
1394                        // Remove invisible match if exists
1395                        && let Some(idx) = candidates
1396                            .iter()
1397                            .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1398                    {
1399                        candidates.remove(idx);
1400                    }
1401
1402                    let is_stable = if is_stable
1403                        && let Some(did) = did
1404                        && this.is_stable(did, path.span)
1405                    {
1406                        true
1407                    } else {
1408                        false
1409                    };
1410
1411                    // Rreplace unstable suggestions if we meet a new stable one,
1412                    // and do nothing if any other situation. For example, if we
1413                    // meet `std::ops::Range` after `std::range::legacy::Range`,
1414                    // we will remove the latter and then insert the former.
1415                    if is_stable
1416                        && let Some(idx) = candidates
1417                            .iter()
1418                            .position(|v: &ImportSuggestion| v.did == did && !v.is_stable)
1419                    {
1420                        candidates.remove(idx);
1421                    }
1422
1423                    if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1424                        // See if we're recommending TryFrom, TryInto, or FromIterator and add
1425                        // a note about editions
1426                        let note = if let Some(did) = did {
1427                            let requires_note = !did.is_local()
1428                                && {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in this.tcx.get_all_attrs(did) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(RustcDiagnosticItem(sym::TryInto
                                | sym::TryFrom | sym::FromIterator)) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(
1429                                    this.tcx,
1430                                    did,
1431                                    RustcDiagnosticItem(
1432                                        sym::TryInto | sym::TryFrom | sym::FromIterator
1433                                    )
1434                                );
1435                            requires_note.then(|| {
1436                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}\' is included in the prelude starting in Edition 2021",
                path_names_to_string(&path)))
    })format!(
1437                                    "'{}' is included in the prelude starting in Edition 2021",
1438                                    path_names_to_string(&path)
1439                                )
1440                            })
1441                        } else {
1442                            None
1443                        };
1444
1445                        candidates.push(ImportSuggestion {
1446                            did,
1447                            descr: res.descr(),
1448                            path,
1449                            accessible: child_accessible,
1450                            doc_visible: child_doc_visible,
1451                            note,
1452                            via_import,
1453                            is_stable,
1454                        });
1455                    }
1456                }
1457
1458                // collect submodules to explore
1459                if let Some(def_id) = name_binding.res().module_like_def_id() {
1460                    // form the path
1461                    let mut path_segments = path_segments.clone();
1462                    path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
1463
1464                    let alias_import = if let DeclKind::Import { import, .. } = name_binding.kind
1465                        && let ImportKind::ExternCrate { source: Some(_), .. } = import.kind
1466                        && import.parent_scope.expansion == parent_scope.expansion
1467                    {
1468                        true
1469                    } else {
1470                        false
1471                    };
1472
1473                    let is_extern_crate_that_also_appears_in_prelude =
1474                        name_binding.is_extern_crate() && lookup_ident.span.at_least_rust_2018();
1475
1476                    if !is_extern_crate_that_also_appears_in_prelude || alias_import {
1477                        // add the module to the lookup
1478                        if seen_modules.insert(def_id) {
1479                            if via_import { &mut worklist_via_import } else { &mut worklist }.push(
1480                                (
1481                                    this.expect_module(def_id),
1482                                    path_segments,
1483                                    child_accessible,
1484                                    child_doc_visible,
1485                                    is_stable && this.is_stable(def_id, name_binding.span),
1486                                ),
1487                            );
1488                        }
1489                    }
1490                }
1491            })
1492        }
1493
1494        candidates
1495    }
1496
1497    fn is_stable(&self, did: DefId, span: Span) -> bool {
1498        if did.is_local() {
1499            return true;
1500        }
1501
1502        match self.tcx.lookup_stability(did) {
1503            Some(Stability {
1504                level: StabilityLevel::Unstable { implied_by, .. }, feature, ..
1505            }) => {
1506                if span.allows_unstable(feature) {
1507                    true
1508                } else if self.tcx.features().enabled(feature) {
1509                    true
1510                } else if let Some(implied_by) = implied_by
1511                    && self.tcx.features().enabled(implied_by)
1512                {
1513                    true
1514                } else {
1515                    false
1516                }
1517            }
1518            Some(_) => true,
1519            None => false,
1520        }
1521    }
1522
1523    /// When name resolution fails, this method can be used to look up candidate
1524    /// entities with the expected name. It allows filtering them using the
1525    /// supplied predicate (which should be used to only accept the types of
1526    /// definitions expected, e.g., traits). The lookup spans across all crates.
1527    ///
1528    /// N.B., the method does not look into imports, but this is not a problem,
1529    /// since we report the definitions (thus, the de-aliased imports).
1530    pub(crate) fn lookup_import_candidates<FilterFn>(
1531        &mut self,
1532        lookup_ident: Ident,
1533        namespace: Namespace,
1534        parent_scope: &ParentScope<'ra>,
1535        filter_fn: FilterFn,
1536    ) -> Vec<ImportSuggestion>
1537    where
1538        FilterFn: Fn(Res) -> bool,
1539    {
1540        let crate_path = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(ast::PathSegment::from_ident(Ident::with_dummy_span(kw::Crate)));
    vec
}thin_vec![ast::PathSegment::from_ident(Ident::with_dummy_span(kw::Crate))];
1541        let mut suggestions = self.lookup_import_candidates_from_module(
1542            lookup_ident,
1543            namespace,
1544            parent_scope,
1545            self.graph_root,
1546            crate_path,
1547            &filter_fn,
1548        );
1549
1550        if lookup_ident.span.at_least_rust_2018() {
1551            for (ident, entry) in &self.extern_prelude {
1552                if entry.span().from_expansion() {
1553                    // Idents are adjusted to the root context before being
1554                    // resolved in the extern prelude, so reporting this to the
1555                    // user is no help. This skips the injected
1556                    // `extern crate std` in the 2018 edition, which would
1557                    // otherwise cause duplicate suggestions.
1558                    continue;
1559                }
1560                let Some(crate_id) =
1561                    self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
1562                else {
1563                    continue;
1564                };
1565
1566                let crate_def_id = crate_id.as_def_id();
1567                let crate_root = self.expect_module(crate_def_id);
1568
1569                // Check if there's already an item in scope with the same name as the crate.
1570                // If so, we have to disambiguate the potential import suggestions by making
1571                // the paths *global* (i.e., by prefixing them with `::`).
1572                let needs_disambiguation =
1573                    self.resolutions(parent_scope.module).borrow().iter().any(
1574                        |(key, name_resolution)| {
1575                            if key.ns == TypeNS
1576                                && key.ident == *ident
1577                                && let Some(decl) = name_resolution.borrow().best_decl()
1578                            {
1579                                match decl.res() {
1580                                    // No disambiguation needed if the identically named item we
1581                                    // found in scope actually refers to the crate in question.
1582                                    Res::Def(_, def_id) => def_id != crate_def_id,
1583                                    Res::PrimTy(_) => true,
1584                                    _ => false,
1585                                }
1586                            } else {
1587                                false
1588                            }
1589                        },
1590                    );
1591                let mut crate_path = ThinVec::new();
1592                if needs_disambiguation {
1593                    crate_path.push(ast::PathSegment::path_root(rustc_span::DUMMY_SP));
1594                }
1595                crate_path.push(ast::PathSegment::from_ident(ident.orig(entry.span())));
1596
1597                suggestions.extend(self.lookup_import_candidates_from_module(
1598                    lookup_ident,
1599                    namespace,
1600                    parent_scope,
1601                    crate_root,
1602                    crate_path,
1603                    &filter_fn,
1604                ));
1605            }
1606        }
1607
1608        suggestions.retain(|suggestion| suggestion.is_stable || self.tcx.sess.is_nightly_build());
1609        suggestions
1610    }
1611
1612    pub(crate) fn unresolved_macro_suggestions(
1613        &mut self,
1614        err: &mut Diag<'_>,
1615        macro_kind: MacroKind,
1616        parent_scope: &ParentScope<'ra>,
1617        ident: Ident,
1618        krate: &Crate,
1619        sugg_span: Option<Span>,
1620    ) {
1621        // Bring all unused `derive` macros into `macro_map` so we ensure they can be used for
1622        // suggestions.
1623        self.register_macros_for_all_crates();
1624
1625        let is_expected =
1626            &|res: Res| res.macro_kinds().is_some_and(|k| k.contains(macro_kind.into()));
1627        let suggestion = self.early_lookup_typo_candidate(
1628            ScopeSet::Macro(macro_kind),
1629            parent_scope,
1630            ident,
1631            is_expected,
1632        );
1633        if !self.add_typo_suggestion(err, suggestion, ident.span) {
1634            self.detect_derive_attribute(err, ident, parent_scope, sugg_span);
1635        }
1636
1637        let import_suggestions =
1638            self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1639        let (span, found_use) = match parent_scope.module.nearest_parent_mod().as_local() {
1640            Some(def_id) => UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id)),
1641            None => (None, FoundUse::No),
1642        };
1643        show_candidates(
1644            self.tcx,
1645            err,
1646            span,
1647            &import_suggestions,
1648            Instead::No,
1649            found_use,
1650            DiagMode::Normal,
1651            ::alloc::vec::Vec::new()vec![],
1652            "",
1653        );
1654
1655        if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1656            let label_span = ident.span.shrink_to_hi();
1657            let mut spans = MultiSpan::from_span(label_span);
1658            spans.push_span_label(label_span, "put a macro name here");
1659            err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1660            return;
1661        }
1662
1663        if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1664            err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1665            return;
1666        }
1667
1668        let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1669            if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1670        });
1671
1672        if let Some((def_id, unused_ident)) = unused_macro {
1673            let scope = self.local_macro_def_scopes[&def_id];
1674            let parent_nearest = parent_scope.module.nearest_parent_mod();
1675            let unused_macro_kinds = self.local_macro_map[def_id].ext.macro_kinds();
1676            if !unused_macro_kinds.contains(macro_kind.into()) {
1677                match macro_kind {
1678                    MacroKind::Bang => {
1679                        err.subdiagnostic(MacroRulesNot::Func { span: unused_ident.span, ident });
1680                    }
1681                    MacroKind::Attr => {
1682                        err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1683                    }
1684                    MacroKind::Derive => {
1685                        err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1686                    }
1687                }
1688                return;
1689            }
1690            if Some(parent_nearest) == scope.opt_def_id() {
1691                err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1692                err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1693                return;
1694            }
1695        }
1696
1697        if ident.name == kw::Default
1698            && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1699        {
1700            let span = self.def_span(def_id);
1701            let source_map = self.tcx.sess.source_map();
1702            let head_span = source_map.guess_head_span(span);
1703            err.subdiagnostic(ConsiderAddingADerive {
1704                span: head_span.shrink_to_lo(),
1705                suggestion: "#[derive(Default)]\n".to_string(),
1706            });
1707        }
1708        for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1709            let Ok(binding) = self.cm().resolve_ident_in_scope_set(
1710                ident,
1711                ScopeSet::All(ns),
1712                parent_scope,
1713                None,
1714                None,
1715                None,
1716            ) else {
1717                continue;
1718            };
1719
1720            let desc = match binding.res() {
1721                Res::Def(DefKind::Macro(MacroKinds::BANG), _) => {
1722                    "a function-like macro".to_string()
1723                }
1724                Res::Def(DefKind::Macro(MacroKinds::ATTR), _) | Res::NonMacroAttr(..) => {
1725                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("an attribute: `#[{0}]`", ident))
    })format!("an attribute: `#[{ident}]`")
1726                }
1727                Res::Def(DefKind::Macro(MacroKinds::DERIVE), _) => {
1728                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a derive macro: `#[derive({0})]`",
                ident))
    })format!("a derive macro: `#[derive({ident})]`")
1729                }
1730                Res::Def(DefKind::Macro(kinds), _) => {
1731                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}", kinds.article(),
                kinds.descr()))
    })format!("{} {}", kinds.article(), kinds.descr())
1732                }
1733                Res::ToolMod => {
1734                    // Don't confuse the user with tool modules.
1735                    continue;
1736                }
1737                Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1738                    "only a trait, without a derive macro".to_string()
1739                }
1740                res => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}, not {2} {3}",
                res.article(), res.descr(), macro_kind.article(),
                macro_kind.descr_expected()))
    })format!(
1741                    "{} {}, not {} {}",
1742                    res.article(),
1743                    res.descr(),
1744                    macro_kind.article(),
1745                    macro_kind.descr_expected(),
1746                ),
1747            };
1748            if let crate::DeclKind::Import { import, .. } = binding.kind
1749                && !import.span.is_dummy()
1750            {
1751                let note = errors::IdentImporterHereButItIsDesc {
1752                    span: import.span,
1753                    imported_ident: ident,
1754                    imported_ident_desc: &desc,
1755                };
1756                err.subdiagnostic(note);
1757                // Silence the 'unused import' warning we might get,
1758                // since this diagnostic already covers that import.
1759                self.record_use(ident, binding, Used::Other);
1760                return;
1761            }
1762            let note = errors::IdentInScopeButItIsDesc {
1763                imported_ident: ident,
1764                imported_ident_desc: &desc,
1765            };
1766            err.subdiagnostic(note);
1767            return;
1768        }
1769
1770        if self.macro_names.contains(&IdentKey::new(ident)) {
1771            err.subdiagnostic(AddedMacroUse);
1772            return;
1773        }
1774    }
1775
1776    /// Given an attribute macro that failed to be resolved, look for `derive` macros that could
1777    /// provide it, either as-is or with small typos.
1778    fn detect_derive_attribute(
1779        &self,
1780        err: &mut Diag<'_>,
1781        ident: Ident,
1782        parent_scope: &ParentScope<'ra>,
1783        sugg_span: Option<Span>,
1784    ) {
1785        // Find all of the `derive`s in scope and collect their corresponding declared
1786        // attributes.
1787        // FIXME: this only works if the crate that owns the macro that has the helper_attr
1788        // has already been imported.
1789        let mut derives = ::alloc::vec::Vec::new()vec![];
1790        let mut all_attrs: UnordMap<Symbol, Vec<_>> = UnordMap::default();
1791        // We're collecting these in a hashmap, and handle ordering the output further down.
1792        #[allow(rustc::potential_query_instability)]
1793        for (def_id, data) in self
1794            .local_macro_map
1795            .iter()
1796            .map(|(local_id, data)| (local_id.to_def_id(), data))
1797            .chain(self.extern_macro_map.borrow().iter().map(|(id, d)| (*id, d)))
1798        {
1799            for helper_attr in &data.ext.helper_attrs {
1800                let item_name = self.tcx.item_name(def_id);
1801                all_attrs.entry(*helper_attr).or_default().push(item_name);
1802                if helper_attr == &ident.name {
1803                    derives.push(item_name);
1804                }
1805            }
1806        }
1807        let kind = MacroKind::Derive.descr();
1808        if !derives.is_empty() {
1809            // We found an exact match for the missing attribute in a `derive` macro. Suggest it.
1810            let mut derives: Vec<String> = derives.into_iter().map(|d| d.to_string()).collect();
1811            derives.sort();
1812            derives.dedup();
1813            let msg = match &derives[..] {
1814                [derive] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" `{0}`", derive))
    })format!(" `{derive}`"),
1815                [start @ .., last] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("s {0} and `{1}`",
                start.iter().map(|d|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("`{0}`", d))
                                    })).collect::<Vec<_>>().join(", "), last))
    })format!(
1816                    "s {} and `{last}`",
1817                    start.iter().map(|d| format!("`{d}`")).collect::<Vec<_>>().join(", ")
1818                ),
1819                [] => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("we checked for this to be non-empty 10 lines above!?")));
}unreachable!("we checked for this to be non-empty 10 lines above!?"),
1820            };
1821            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is an attribute that can be used by the {1}{2}, you might be missing a `derive` attribute",
                ident.name, kind, msg))
    })format!(
1822                "`{}` is an attribute that can be used by the {kind}{msg}, you might be \
1823                     missing a `derive` attribute",
1824                ident.name,
1825            );
1826            let sugg_span = if let ModuleKind::Def(DefKind::Enum, id, _) = parent_scope.module.kind
1827            {
1828                let span = self.def_span(id);
1829                if span.from_expansion() {
1830                    None
1831                } else {
1832                    // For enum variants sugg_span is empty but we can get the enum's Span.
1833                    Some(span.shrink_to_lo())
1834                }
1835            } else {
1836                // For items this `Span` will be populated, everything else it'll be None.
1837                sugg_span
1838            };
1839            match sugg_span {
1840                Some(span) => {
1841                    err.span_suggestion_verbose(
1842                        span,
1843                        msg,
1844                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#[derive({0})]\n",
                derives.join(", ")))
    })format!("#[derive({})]\n", derives.join(", ")),
1845                        Applicability::MaybeIncorrect,
1846                    );
1847                }
1848                None => {
1849                    err.note(msg);
1850                }
1851            }
1852        } else {
1853            // We didn't find an exact match. Look for close matches. If any, suggest fixing typo.
1854            let all_attr_names = all_attrs.keys().map(|s| *s).into_sorted_stable_ord();
1855            if let Some(best_match) = find_best_match_for_name(&all_attr_names, ident.name, None)
1856                && let Some(macros) = all_attrs.get(&best_match)
1857            {
1858                let mut macros: Vec<String> = macros.into_iter().map(|d| d.to_string()).collect();
1859                macros.sort();
1860                macros.dedup();
1861                let msg = match &macros[..] {
1862                    [] => return,
1863                    [name] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" `{0}` accepts", name))
    })format!(" `{name}` accepts"),
1864                    [start @ .., end] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("s {0} and `{1}` accept",
                start.iter().map(|m|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("`{0}`", m))
                                    })).collect::<Vec<_>>().join(", "), end))
    })format!(
1865                        "s {} and `{end}` accept",
1866                        start.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", "),
1867                    ),
1868                };
1869                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the {0}{1} the similarly named `{2}` attribute",
                kind, msg, best_match))
    })format!("the {kind}{msg} the similarly named `{best_match}` attribute");
1870                err.span_suggestion_verbose(
1871                    ident.span,
1872                    msg,
1873                    best_match,
1874                    Applicability::MaybeIncorrect,
1875                );
1876            }
1877        }
1878    }
1879
1880    pub(crate) fn add_typo_suggestion(
1881        &self,
1882        err: &mut Diag<'_>,
1883        suggestion: Option<TypoSuggestion>,
1884        span: Span,
1885    ) -> bool {
1886        let suggestion = match suggestion {
1887            None => return false,
1888            // We shouldn't suggest underscore.
1889            Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1890            Some(suggestion) => suggestion,
1891        };
1892
1893        let mut did_label_def_span = false;
1894
1895        if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1896            if span.overlaps(def_span) {
1897                // Don't suggest typo suggestion for itself like in the following:
1898                // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1899                //   --> $DIR/unicode-string-literal-syntax-error-64792.rs:4:14
1900                //    |
1901                // LL | struct X {}
1902                //    | ----------- `X` defined here
1903                // LL |
1904                // LL | const Y: X = X("ö");
1905                //    | -------------^^^^^^- similarly named constant `Y` defined here
1906                //    |
1907                // help: use struct literal syntax instead
1908                //    |
1909                // LL | const Y: X = X {};
1910                //    |              ^^^^
1911                // help: a constant with a similar name exists
1912                //    |
1913                // LL | const Y: X = Y("ö");
1914                //    |              ^
1915                return false;
1916            }
1917            let span = self.tcx.sess.source_map().guess_head_span(def_span);
1918            let candidate_descr = suggestion.res.descr();
1919            let candidate = suggestion.candidate;
1920            let label = match suggestion.target {
1921                SuggestionTarget::SimilarlyNamed => {
1922                    errors::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
1923                }
1924                SuggestionTarget::SingleItem => {
1925                    errors::DefinedHere::SingleItem { span, candidate_descr, candidate }
1926                }
1927            };
1928            did_label_def_span = true;
1929            err.subdiagnostic(label);
1930        }
1931
1932        let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
1933            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1934            && let Some(span) = suggestion.span
1935            && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
1936            && snippet == candidate
1937        {
1938            let candidate = suggestion.candidate;
1939            // When the suggested binding change would be from `x` to `_x`, suggest changing the
1940            // original binding definition instead. (#60164)
1941            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the leading underscore in `{0}` marks it as unused, consider renaming it to `{1}`",
                candidate, snippet))
    })format!(
1942                "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
1943            );
1944            if !did_label_def_span {
1945                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` defined here", candidate))
    })format!("`{candidate}` defined here"));
1946            }
1947            (span, msg, snippet)
1948        } else {
1949            let msg = match suggestion.target {
1950                SuggestionTarget::SimilarlyNamed => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1} with a similar name exists",
                suggestion.res.article(), suggestion.res.descr()))
    })format!(
1951                    "{} {} with a similar name exists",
1952                    suggestion.res.article(),
1953                    suggestion.res.descr()
1954                ),
1955                SuggestionTarget::SingleItem => {
1956                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("maybe you meant this {0}",
                suggestion.res.descr()))
    })format!("maybe you meant this {}", suggestion.res.descr())
1957                }
1958            };
1959            (span, msg, suggestion.candidate.to_ident_string())
1960        };
1961        err.span_suggestion_verbose(span, msg, sugg, Applicability::MaybeIncorrect);
1962        true
1963    }
1964
1965    fn decl_description(&self, b: Decl<'_>, ident: Ident, scope: Scope<'_>) -> String {
1966        let res = b.res();
1967        if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
1968            let (built_in, from) = match scope {
1969                Scope::StdLibPrelude | Scope::MacroUsePrelude => ("", " from prelude"),
1970                Scope::ExternPreludeFlags
1971                    if self.tcx.sess.opts.externs.get(ident.as_str()).is_some() =>
1972                {
1973                    ("", " passed with `--extern`")
1974                }
1975                _ => {
1976                    if #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => true,
    _ => false,
}matches!(res, Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod) {
1977                        // These already contain the "built-in" prefix or look bad with it.
1978                        ("", "")
1979                    } else {
1980                        (" built-in", "")
1981                    }
1982                }
1983            };
1984
1985            let a = if built_in.is_empty() { res.article() } else { "a" };
1986            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{2} {0}{3}", res.descr(), a,
                built_in, from))
    })format!("{a}{built_in} {thing}{from}", thing = res.descr())
1987        } else {
1988            let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1989            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the {0} {1} here", res.descr(),
                introduced))
    })format!("the {thing} {introduced} here", thing = res.descr())
1990        }
1991    }
1992
1993    fn ambiguity_diagnostic(&self, ambiguity_error: &AmbiguityError<'ra>) -> errors::Ambiguity {
1994        let AmbiguityError { kind, ambig_vis, ident, b1, b2, scope1, scope2, .. } =
1995            *ambiguity_error;
1996        let extern_prelude_ambiguity = || {
1997            // Note: b1 may come from a module scope, as an extern crate item in module.
1998            #[allow(non_exhaustive_omitted_patterns)] match scope2 {
    Scope::ExternPreludeFlags => true,
    _ => false,
}matches!(scope2, Scope::ExternPreludeFlags)
1999                && self
2000                    .extern_prelude
2001                    .get(&IdentKey::new(ident))
2002                    .is_some_and(|entry| entry.item_decl.map(|(b, ..)| b) == Some(b1))
2003        };
2004        let (b1, b2, scope1, scope2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
2005            // We have to print the span-less alternative first, otherwise formatting looks bad.
2006            (b2, b1, scope2, scope1, true)
2007        } else {
2008            (b1, b2, scope1, scope2, false)
2009        };
2010
2011        let could_refer_to = |b: Decl<'_>, scope: Scope<'ra>, also: &str| {
2012            let what = self.decl_description(b, ident, scope);
2013            let note_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` could{1} refer to {2}",
                ident, also, what))
    })format!("`{ident}` could{also} refer to {what}");
2014
2015            let thing = b.res().descr();
2016            let mut help_msgs = Vec::new();
2017            if b.is_glob_import()
2018                && (kind == AmbiguityKind::GlobVsGlob
2019                    || kind == AmbiguityKind::GlobVsExpanded
2020                    || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
2021            {
2022                help_msgs.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider adding an explicit import of `{0}` to disambiguate",
                ident))
    })format!(
2023                    "consider adding an explicit import of `{ident}` to disambiguate"
2024                ))
2025            }
2026            if b.is_extern_crate() && ident.span.at_least_rust_2018() && !extern_prelude_ambiguity()
2027            {
2028                help_msgs.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `::{0}` to refer to this {1} unambiguously",
                ident, thing))
    })format!("use `::{ident}` to refer to this {thing} unambiguously"))
2029            }
2030
2031            if kind != AmbiguityKind::GlobVsGlob {
2032                if let Scope::ModuleNonGlobs(module, _) | Scope::ModuleGlobs(module, _) = scope {
2033                    if module == self.graph_root {
2034                        help_msgs.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `crate::{0}` to refer to this {1} unambiguously",
                ident, thing))
    })format!(
2035                            "use `crate::{ident}` to refer to this {thing} unambiguously"
2036                        ));
2037                    } else if module.is_normal() {
2038                        help_msgs.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `self::{0}` to refer to this {1} unambiguously",
                ident, thing))
    })format!(
2039                            "use `self::{ident}` to refer to this {thing} unambiguously"
2040                        ));
2041                    }
2042                }
2043            }
2044
2045            (
2046                Spanned { node: note_msg, span: b.span },
2047                help_msgs
2048                    .iter()
2049                    .enumerate()
2050                    .map(|(i, help_msg)| {
2051                        let or = if i == 0 { "" } else { "or " };
2052                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", or, help_msg))
    })format!("{or}{help_msg}")
2053                    })
2054                    .collect::<Vec<_>>(),
2055            )
2056        };
2057        let (b1_note, b1_help_msgs) = could_refer_to(b1, scope1, "");
2058        let (b2_note, b2_help_msgs) = could_refer_to(b2, scope2, " also");
2059        let help = if kind == AmbiguityKind::GlobVsGlob
2060            && b1
2061                .parent_module
2062                .and_then(|m| m.opt_def_id())
2063                .map(|d| !d.is_local())
2064                .unwrap_or_default()
2065        {
2066            Some(&[
2067                "consider updating this dependency to resolve this error",
2068                "if updating the dependency does not resolve the problem report the problem to the author of the relevant crate",
2069            ] as &[_])
2070        } else {
2071            None
2072        };
2073
2074        let ambig_vis = ambig_vis.map(|(vis1, vis2)| {
2075            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} or {1}",
                vis1.to_string(CRATE_DEF_ID, self.tcx),
                vis2.to_string(CRATE_DEF_ID, self.tcx)))
    })format!(
2076                "{} or {}",
2077                vis1.to_string(CRATE_DEF_ID, self.tcx),
2078                vis2.to_string(CRATE_DEF_ID, self.tcx)
2079            )
2080        });
2081
2082        errors::Ambiguity {
2083            ident,
2084            help,
2085            ambig_vis,
2086            kind: kind.descr(),
2087            b1_note,
2088            b1_help_msgs,
2089            b2_note,
2090            b2_help_msgs,
2091        }
2092    }
2093
2094    /// If the binding refers to a tuple struct constructor with fields,
2095    /// returns the span of its fields.
2096    fn ctor_fields_span(&self, decl: Decl<'_>) -> Option<Span> {
2097        let DeclKind::Def(Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id)) =
2098            decl.kind
2099        else {
2100            return None;
2101        };
2102
2103        let def_id = self.tcx.parent(ctor_def_id);
2104        self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) // None for `struct Foo()`
2105    }
2106
2107    fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
2108        let PrivacyError {
2109            ident,
2110            decl,
2111            outermost_res,
2112            parent_scope,
2113            single_nested,
2114            dedup_span,
2115            ref source,
2116        } = *privacy_error;
2117
2118        let res = decl.res();
2119        let ctor_fields_span = self.ctor_fields_span(decl);
2120        let plain_descr = res.descr().to_string();
2121        let nonimport_descr =
2122            if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
2123        let import_descr = nonimport_descr.clone() + " import";
2124        let get_descr = |b: Decl<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
2125
2126        // Print the primary message.
2127        let ident_descr = get_descr(decl);
2128        let mut err =
2129            self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
2130
2131        self.mention_default_field_values(source, ident, &mut err);
2132
2133        let mut not_publicly_reexported = false;
2134        if let Some((this_res, outer_ident)) = outermost_res {
2135            let import_suggestions = self.lookup_import_candidates(
2136                outer_ident,
2137                this_res.ns().unwrap_or(Namespace::TypeNS),
2138                &parent_scope,
2139                &|res: Res| res == this_res,
2140            );
2141            let point_to_def = !show_candidates(
2142                self.tcx,
2143                &mut err,
2144                Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
2145                &import_suggestions,
2146                Instead::Yes,
2147                FoundUse::Yes,
2148                DiagMode::Import { append: single_nested, unresolved_import: false },
2149                ::alloc::vec::Vec::new()vec![],
2150                "",
2151            );
2152            // If we suggest importing a public re-export, don't point at the definition.
2153            if point_to_def && ident.span != outer_ident.span {
2154                not_publicly_reexported = true;
2155                let label = errors::OuterIdentIsNotPubliclyReexported {
2156                    span: outer_ident.span,
2157                    outer_ident_descr: this_res.descr(),
2158                    outer_ident,
2159                };
2160                err.subdiagnostic(label);
2161            }
2162        }
2163
2164        let mut non_exhaustive = None;
2165        // If an ADT is foreign and marked as `non_exhaustive`, then that's
2166        // probably why we have the privacy error.
2167        // Otherwise, point out if the struct has any private fields.
2168        if let Some(def_id) = res.opt_def_id()
2169            && !def_id.is_local()
2170            && let Some(attr_span) = {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in self.tcx.get_all_attrs(def_id) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(NonExhaustive(span)) => {
                            break 'done Some(*span);
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }
}find_attr!(self.tcx, def_id, NonExhaustive(span) => *span)
2171        {
2172            non_exhaustive = Some(attr_span);
2173        } else if let Some(span) = ctor_fields_span {
2174            let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
2175            err.subdiagnostic(label);
2176            if let Res::Def(_, d) = res
2177                && let Some(fields) = self.field_visibility_spans.get(&d)
2178            {
2179                let spans = fields.iter().map(|span| *span).collect();
2180                let sugg =
2181                    errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
2182                err.subdiagnostic(sugg);
2183            }
2184        }
2185
2186        let mut sugg_paths: Vec<(Vec<Ident>, bool)> = ::alloc::vec::Vec::new()vec![];
2187        if let Some(mut def_id) = res.opt_def_id() {
2188            // We can't use `def_path_str` in resolve.
2189            let mut path = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [def_id]))vec![def_id];
2190            while let Some(parent) = self.tcx.opt_parent(def_id) {
2191                def_id = parent;
2192                if !def_id.is_top_level_module() {
2193                    path.push(def_id);
2194                } else {
2195                    break;
2196                }
2197            }
2198            // We will only suggest importing directly if it is accessible through that path.
2199            let path_names: Option<Vec<Ident>> = path
2200                .iter()
2201                .rev()
2202                .map(|def_id| {
2203                    self.tcx.opt_item_name(*def_id).map(|name| {
2204                        Ident::with_dummy_span(if def_id.is_top_level_module() {
2205                            kw::Crate
2206                        } else {
2207                            name
2208                        })
2209                    })
2210                })
2211                .collect();
2212            if let Some(&def_id) = path.get(0)
2213                && let Some(path) = path_names
2214            {
2215                if let Some(def_id) = def_id.as_local() {
2216                    if self.effective_visibilities.is_directly_public(def_id) {
2217                        sugg_paths.push((path, false));
2218                    }
2219                } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
2220                {
2221                    sugg_paths.push((path, false));
2222                }
2223            }
2224        }
2225
2226        // Print the whole import chain to make it easier to see what happens.
2227        let first_binding = decl;
2228        let mut next_binding = Some(decl);
2229        let mut next_ident = ident;
2230        let mut path = ::alloc::vec::Vec::new()vec![];
2231        while let Some(binding) = next_binding {
2232            let name = next_ident;
2233            next_binding = match binding.kind {
2234                _ if res == Res::Err => None,
2235                DeclKind::Import { source_decl, import, .. } => match import.kind {
2236                    _ if source_decl.span.is_dummy() => None,
2237                    ImportKind::Single { source, .. } => {
2238                        next_ident = source;
2239                        Some(source_decl)
2240                    }
2241                    ImportKind::Glob { .. }
2242                    | ImportKind::MacroUse { .. }
2243                    | ImportKind::MacroExport => Some(source_decl),
2244                    ImportKind::ExternCrate { .. } => None,
2245                },
2246                _ => None,
2247            };
2248
2249            match binding.kind {
2250                DeclKind::Import { import, .. } => {
2251                    for segment in import.module_path.iter().skip(1) {
2252                        // Don't include `{{root}}` in suggestions - it's an internal symbol
2253                        // that should never be shown to users.
2254                        if segment.ident.name != kw::PathRoot {
2255                            path.push(segment.ident);
2256                        }
2257                    }
2258                    sugg_paths.push((
2259                        path.iter().cloned().chain(std::iter::once(ident)).collect::<Vec<_>>(),
2260                        true, // re-export
2261                    ));
2262                }
2263                DeclKind::Def(_) => {}
2264            }
2265            let first = binding == first_binding;
2266            let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
2267            let mut note_span = MultiSpan::from_span(def_span);
2268            if !first && binding.vis().is_public() {
2269                let desc = match binding.kind {
2270                    DeclKind::Import { .. } => "re-export",
2271                    _ => "directly",
2272                };
2273                note_span.push_span_label(def_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you could import this {0}", desc))
    })format!("you could import this {desc}"));
2274            }
2275            // Final step in the import chain, point out if the ADT is `non_exhaustive`
2276            // which is probably why this privacy violation occurred.
2277            if next_binding.is_none()
2278                && let Some(span) = non_exhaustive
2279            {
2280                note_span.push_span_label(
2281                    span,
2282                    "cannot be constructed because it is `#[non_exhaustive]`",
2283                );
2284            }
2285            let note = errors::NoteAndRefersToTheItemDefinedHere {
2286                span: note_span,
2287                binding_descr: get_descr(binding),
2288                binding_name: name,
2289                first,
2290                dots: next_binding.is_some(),
2291            };
2292            err.subdiagnostic(note);
2293        }
2294        // We prioritize shorter paths, non-core imports and direct imports over the alternatives.
2295        sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0].name == sym::core, *reexport));
2296        for (sugg, reexport) in sugg_paths {
2297            if not_publicly_reexported {
2298                break;
2299            }
2300            if sugg.len() <= 1 {
2301                // A single path segment suggestion is wrong. This happens on circular imports.
2302                // `tests/ui/imports/issue-55884-2.rs`
2303                continue;
2304            }
2305            let path = join_path_idents(sugg);
2306            let sugg = if reexport {
2307                errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
2308            } else {
2309                errors::ImportIdent::Directly { span: dedup_span, ident, path }
2310            };
2311            err.subdiagnostic(sugg);
2312            break;
2313        }
2314
2315        err.emit();
2316    }
2317
2318    /// When a private field is being set that has a default field value, we suggest using `..` and
2319    /// setting the value of that field implicitly with its default.
2320    ///
2321    /// If we encounter code like
2322    /// ```text
2323    /// struct Priv;
2324    /// pub struct S {
2325    ///     pub field: Priv = Priv,
2326    /// }
2327    /// ```
2328    /// which is used from a place where `Priv` isn't accessible
2329    /// ```text
2330    /// let _ = S { field: m::Priv1 {} };
2331    /// //                    ^^^^^ private struct
2332    /// ```
2333    /// we will suggest instead using the `default_field_values` syntax instead:
2334    /// ```text
2335    /// let _ = S { .. };
2336    /// ```
2337    fn mention_default_field_values(
2338        &self,
2339        source: &Option<ast::Expr>,
2340        ident: Ident,
2341        err: &mut Diag<'_>,
2342    ) {
2343        let Some(expr) = source else { return };
2344        let ast::ExprKind::Struct(struct_expr) = &expr.kind else { return };
2345        // We don't have to handle type-relative paths because they're forbidden in ADT
2346        // expressions, but that would change with `#[feature(more_qualified_paths)]`.
2347        let Some(segment) = struct_expr.path.segments.last() else { return };
2348        let Some(partial_res) = self.partial_res_map.get(&segment.id) else { return };
2349        let Some(Res::Def(_, def_id)) = partial_res.full_res() else {
2350            return;
2351        };
2352        let Some(default_fields) = self.field_defaults(def_id) else { return };
2353        if struct_expr.fields.is_empty() {
2354            return;
2355        }
2356        let last_span = struct_expr.fields.iter().last().unwrap().span;
2357        let mut iter = struct_expr.fields.iter().peekable();
2358        let mut prev: Option<Span> = None;
2359        while let Some(field) = iter.next() {
2360            if field.expr.span.overlaps(ident.span) {
2361                err.span_label(field.ident.span, "while setting this field");
2362                if default_fields.contains(&field.ident.name) {
2363                    let sugg = if last_span == field.span {
2364                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(field.span, "..".to_string())]))vec![(field.span, "..".to_string())]
2365                    } else {
2366                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(match (prev, iter.peek()) {
                        (_, Some(next)) => field.span.with_hi(next.span.lo()),
                        (Some(prev), _) => field.span.with_lo(prev.hi()),
                        (None, None) => field.span,
                    }, String::new()),
                (last_span.shrink_to_hi(), ", ..".to_string())]))vec![
2367                            (
2368                                // Account for trailing commas and ensure we remove them.
2369                                match (prev, iter.peek()) {
2370                                    (_, Some(next)) => field.span.with_hi(next.span.lo()),
2371                                    (Some(prev), _) => field.span.with_lo(prev.hi()),
2372                                    (None, None) => field.span,
2373                                },
2374                                String::new(),
2375                            ),
2376                            (last_span.shrink_to_hi(), ", ..".to_string()),
2377                        ]
2378                    };
2379                    err.multipart_suggestion(
2380                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the type `{2}` of field `{0}` is private, but you can construct the default value defined for it in `{1}` using `..` in the struct initializer expression",
                field.ident, self.tcx.item_name(def_id), ident))
    })format!(
2381                            "the type `{ident}` of field `{}` is private, but you can construct \
2382                             the default value defined for it in `{}` using `..` in the struct \
2383                             initializer expression",
2384                            field.ident,
2385                            self.tcx.item_name(def_id),
2386                        ),
2387                        sugg,
2388                        Applicability::MachineApplicable,
2389                    );
2390                    break;
2391                }
2392            }
2393            prev = Some(field.span);
2394        }
2395    }
2396
2397    pub(crate) fn find_similarly_named_module_or_crate(
2398        &self,
2399        ident: Symbol,
2400        current_module: Module<'ra>,
2401    ) -> Option<Symbol> {
2402        let mut candidates = self
2403            .extern_prelude
2404            .keys()
2405            .map(|ident| ident.name)
2406            .chain(
2407                self.local_module_map
2408                    .iter()
2409                    .filter(|(_, module)| {
2410                        current_module.is_ancestor_of(**module) && current_module != **module
2411                    })
2412                    .flat_map(|(_, module)| module.kind.name()),
2413            )
2414            .chain(
2415                self.extern_module_map
2416                    .borrow()
2417                    .iter()
2418                    .filter(|(_, module)| {
2419                        current_module.is_ancestor_of(**module) && current_module != **module
2420                    })
2421                    .flat_map(|(_, module)| module.kind.name()),
2422            )
2423            .filter(|c| !c.to_string().is_empty())
2424            .collect::<Vec<_>>();
2425        candidates.sort();
2426        candidates.dedup();
2427        find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
2428    }
2429
2430    pub(crate) fn report_path_resolution_error(
2431        &mut self,
2432        path: &[Segment],
2433        opt_ns: Option<Namespace>, // `None` indicates a module path in import
2434        parent_scope: &ParentScope<'ra>,
2435        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
2436        ignore_decl: Option<Decl<'ra>>,
2437        ignore_import: Option<Import<'ra>>,
2438        module: Option<ModuleOrUniformRoot<'ra>>,
2439        failed_segment_idx: usize,
2440        ident: Ident,
2441        diag_metadata: Option<&DiagMetadata<'_>>,
2442    ) -> (String, String, Option<Suggestion>) {
2443        let is_last = failed_segment_idx == path.len() - 1;
2444        let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2445        let module_res = match module {
2446            Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2447            _ => None,
2448        };
2449        let scope = match &path[..failed_segment_idx] {
2450            [.., prev] => {
2451                if prev.ident.name == kw::PathRoot {
2452                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the crate root"))
    })format!("the crate root")
2453                } else {
2454                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", prev.ident))
    })format!("`{}`", prev.ident)
2455                }
2456            }
2457            _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this scope"))
    })format!("this scope"),
2458        };
2459        let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find `{0}` in {1}", ident,
                scope))
    })format!("cannot find `{ident}` in {scope}");
2460
2461        if module_res == self.graph_root.res() {
2462            let is_mod = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Mod, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Mod, _));
2463            let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2464            candidates
2465                .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2466            if let Some(candidate) = candidates.get(0) {
2467                let path = {
2468                    // remove the possible common prefix of the path
2469                    let len = candidate.path.segments.len();
2470                    let start_index = (0..=failed_segment_idx.min(len - 1))
2471                        .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2472                        .unwrap_or_default();
2473                    let segments =
2474                        (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2475                    Path { segments, span: Span::default(), tokens: None }
2476                };
2477                (
2478                    message,
2479                    String::from("unresolved import"),
2480                    Some((
2481                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ident.span, pprust::path_to_string(&path))]))vec![(ident.span, pprust::path_to_string(&path))],
2482                        String::from("a similar path exists"),
2483                        Applicability::MaybeIncorrect,
2484                    )),
2485                )
2486            } else if ident.name == sym::core {
2487                (
2488                    message,
2489                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might be missing crate `{0}`",
                ident))
    })format!("you might be missing crate `{ident}`"),
2490                    Some((
2491                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ident.span, "std".to_string())]))vec![(ident.span, "std".to_string())],
2492                        "try using `std` instead of `core`".to_string(),
2493                        Applicability::MaybeIncorrect,
2494                    )),
2495                )
2496            } else if ident.name == kw::Underscore {
2497                (
2498                    "invalid crate or module name `_`".to_string(),
2499                    "`_` is not a valid crate or module name".to_string(),
2500                    None,
2501                )
2502            } else if self.tcx.sess.is_rust_2015() {
2503                (
2504                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
                ident, scope))
    })format!("cannot find module or crate `{ident}` in {scope}"),
2505                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use of unresolved module or unlinked crate `{0}`",
                ident))
    })format!("use of unresolved module or unlinked crate `{ident}`"),
2506                    Some((
2507                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(self.current_crate_outer_attr_insert_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("extern crate {0};\n",
                                    ident))
                        }))]))vec![(
2508                            self.current_crate_outer_attr_insert_span,
2509                            format!("extern crate {ident};\n"),
2510                        )],
2511                        if was_invoked_from_cargo() {
2512                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you wanted to use a crate named `{0}`, use `cargo add {0}` to add it to your `Cargo.toml` and import it in your code",
                ident))
    })format!(
2513                                "if you wanted to use a crate named `{ident}`, use `cargo add \
2514                                 {ident}` to add it to your `Cargo.toml` and import it in your \
2515                                 code",
2516                            )
2517                        } else {
2518                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might be missing a crate named `{0}`, add it to your project and import it in your code",
                ident))
    })format!(
2519                                "you might be missing a crate named `{ident}`, add it to your \
2520                                 project and import it in your code",
2521                            )
2522                        },
2523                        Applicability::MaybeIncorrect,
2524                    )),
2525                )
2526            } else {
2527                (message, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("could not find `{0}` in the crate root",
                ident))
    })format!("could not find `{ident}` in the crate root"), None)
2528            }
2529        } else if failed_segment_idx > 0 {
2530            let parent = path[failed_segment_idx - 1].ident.name;
2531            let parent = match parent {
2532                // ::foo is mounted at the crate root for 2015, and is the extern
2533                // prelude for 2018+
2534                kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2535                    "the list of imported crates".to_owned()
2536                }
2537                kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2538                _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", parent))
    })format!("`{parent}`"),
2539            };
2540
2541            let mut msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("could not find `{0}` in {1}",
                ident, parent))
    })format!("could not find `{ident}` in {parent}");
2542            if ns == TypeNS || ns == ValueNS {
2543                let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2544                let binding = if let Some(module) = module {
2545                    self.cm()
2546                        .resolve_ident_in_module(
2547                            module,
2548                            ident,
2549                            ns_to_try,
2550                            parent_scope,
2551                            None,
2552                            ignore_decl,
2553                            ignore_import,
2554                        )
2555                        .ok()
2556                } else if let Some(ribs) = ribs
2557                    && let Some(TypeNS | ValueNS) = opt_ns
2558                {
2559                    if !ignore_import.is_none() {
    ::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
2560                    match self.resolve_ident_in_lexical_scope(
2561                        ident,
2562                        ns_to_try,
2563                        parent_scope,
2564                        None,
2565                        &ribs[ns_to_try],
2566                        ignore_decl,
2567                        diag_metadata,
2568                    ) {
2569                        // we found a locally-imported or available item/module
2570                        Some(LateDecl::Decl(binding)) => Some(binding),
2571                        _ => None,
2572                    }
2573                } else {
2574                    self.cm()
2575                        .resolve_ident_in_scope_set(
2576                            ident,
2577                            ScopeSet::All(ns_to_try),
2578                            parent_scope,
2579                            None,
2580                            ignore_decl,
2581                            ignore_import,
2582                        )
2583                        .ok()
2584                };
2585                if let Some(binding) = binding {
2586                    msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1} `{2}` in {3}",
                ns.descr(), binding.res().descr(), ident, parent))
    })format!(
2587                        "expected {}, found {} `{ident}` in {parent}",
2588                        ns.descr(),
2589                        binding.res().descr(),
2590                    );
2591                };
2592            }
2593            (message, msg, None)
2594        } else if ident.name == kw::SelfUpper {
2595            // As mentioned above, `opt_ns` being `None` indicates a module path in import.
2596            // We can use this to improve a confusing error for, e.g. `use Self::Variant` in an
2597            // impl
2598            if opt_ns.is_none() {
2599                (message, "`Self` cannot be used in imports".to_string(), None)
2600            } else {
2601                (
2602                    message,
2603                    "`Self` is only available in impls, traits, and type definitions".to_string(),
2604                    None,
2605                )
2606            }
2607        } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2608            // Check whether the name refers to an item in the value namespace.
2609            let binding = if let Some(ribs) = ribs {
2610                if !ignore_import.is_none() {
    ::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
2611                self.resolve_ident_in_lexical_scope(
2612                    ident,
2613                    ValueNS,
2614                    parent_scope,
2615                    None,
2616                    &ribs[ValueNS],
2617                    ignore_decl,
2618                    diag_metadata,
2619                )
2620            } else {
2621                None
2622            };
2623            let match_span = match binding {
2624                // Name matches a local variable. For example:
2625                // ```
2626                // fn f() {
2627                //     let Foo: &str = "";
2628                //     println!("{}", Foo::Bar); // Name refers to local
2629                //                               // variable `Foo`.
2630                // }
2631                // ```
2632                Some(LateDecl::RibDef(Res::Local(id))) => {
2633                    Some((*self.pat_span_map.get(&id).unwrap(), "a", "local binding"))
2634                }
2635                // Name matches item from a local name binding
2636                // created by `use` declaration. For example:
2637                // ```
2638                // pub const Foo: &str = "";
2639                //
2640                // mod submod {
2641                //     use super::Foo;
2642                //     println!("{}", Foo::Bar); // Name refers to local
2643                //                               // binding `Foo`.
2644                // }
2645                // ```
2646                Some(LateDecl::Decl(name_binding)) => Some((
2647                    name_binding.span,
2648                    name_binding.res().article(),
2649                    name_binding.res().descr(),
2650                )),
2651                _ => None,
2652            };
2653
2654            let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find type `{0}` in {1}",
                ident, scope))
    })format!("cannot find type `{ident}` in {scope}");
2655            let label = if let Some((span, article, descr)) = match_span {
2656                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{1}` is declared as {2} {3} at `{0}`, not a type",
                self.tcx.sess.source_map().span_to_short_string(span,
                    RemapPathScopeComponents::DIAGNOSTICS), ident, article,
                descr))
    })format!(
2657                    "`{ident}` is declared as {article} {descr} at `{}`, not a type",
2658                    self.tcx
2659                        .sess
2660                        .source_map()
2661                        .span_to_short_string(span, RemapPathScopeComponents::DIAGNOSTICS)
2662                )
2663            } else {
2664                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use of undeclared type `{0}`",
                ident))
    })format!("use of undeclared type `{ident}`")
2665            };
2666            (message, label, None)
2667        } else {
2668            let mut suggestion = None;
2669            if ident.name == sym::alloc {
2670                suggestion = Some((
2671                    ::alloc::vec::Vec::new()vec![],
2672                    String::from("add `extern crate alloc` to use the `alloc` crate"),
2673                    Applicability::MaybeIncorrect,
2674                ))
2675            }
2676
2677            suggestion = suggestion.or_else(|| {
2678                self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2679                    |sugg| {
2680                        (
2681                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(ident.span, sugg.to_string())]))vec![(ident.span, sugg.to_string())],
2682                            String::from("there is a crate or module with a similar name"),
2683                            Applicability::MaybeIncorrect,
2684                        )
2685                    },
2686                )
2687            });
2688            if let Ok(binding) = self.cm().resolve_ident_in_scope_set(
2689                ident,
2690                ScopeSet::All(ValueNS),
2691                parent_scope,
2692                None,
2693                ignore_decl,
2694                ignore_import,
2695            ) {
2696                let descr = binding.res().descr();
2697                let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
                ident, scope))
    })format!("cannot find module or crate `{ident}` in {scope}");
2698                (message, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}` is not a crate or module",
                descr, ident))
    })format!("{descr} `{ident}` is not a crate or module"), suggestion)
2699            } else {
2700                let suggestion = if suggestion.is_some() {
2701                    suggestion
2702                } else if let Some(m) = self.undeclared_module_exists(ident) {
2703                    self.undeclared_module_suggest_declare(ident, m)
2704                } else if was_invoked_from_cargo() {
2705                    Some((
2706                        ::alloc::vec::Vec::new()vec![],
2707                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you wanted to use a crate named `{0}`, use `cargo add {0}` to add it to your `Cargo.toml`",
                ident))
    })format!(
2708                            "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2709                             to add it to your `Cargo.toml`",
2710                        ),
2711                        Applicability::MaybeIncorrect,
2712                    ))
2713                } else {
2714                    Some((
2715                        ::alloc::vec::Vec::new()vec![],
2716                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might be missing a crate named `{0}`",
                ident))
    })format!("you might be missing a crate named `{ident}`",),
2717                        Applicability::MaybeIncorrect,
2718                    ))
2719                };
2720                let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
                ident, scope))
    })format!("cannot find module or crate `{ident}` in {scope}");
2721                (
2722                    message,
2723                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use of unresolved module or unlinked crate `{0}`",
                ident))
    })format!("use of unresolved module or unlinked crate `{ident}`"),
2724                    suggestion,
2725                )
2726            }
2727        }
2728    }
2729
2730    fn undeclared_module_suggest_declare(
2731        &self,
2732        ident: Ident,
2733        path: std::path::PathBuf,
2734    ) -> Option<(Vec<(Span, String)>, String, Applicability)> {
2735        Some((
2736            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(self.current_crate_outer_attr_insert_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("mod {0};\n", ident))
                        }))]))vec![(self.current_crate_outer_attr_insert_span, format!("mod {ident};\n"))],
2737            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to make use of source file {0}, use `mod {1}` in this file to declare the module",
                path.display(), ident))
    })format!(
2738                "to make use of source file {}, use `mod {ident}` \
2739                 in this file to declare the module",
2740                path.display()
2741            ),
2742            Applicability::MaybeIncorrect,
2743        ))
2744    }
2745
2746    fn undeclared_module_exists(&self, ident: Ident) -> Option<std::path::PathBuf> {
2747        let map = self.tcx.sess.source_map();
2748
2749        let src = map.span_to_filename(ident.span).into_local_path()?;
2750        let i = ident.as_str();
2751        // FIXME: add case where non parent using undeclared module (hard?)
2752        let dir = src.parent()?;
2753        let src = src.file_stem()?.to_str()?;
2754        for file in [
2755            // …/x.rs
2756            dir.join(i).with_extension("rs"),
2757            // …/x/mod.rs
2758            dir.join(i).join("mod.rs"),
2759        ] {
2760            if file.exists() {
2761                return Some(file);
2762            }
2763        }
2764        if !#[allow(non_exhaustive_omitted_patterns)] match src {
    "main" | "lib" | "mod" => true,
    _ => false,
}matches!(src, "main" | "lib" | "mod") {
2765            for file in [
2766                // …/x/y.rs
2767                dir.join(src).join(i).with_extension("rs"),
2768                // …/x/y/mod.rs
2769                dir.join(src).join(i).join("mod.rs"),
2770            ] {
2771                if file.exists() {
2772                    return Some(file);
2773                }
2774            }
2775        }
2776        None
2777    }
2778
2779    /// Adds suggestions for a path that cannot be resolved.
2780    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("make_path_suggestion",
                                    "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2780u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&["path"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Option<(Vec<Segment>, Option<String>)> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match path[..] {
                [first, second, ..] if
                    first.ident.name == kw::PathRoot &&
                        !second.ident.is_path_segment_keyword() => {}
                [first, ..] if
                    first.ident.span.at_least_rust_2018() &&
                        !first.ident.is_path_segment_keyword() => {
                    path.insert(0, Segment::from_ident(Ident::dummy()));
                }
                _ => return None,
            }
            self.make_missing_self_suggestion(path.clone(),
                            parent_scope).or_else(||
                            self.make_missing_crate_suggestion(path.clone(),
                                parent_scope)).or_else(||
                        self.make_missing_super_suggestion(path.clone(),
                            parent_scope)).or_else(||
                    self.make_external_crate_suggestion(path, parent_scope))
        }
    }
}#[instrument(level = "debug", skip(self, parent_scope))]
2781    pub(crate) fn make_path_suggestion(
2782        &mut self,
2783        mut path: Vec<Segment>,
2784        parent_scope: &ParentScope<'ra>,
2785    ) -> Option<(Vec<Segment>, Option<String>)> {
2786        match path[..] {
2787            // `{{root}}::ident::...` on both editions.
2788            // On 2015 `{{root}}` is usually added implicitly.
2789            [first, second, ..]
2790                if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2791            // `ident::...` on 2018.
2792            [first, ..]
2793                if first.ident.span.at_least_rust_2018()
2794                    && !first.ident.is_path_segment_keyword() =>
2795            {
2796                // Insert a placeholder that's later replaced by `self`/`super`/etc.
2797                path.insert(0, Segment::from_ident(Ident::dummy()));
2798            }
2799            _ => return None,
2800        }
2801
2802        self.make_missing_self_suggestion(path.clone(), parent_scope)
2803            .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2804            .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2805            .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2806    }
2807
2808    /// Suggest a missing `self::` if that resolves to an correct module.
2809    ///
2810    /// ```text
2811    ///    |
2812    /// LL | use foo::Bar;
2813    ///    |     ^^^ did you mean `self::foo`?
2814    /// ```
2815    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("make_missing_self_suggestion",
                                    "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2815u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&["path"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Option<(Vec<Segment>, Option<String>)> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            path[0].ident.name = kw::SelfLower;
            let result =
                self.cm().maybe_resolve_path(&path, None, parent_scope, None);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2824",
                                    "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2824u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&["path", "result"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&path) as
                                                        &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&result) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            if let PathResult::Module(..) = result {
                Some((path, None))
            } else { None }
        }
    }
}#[instrument(level = "debug", skip(self, parent_scope))]
2816    fn make_missing_self_suggestion(
2817        &mut self,
2818        mut path: Vec<Segment>,
2819        parent_scope: &ParentScope<'ra>,
2820    ) -> Option<(Vec<Segment>, Option<String>)> {
2821        // Replace first ident with `self` and check if that is valid.
2822        path[0].ident.name = kw::SelfLower;
2823        let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2824        debug!(?path, ?result);
2825        if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2826    }
2827
2828    /// Suggests a missing `crate::` if that resolves to an correct module.
2829    ///
2830    /// ```text
2831    ///    |
2832    /// LL | use foo::Bar;
2833    ///    |     ^^^ did you mean `crate::foo`?
2834    /// ```
2835    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("make_missing_crate_suggestion",
                                    "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2835u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&["path"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Option<(Vec<Segment>, Option<String>)> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            path[0].ident.name = kw::Crate;
            let result =
                self.cm().maybe_resolve_path(&path, None, parent_scope, None);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2844",
                                    "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2844u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&["path", "result"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&path) as
                                                        &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&result) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            if let PathResult::Module(..) = result {
                Some((path,
                        Some("`use` statements changed in Rust 2018; read more at \
                     <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
                     clarity.html>".to_string())))
            } else { None }
        }
    }
}#[instrument(level = "debug", skip(self, parent_scope))]
2836    fn make_missing_crate_suggestion(
2837        &mut self,
2838        mut path: Vec<Segment>,
2839        parent_scope: &ParentScope<'ra>,
2840    ) -> Option<(Vec<Segment>, Option<String>)> {
2841        // Replace first ident with `crate` and check if that is valid.
2842        path[0].ident.name = kw::Crate;
2843        let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2844        debug!(?path, ?result);
2845        if let PathResult::Module(..) = result {
2846            Some((
2847                path,
2848                Some(
2849                    "`use` statements changed in Rust 2018; read more at \
2850                     <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2851                     clarity.html>"
2852                        .to_string(),
2853                ),
2854            ))
2855        } else {
2856            None
2857        }
2858    }
2859
2860    /// Suggests a missing `super::` if that resolves to an correct module.
2861    ///
2862    /// ```text
2863    ///    |
2864    /// LL | use foo::Bar;
2865    ///    |     ^^^ did you mean `super::foo`?
2866    /// ```
2867    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("make_missing_super_suggestion",
                                    "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2867u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&["path"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Option<(Vec<Segment>, Option<String>)> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            path[0].ident.name = kw::Super;
            let result =
                self.cm().maybe_resolve_path(&path, None, parent_scope, None);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2876",
                                    "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2876u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&["path", "result"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&path) as
                                                        &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&result) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            if let PathResult::Module(..) = result {
                Some((path, None))
            } else { None }
        }
    }
}#[instrument(level = "debug", skip(self, parent_scope))]
2868    fn make_missing_super_suggestion(
2869        &mut self,
2870        mut path: Vec<Segment>,
2871        parent_scope: &ParentScope<'ra>,
2872    ) -> Option<(Vec<Segment>, Option<String>)> {
2873        // Replace first ident with `crate` and check if that is valid.
2874        path[0].ident.name = kw::Super;
2875        let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2876        debug!(?path, ?result);
2877        if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2878    }
2879
2880    /// Suggests a missing external crate name if that resolves to an correct module.
2881    ///
2882    /// ```text
2883    ///    |
2884    /// LL | use foobar::Baz;
2885    ///    |     ^^^^^^ did you mean `baz::foobar`?
2886    /// ```
2887    ///
2888    /// Used when importing a submodule of an external crate but missing that crate's
2889    /// name as the first part of path.
2890    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("make_external_crate_suggestion",
                                    "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2890u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&["path"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Option<(Vec<Segment>, Option<String>)> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if path[1].ident.span.is_rust_2015() { return None; }
            let mut extern_crate_names =
                self.extern_prelude.keys().map(|ident|
                            ident.name).collect::<Vec<_>>();
            extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
            for name in extern_crate_names.into_iter() {
                path[0].ident.name = name;
                let result =
                    self.cm().maybe_resolve_path(&path, None, parent_scope,
                        None);
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2911",
                                        "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                                        ::tracing_core::__macro_support::Option::Some(2911u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                                        ::tracing_core::field::FieldSet::new(&["path", "name",
                                                        "result"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&path) as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&name) as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&result) as
                                                            &dyn Value))])
                            });
                    } else { ; }
                };
                if let PathResult::Module(..) = result {
                    return Some((path, None));
                }
            }
            None
        }
    }
}#[instrument(level = "debug", skip(self, parent_scope))]
2891    fn make_external_crate_suggestion(
2892        &mut self,
2893        mut path: Vec<Segment>,
2894        parent_scope: &ParentScope<'ra>,
2895    ) -> Option<(Vec<Segment>, Option<String>)> {
2896        if path[1].ident.span.is_rust_2015() {
2897            return None;
2898        }
2899
2900        // Sort extern crate names in *reverse* order to get
2901        // 1) some consistent ordering for emitted diagnostics, and
2902        // 2) `std` suggestions before `core` suggestions.
2903        let mut extern_crate_names =
2904            self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2905        extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
2906
2907        for name in extern_crate_names.into_iter() {
2908            // Replace first ident with a crate name and check if that is valid.
2909            path[0].ident.name = name;
2910            let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2911            debug!(?path, ?name, ?result);
2912            if let PathResult::Module(..) = result {
2913                return Some((path, None));
2914            }
2915        }
2916
2917        None
2918    }
2919
2920    /// Suggests importing a macro from the root of the crate rather than a module within
2921    /// the crate.
2922    ///
2923    /// ```text
2924    /// help: a macro with this name exists at the root of the crate
2925    ///    |
2926    /// LL | use issue_59764::makro;
2927    ///    |     ^^^^^^^^^^^^^^^^^^
2928    ///    |
2929    ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
2930    ///            at the root of the crate instead of the module where it is defined
2931    /// ```
2932    pub(crate) fn check_for_module_export_macro(
2933        &mut self,
2934        import: Import<'ra>,
2935        module: ModuleOrUniformRoot<'ra>,
2936        ident: Ident,
2937    ) -> Option<(Option<Suggestion>, Option<String>)> {
2938        let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2939            return None;
2940        };
2941
2942        while let Some(parent) = crate_module.parent {
2943            crate_module = parent;
2944        }
2945
2946        if module == ModuleOrUniformRoot::Module(crate_module) {
2947            // Don't make a suggestion if the import was already from the root of the crate.
2948            return None;
2949        }
2950
2951        let binding_key = BindingKey::new(IdentKey::new(ident), MacroNS);
2952        let binding = self.resolution(crate_module, binding_key)?.binding()?;
2953        let Res::Def(DefKind::Macro(kinds), _) = binding.res() else {
2954            return None;
2955        };
2956        if !kinds.contains(MacroKinds::BANG) {
2957            return None;
2958        }
2959        let module_name = crate_module.kind.name().unwrap_or(kw::Crate);
2960        let import_snippet = match import.kind {
2961            ImportKind::Single { source, target, .. } if source != target => {
2962                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} as {1}", source, target))
    })format!("{source} as {target}")
2963            }
2964            _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", ident))
    })format!("{ident}"),
2965        };
2966
2967        let mut corrections: Vec<(Span, String)> = Vec::new();
2968        if !import.is_nested() {
2969            // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2970            // intermediate segments.
2971            corrections.push((import.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{1}", module_name,
                import_snippet))
    })format!("{module_name}::{import_snippet}")));
2972        } else {
2973            // Find the binding span (and any trailing commas and spaces).
2974            //   ie. `use a::b::{c, d, e};`
2975            //                      ^^^
2976            let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2977                self.tcx.sess,
2978                import.span,
2979                import.use_span,
2980            );
2981            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2981",
                        "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(2981u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["found_closing_brace",
                                        "binding_span"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&found_closing_brace
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&binding_span)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(found_closing_brace, ?binding_span);
2982
2983            let mut removal_span = binding_span;
2984
2985            // If the binding span ended with a closing brace, as in the below example:
2986            //   ie. `use a::b::{c, d};`
2987            //                      ^
2988            // Then expand the span of characters to remove to include the previous
2989            // binding's trailing comma.
2990            //   ie. `use a::b::{c, d};`
2991            //                    ^^^
2992            if found_closing_brace
2993                && let Some(previous_span) =
2994                    extend_span_to_previous_binding(self.tcx.sess, binding_span)
2995            {
2996                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2996",
                        "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(2996u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["previous_span"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&previous_span)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?previous_span);
2997                removal_span = removal_span.with_lo(previous_span.lo());
2998            }
2999            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2999",
                        "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(2999u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["removal_span"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&removal_span)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?removal_span);
3000
3001            // Remove the `removal_span`.
3002            corrections.push((removal_span, "".to_string()));
3003
3004            // Find the span after the crate name and if it has nested imports immediately
3005            // after the crate name already.
3006            //   ie. `use a::b::{c, d};`
3007            //               ^^^^^^^^^
3008            //   or  `use a::{b, c, d}};`
3009            //               ^^^^^^^^^^^
3010            let (has_nested, after_crate_name) =
3011                find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
3012            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:3012",
                        "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(3012u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["has_nested",
                                        "after_crate_name"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&has_nested as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&after_crate_name)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(has_nested, ?after_crate_name);
3013
3014            let source_map = self.tcx.sess.source_map();
3015
3016            // Make sure this is actually crate-relative.
3017            let is_definitely_crate = import
3018                .module_path
3019                .first()
3020                .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
3021
3022            // Add the import to the start, with a `{` if required.
3023            let start_point = source_map.start_point(after_crate_name);
3024            if is_definitely_crate
3025                && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
3026            {
3027                corrections.push((
3028                    start_point,
3029                    if has_nested {
3030                        // In this case, `start_snippet` must equal '{'.
3031                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}, ", start_snippet,
                import_snippet))
    })format!("{start_snippet}{import_snippet}, ")
3032                    } else {
3033                        // In this case, add a `{`, then the moved import, then whatever
3034                        // was there before.
3035                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}, {1}", import_snippet,
                start_snippet))
    })format!("{{{import_snippet}, {start_snippet}")
3036                    },
3037                ));
3038
3039                // Add a `};` to the end if nested, matching the `{` added at the start.
3040                if !has_nested {
3041                    corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
3042                }
3043            } else {
3044                // If the root import is module-relative, add the import separately
3045                corrections.push((
3046                    import.use_span.shrink_to_lo(),
3047                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use {0}::{1};\n", module_name,
                import_snippet))
    })format!("use {module_name}::{import_snippet};\n"),
3048                ));
3049            }
3050        }
3051
3052        let suggestion = Some((
3053            corrections,
3054            String::from("a macro with this name exists at the root of the crate"),
3055            Applicability::MaybeIncorrect,
3056        ));
3057        Some((
3058            suggestion,
3059            Some(
3060                "this could be because a macro annotated with `#[macro_export]` will be exported \
3061            at the root of the crate instead of the module where it is defined"
3062                    .to_string(),
3063            ),
3064        ))
3065    }
3066
3067    /// Finds a cfg-ed out item inside `module` with the matching name.
3068    pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
3069        let local_items;
3070        let symbols = if module.is_local() {
3071            local_items = self
3072                .stripped_cfg_items
3073                .iter()
3074                .filter_map(|item| {
3075                    let parent_module = self.opt_local_def_id(item.parent_module)?.to_def_id();
3076                    Some(StrippedCfgItem {
3077                        parent_module,
3078                        ident: item.ident,
3079                        cfg: item.cfg.clone(),
3080                    })
3081                })
3082                .collect::<Vec<_>>();
3083            local_items.as_slice()
3084        } else {
3085            self.tcx.stripped_cfg_items(module.krate)
3086        };
3087
3088        for &StrippedCfgItem { parent_module, ident, ref cfg } in symbols {
3089            if ident.name != *segment {
3090                continue;
3091            }
3092
3093            fn comes_from_same_module_for_glob(
3094                r: &Resolver<'_, '_>,
3095                parent_module: DefId,
3096                module: DefId,
3097                visited: &mut FxHashMap<DefId, bool>,
3098            ) -> bool {
3099                if let Some(&cached) = visited.get(&parent_module) {
3100                    // this branch is prevent from being called recursively infinity,
3101                    // because there has some cycles in globs imports,
3102                    // see more spec case at `tests/ui/cfg/diagnostics-reexport-2.rs#reexport32`
3103                    return cached;
3104                }
3105                visited.insert(parent_module, false);
3106                let m = r.expect_module(parent_module);
3107                let mut res = false;
3108                for importer in m.glob_importers.borrow().iter() {
3109                    if let Some(next_parent_module) = importer.parent_scope.module.opt_def_id() {
3110                        if next_parent_module == module
3111                            || comes_from_same_module_for_glob(
3112                                r,
3113                                next_parent_module,
3114                                module,
3115                                visited,
3116                            )
3117                        {
3118                            res = true;
3119                            break;
3120                        }
3121                    }
3122                }
3123                visited.insert(parent_module, res);
3124                res
3125            }
3126
3127            let comes_from_same_module = parent_module == module
3128                || comes_from_same_module_for_glob(
3129                    self,
3130                    parent_module,
3131                    module,
3132                    &mut Default::default(),
3133                );
3134            if !comes_from_same_module {
3135                continue;
3136            }
3137
3138            let item_was = if let CfgEntry::NameValue { value: Some(feature), .. } = cfg.0 {
3139                errors::ItemWas::BehindFeature { feature, span: cfg.1 }
3140            } else {
3141                errors::ItemWas::CfgOut { span: cfg.1 }
3142            };
3143            let note = errors::FoundItemConfigureOut { span: ident.span, item_was };
3144            err.subdiagnostic(note);
3145        }
3146    }
3147}
3148
3149/// Given a `binding_span` of a binding within a use statement:
3150///
3151/// ```ignore (illustrative)
3152/// use foo::{a, b, c};
3153/// //           ^
3154/// ```
3155///
3156/// then return the span until the next binding or the end of the statement:
3157///
3158/// ```ignore (illustrative)
3159/// use foo::{a, b, c};
3160/// //           ^^^
3161/// ```
3162fn find_span_of_binding_until_next_binding(
3163    sess: &Session,
3164    binding_span: Span,
3165    use_span: Span,
3166) -> (bool, Span) {
3167    let source_map = sess.source_map();
3168
3169    // Find the span of everything after the binding.
3170    //   ie. `a, e};` or `a};`
3171    let binding_until_end = binding_span.with_hi(use_span.hi());
3172
3173    // Find everything after the binding but not including the binding.
3174    //   ie. `, e};` or `};`
3175    let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
3176
3177    // Keep characters in the span until we encounter something that isn't a comma or
3178    // whitespace.
3179    //   ie. `, ` or ``.
3180    //
3181    // Also note whether a closing brace character was encountered. If there
3182    // was, then later go backwards to remove any trailing commas that are left.
3183    let mut found_closing_brace = false;
3184    let after_binding_until_next_binding =
3185        source_map.span_take_while(after_binding_until_end, |&ch| {
3186            if ch == '}' {
3187                found_closing_brace = true;
3188            }
3189            ch == ' ' || ch == ','
3190        });
3191
3192    // Combine the two spans.
3193    //   ie. `a, ` or `a`.
3194    //
3195    // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
3196    let span = binding_span.with_hi(after_binding_until_next_binding.hi());
3197
3198    (found_closing_brace, span)
3199}
3200
3201/// Given a `binding_span`, return the span through to the comma or opening brace of the previous
3202/// binding.
3203///
3204/// ```ignore (illustrative)
3205/// use foo::a::{a, b, c};
3206/// //            ^^--- binding span
3207/// //            |
3208/// //            returned span
3209///
3210/// use foo::{a, b, c};
3211/// //        --- binding span
3212/// ```
3213fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
3214    let source_map = sess.source_map();
3215
3216    // `prev_source` will contain all of the source that came before the span.
3217    // Then split based on a command and take the first (ie. closest to our span)
3218    // snippet. In the example, this is a space.
3219    let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
3220
3221    let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
3222    let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
3223    if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
3224        return None;
3225    }
3226
3227    let prev_comma = prev_comma.first().unwrap();
3228    let prev_starting_brace = prev_starting_brace.first().unwrap();
3229
3230    // If the amount of source code before the comma is greater than
3231    // the amount of source code before the starting brace then we've only
3232    // got one item in the nested item (eg. `issue_52891::{self}`).
3233    if prev_comma.len() > prev_starting_brace.len() {
3234        return None;
3235    }
3236
3237    Some(binding_span.with_lo(BytePos(
3238        // Take away the number of bytes for the characters we've found and an
3239        // extra for the comma.
3240        binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
3241    )))
3242}
3243
3244/// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
3245/// it is a nested use tree.
3246///
3247/// ```ignore (illustrative)
3248/// use foo::a::{b, c};
3249/// //       ^^^^^^^^^^ -- false
3250///
3251/// use foo::{a, b, c};
3252/// //       ^^^^^^^^^^ -- true
3253///
3254/// use foo::{a, b::{c, d}};
3255/// //       ^^^^^^^^^^^^^^^ -- true
3256/// ```
3257#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("find_span_immediately_after_crate_name",
                                    "rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3257u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&["use_span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: (bool, Span) = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let source_map = sess.source_map();
            let mut num_colons = 0;
            let until_second_colon =
                source_map.span_take_while(use_span,
                    |c|
                        {
                            if *c == ':' { num_colons += 1; }
                            !#[allow(non_exhaustive_omitted_patterns)] match c {
                                    ':' if num_colons == 2 => true,
                                    _ => false,
                                }
                        });
            let from_second_colon =
                use_span.with_lo(until_second_colon.hi() + BytePos(1));
            let mut found_a_non_whitespace_character = false;
            let after_second_colon =
                source_map.span_take_while(from_second_colon,
                    |c|
                        {
                            if found_a_non_whitespace_character { return false; }
                            if !c.is_whitespace() {
                                found_a_non_whitespace_character = true;
                            }
                            true
                        });
            let next_left_bracket =
                source_map.span_through_char(from_second_colon, '{');
            (next_left_bracket == after_second_colon, from_second_colon)
        }
    }
}#[instrument(level = "debug", skip(sess))]
3258fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
3259    let source_map = sess.source_map();
3260
3261    // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
3262    let mut num_colons = 0;
3263    // Find second colon.. `use issue_59764:`
3264    let until_second_colon = source_map.span_take_while(use_span, |c| {
3265        if *c == ':' {
3266            num_colons += 1;
3267        }
3268        !matches!(c, ':' if num_colons == 2)
3269    });
3270    // Find everything after the second colon.. `foo::{baz, makro};`
3271    let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
3272
3273    let mut found_a_non_whitespace_character = false;
3274    // Find the first non-whitespace character in `from_second_colon`.. `f`
3275    let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
3276        if found_a_non_whitespace_character {
3277            return false;
3278        }
3279        if !c.is_whitespace() {
3280            found_a_non_whitespace_character = true;
3281        }
3282        true
3283    });
3284
3285    // Find the first `{` in from_second_colon.. `foo::{`
3286    let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
3287
3288    (next_left_bracket == after_second_colon, from_second_colon)
3289}
3290
3291/// A suggestion has already been emitted, change the wording slightly to clarify that both are
3292/// independent options.
3293enum Instead {
3294    Yes,
3295    No,
3296}
3297
3298/// Whether an existing place with an `use` item was found.
3299enum FoundUse {
3300    Yes,
3301    No,
3302}
3303
3304/// Whether a binding is part of a pattern or a use statement. Used for diagnostics.
3305pub(crate) enum DiagMode {
3306    Normal,
3307    /// The binding is part of a pattern
3308    Pattern,
3309    /// The binding is part of a use statement
3310    Import {
3311        /// `true` means diagnostics is for unresolved import
3312        unresolved_import: bool,
3313        /// `true` mean add the tips afterward for case `use a::{b,c}`,
3314        /// rather than replacing within.
3315        append: bool,
3316    },
3317}
3318
3319pub(crate) fn import_candidates(
3320    tcx: TyCtxt<'_>,
3321    err: &mut Diag<'_>,
3322    // This is `None` if all placement locations are inside expansions
3323    use_placement_span: Option<Span>,
3324    candidates: &[ImportSuggestion],
3325    mode: DiagMode,
3326    append: &str,
3327) {
3328    show_candidates(
3329        tcx,
3330        err,
3331        use_placement_span,
3332        candidates,
3333        Instead::Yes,
3334        FoundUse::Yes,
3335        mode,
3336        ::alloc::vec::Vec::new()vec![],
3337        append,
3338    );
3339}
3340
3341type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
3342
3343/// When an entity with a given name is not available in scope, we search for
3344/// entities with that name in all crates. This method allows outputting the
3345/// results of this search in a programmer-friendly way. If any entities are
3346/// found and suggested, returns `true`, otherwise returns `false`.
3347fn show_candidates(
3348    tcx: TyCtxt<'_>,
3349    err: &mut Diag<'_>,
3350    // This is `None` if all placement locations are inside expansions
3351    use_placement_span: Option<Span>,
3352    candidates: &[ImportSuggestion],
3353    instead: Instead,
3354    found_use: FoundUse,
3355    mode: DiagMode,
3356    path: Vec<Segment>,
3357    append: &str,
3358) -> bool {
3359    if candidates.is_empty() {
3360        return false;
3361    }
3362
3363    let mut showed = false;
3364    let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
3365    let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
3366
3367    candidates.iter().for_each(|c| {
3368        if c.accessible {
3369            // Don't suggest `#[doc(hidden)]` items from other crates
3370            if c.doc_visible {
3371                accessible_path_strings.push((
3372                    pprust::path_to_string(&c.path),
3373                    c.descr,
3374                    c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3375                    &c.note,
3376                    c.via_import,
3377                ))
3378            }
3379        } else {
3380            inaccessible_path_strings.push((
3381                pprust::path_to_string(&c.path),
3382                c.descr,
3383                c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3384                &c.note,
3385                c.via_import,
3386            ))
3387        }
3388    });
3389
3390    // we want consistent results across executions, but candidates are produced
3391    // by iterating through a hash map, so make sure they are ordered:
3392    for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
3393        path_strings.sort_by(|a, b| a.0.cmp(&b.0));
3394        path_strings.dedup_by(|a, b| a.0 == b.0);
3395        let core_path_strings =
3396            path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
3397        let std_path_strings =
3398            path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
3399        let foreign_crate_path_strings =
3400            path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
3401
3402        // We list the `crate` local paths first.
3403        // Then we list the `std`/`core` paths.
3404        if std_path_strings.len() == core_path_strings.len() {
3405            // Do not list `core::` paths if we are already listing the `std::` ones.
3406            path_strings.extend(std_path_strings);
3407        } else {
3408            path_strings.extend(std_path_strings);
3409            path_strings.extend(core_path_strings);
3410        }
3411        // List all paths from foreign crates last.
3412        path_strings.extend(foreign_crate_path_strings);
3413    }
3414
3415    if !accessible_path_strings.is_empty() {
3416        let (determiner, kind, s, name, through) =
3417            if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
3418                (
3419                    "this",
3420                    *descr,
3421                    "",
3422                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" `{0}`", name))
    })format!(" `{name}`"),
3423                    if *via_import { " through its public re-export" } else { "" },
3424                )
3425            } else {
3426                // Get the unique item kinds and if there's only one, we use the right kind name
3427                // instead of the more generic "items".
3428                let kinds = accessible_path_strings
3429                    .iter()
3430                    .map(|(_, descr, _, _, _)| *descr)
3431                    .collect::<UnordSet<&str>>();
3432                let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
3433                let s = if kind.ends_with('s') { "es" } else { "s" };
3434
3435                ("one of these", kind, s, String::new(), "")
3436            };
3437
3438        let instead = if let Instead::Yes = instead { " instead" } else { "" };
3439        let mut msg = if let DiagMode::Pattern = mode {
3440            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you meant to match on {0}{1}{2}{3}, use the full path in the pattern",
                kind, s, instead, name))
    })format!(
3441                "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
3442                 pattern",
3443            )
3444        } else {
3445            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider importing {0} {1}{2}{3}{4}",
                determiner, kind, s, through, instead))
    })format!("consider importing {determiner} {kind}{s}{through}{instead}")
3446        };
3447
3448        for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3449            err.note(note.clone());
3450        }
3451
3452        let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
3453            msg.push(':');
3454
3455            for candidate in accessible_path_strings {
3456                msg.push('\n');
3457                msg.push_str(&candidate.0);
3458            }
3459        };
3460
3461        if let Some(span) = use_placement_span {
3462            let (add_use, trailing) = match mode {
3463                DiagMode::Pattern => {
3464                    err.span_suggestions(
3465                        span,
3466                        msg,
3467                        accessible_path_strings.into_iter().map(|a| a.0),
3468                        Applicability::MaybeIncorrect,
3469                    );
3470                    return true;
3471                }
3472                DiagMode::Import { .. } => ("", ""),
3473                DiagMode::Normal => ("use ", ";\n"),
3474            };
3475            for candidate in &mut accessible_path_strings {
3476                // produce an additional newline to separate the new use statement
3477                // from the directly following item.
3478                let additional_newline = if let FoundUse::No = found_use
3479                    && let DiagMode::Normal = mode
3480                {
3481                    "\n"
3482                } else {
3483                    ""
3484                };
3485                candidate.0 =
3486                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{0}{2}{3}{4}", candidate.0,
                add_use, append, trailing, additional_newline))
    })format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
3487            }
3488
3489            match mode {
3490                DiagMode::Import { append: true, .. } => {
3491                    append_candidates(&mut msg, accessible_path_strings);
3492                    err.span_help(span, msg);
3493                }
3494                _ => {
3495                    err.span_suggestions_with_style(
3496                        span,
3497                        msg,
3498                        accessible_path_strings.into_iter().map(|a| a.0),
3499                        Applicability::MaybeIncorrect,
3500                        SuggestionStyle::ShowAlways,
3501                    );
3502                }
3503            }
3504
3505            if let [first, .., last] = &path[..] {
3506                let sp = first.ident.span.until(last.ident.span);
3507                // Our suggestion is empty, so make sure the span is not empty (or we'd ICE).
3508                // Can happen for derive-generated spans.
3509                if sp.can_be_used_for_suggestions() && !sp.is_empty() {
3510                    err.span_suggestion_verbose(
3511                        sp,
3512                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you import `{0}`, refer to it directly",
                last.ident))
    })format!("if you import `{}`, refer to it directly", last.ident),
3513                        "",
3514                        Applicability::Unspecified,
3515                    );
3516                }
3517            }
3518        } else {
3519            append_candidates(&mut msg, accessible_path_strings);
3520            err.help(msg);
3521        }
3522        showed = true;
3523    }
3524    if !inaccessible_path_strings.is_empty()
3525        && (!#[allow(non_exhaustive_omitted_patterns)] match mode {
    DiagMode::Import { unresolved_import: false, .. } => true,
    _ => false,
}matches!(mode, DiagMode::Import { unresolved_import: false, .. }))
3526    {
3527        let prefix =
3528            if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
3529        if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
3530            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{2} `{3}`{0} exists but is inaccessible",
                if let DiagMode::Pattern = mode { ", which" } else { "" },
                prefix, descr, name))
    })format!(
3531                "{prefix}{descr} `{name}`{} exists but is inaccessible",
3532                if let DiagMode::Pattern = mode { ", which" } else { "" }
3533            );
3534
3535            if let Some(source_span) = source_span {
3536                let span = tcx.sess.source_map().guess_head_span(*source_span);
3537                let mut multi_span = MultiSpan::from_span(span);
3538                multi_span.push_span_label(span, "not accessible");
3539                err.span_note(multi_span, msg);
3540            } else {
3541                err.note(msg);
3542            }
3543            if let Some(note) = (*note).as_deref() {
3544                err.note(note.to_string());
3545            }
3546        } else {
3547            let descr = inaccessible_path_strings
3548                .iter()
3549                .map(|&(_, descr, _, _, _)| descr)
3550                .all_equal_value()
3551                .unwrap_or("item");
3552            let plural_descr =
3553                if descr.ends_with('s') { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}es", descr))
    })format!("{descr}es") } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}s", descr))
    })format!("{descr}s") };
3554
3555            let mut msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}these {1} exist but are inaccessible",
                prefix, plural_descr))
    })format!("{prefix}these {plural_descr} exist but are inaccessible");
3556            let mut has_colon = false;
3557
3558            let mut spans = Vec::new();
3559            for (name, _, source_span, _, _) in &inaccessible_path_strings {
3560                if let Some(source_span) = source_span {
3561                    let span = tcx.sess.source_map().guess_head_span(*source_span);
3562                    spans.push((name, span));
3563                } else {
3564                    if !has_colon {
3565                        msg.push(':');
3566                        has_colon = true;
3567                    }
3568                    msg.push('\n');
3569                    msg.push_str(name);
3570                }
3571            }
3572
3573            let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3574            for (name, span) in spans {
3575                multi_span.push_span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`: not accessible", name))
    })format!("`{name}`: not accessible"));
3576            }
3577
3578            for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3579                err.note(note.clone());
3580            }
3581
3582            err.span_note(multi_span, msg);
3583        }
3584        showed = true;
3585    }
3586    showed
3587}
3588
3589#[derive(#[automatically_derived]
impl ::core::fmt::Debug for UsePlacementFinder {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "UsePlacementFinder", "target_module", &self.target_module,
            "first_legal_span", &self.first_legal_span, "first_use_span",
            &&self.first_use_span)
    }
}Debug)]
3590struct UsePlacementFinder {
3591    target_module: NodeId,
3592    first_legal_span: Option<Span>,
3593    first_use_span: Option<Span>,
3594}
3595
3596impl UsePlacementFinder {
3597    fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3598        let mut finder =
3599            UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3600        finder.visit_crate(krate);
3601        if let Some(use_span) = finder.first_use_span {
3602            (Some(use_span), FoundUse::Yes)
3603        } else {
3604            (finder.first_legal_span, FoundUse::No)
3605        }
3606    }
3607}
3608
3609impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
3610    fn visit_crate(&mut self, c: &Crate) {
3611        if self.target_module == CRATE_NODE_ID {
3612            let inject = c.spans.inject_use_span;
3613            if is_span_suitable_for_use_injection(inject) {
3614                self.first_legal_span = Some(inject);
3615            }
3616            self.first_use_span = search_for_any_use_in_items(&c.items);
3617        } else {
3618            visit::walk_crate(self, c);
3619        }
3620    }
3621
3622    fn visit_item(&mut self, item: &'tcx ast::Item) {
3623        if self.target_module == item.id {
3624            if let ItemKind::Mod(_, _, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
3625                let inject = mod_spans.inject_use_span;
3626                if is_span_suitable_for_use_injection(inject) {
3627                    self.first_legal_span = Some(inject);
3628                }
3629                self.first_use_span = search_for_any_use_in_items(items);
3630            }
3631        } else {
3632            visit::walk_item(self, item);
3633        }
3634    }
3635}
3636
3637#[derive(#[automatically_derived]
impl ::core::default::Default for BindingVisitor {
    #[inline]
    fn default() -> BindingVisitor {
        BindingVisitor {
            identifiers: ::core::default::Default::default(),
            spans: ::core::default::Default::default(),
        }
    }
}Default)]
3638struct BindingVisitor {
3639    identifiers: Vec<Symbol>,
3640    spans: FxHashMap<Symbol, Vec<Span>>,
3641}
3642
3643impl<'tcx> Visitor<'tcx> for BindingVisitor {
3644    fn visit_pat(&mut self, pat: &ast::Pat) {
3645        if let ast::PatKind::Ident(_, ident, _) = pat.kind {
3646            self.identifiers.push(ident.name);
3647            self.spans.entry(ident.name).or_default().push(ident.span);
3648        }
3649        visit::walk_pat(self, pat);
3650    }
3651}
3652
3653fn search_for_any_use_in_items(items: &[Box<ast::Item>]) -> Option<Span> {
3654    for item in items {
3655        if let ItemKind::Use(..) = item.kind
3656            && is_span_suitable_for_use_injection(item.span)
3657        {
3658            let mut lo = item.span.lo();
3659            for attr in &item.attrs {
3660                if attr.span.eq_ctxt(item.span) {
3661                    lo = std::cmp::min(lo, attr.span.lo());
3662                }
3663            }
3664            return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3665        }
3666    }
3667    None
3668}
3669
3670fn is_span_suitable_for_use_injection(s: Span) -> bool {
3671    // don't suggest placing a use before the prelude
3672    // import or other generated ones
3673    !s.from_expansion()
3674}