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