Skip to main content

rustc_resolve/
diagnostics.rs

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