Skip to main content

rustc_resolve/diagnostics/
impls.rs

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