Skip to main content

rustc_resolve/
diagnostics.rs

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