rustc_resolve/
diagnostics.rs

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