Skip to main content

rustc_resolve/
diagnostics.rs

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