rustc_resolve/
diagnostics.rs

1use rustc_ast::expand::StrippedCfgItem;
2use rustc_ast::ptr::P;
3use rustc_ast::visit::{self, Visitor};
4use rustc_ast::{
5    self as ast, CRATE_NODE_ID, Crate, ItemKind, MetaItemInner, MetaItemKind, ModKind, NodeId, Path,
6};
7use rustc_ast_pretty::pprust;
8use rustc_data_structures::fx::FxHashSet;
9use rustc_data_structures::unord::UnordSet;
10use rustc_errors::codes::*;
11use rustc_errors::{
12    Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, MultiSpan, SuggestionStyle,
13    report_ambiguity_error, struct_span_code_err,
14};
15use rustc_feature::BUILTIN_ATTRIBUTES;
16use rustc_hir::PrimTy;
17use rustc_hir::def::Namespace::{self, *};
18use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS};
19use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
20use rustc_middle::bug;
21use rustc_middle::ty::TyCtxt;
22use rustc_session::Session;
23use rustc_session::lint::builtin::{
24    ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS,
25    MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
26};
27use rustc_session::lint::{AmbiguityErrorDiag, BuiltinLintDiag};
28use rustc_session::utils::was_invoked_from_cargo;
29use rustc_span::edit_distance::find_best_match_for_name;
30use rustc_span::edition::Edition;
31use rustc_span::hygiene::MacroKind;
32use rustc_span::source_map::SourceMap;
33use rustc_span::{BytePos, Ident, Span, Symbol, SyntaxContext, kw, sym};
34use thin_vec::{ThinVec, thin_vec};
35use tracing::{debug, instrument};
36
37use crate::errors::{
38    self, AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion, ConsiderAddingADerive,
39    ExplicitUnsafeTraits, MacroDefinedLater, MacroRulesNot, MacroSuggMovePosition,
40    MaybeMissingMacroRulesName,
41};
42use crate::imports::{Import, ImportKind};
43use crate::late::{PatternSource, Rib};
44use crate::{
45    AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, BindingKey, Finalize,
46    ForwardGenericParamBanReason, HasGenericParams, LexicalScopeBinding, MacroRulesScope, Module,
47    ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult,
48    PrivacyError, ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used,
49    VisResolutionError, errors as errs, path_names_to_string,
50};
51
52type Res = def::Res<ast::NodeId>;
53
54/// A vector of spans and replacements, a message and applicability.
55pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
56
57/// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
58/// similarly named label and whether or not it is reachable.
59pub(crate) type LabelSuggestion = (Ident, bool);
60
61#[derive(Debug)]
62pub(crate) enum SuggestionTarget {
63    /// The target has a similar name as the name used by the programmer (probably a typo)
64    SimilarlyNamed,
65    /// The target is the only valid item that can be used in the corresponding context
66    SingleItem,
67}
68
69#[derive(Debug)]
70pub(crate) struct TypoSuggestion {
71    pub candidate: Symbol,
72    /// The source location where the name is defined; None if the name is not defined
73    /// in source e.g. primitives
74    pub span: Option<Span>,
75    pub res: Res,
76    pub target: SuggestionTarget,
77}
78
79impl TypoSuggestion {
80    pub(crate) fn typo_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
81        Self {
82            candidate: ident.name,
83            span: Some(ident.span),
84            res,
85            target: SuggestionTarget::SimilarlyNamed,
86        }
87    }
88    pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
89        Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
90    }
91    pub(crate) fn single_item_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
92        Self {
93            candidate: ident.name,
94            span: Some(ident.span),
95            res,
96            target: SuggestionTarget::SingleItem,
97        }
98    }
99}
100
101/// A free importable items suggested in case of resolution failure.
102#[derive(Debug, Clone)]
103pub(crate) struct ImportSuggestion {
104    pub did: Option<DefId>,
105    pub descr: &'static str,
106    pub path: Path,
107    pub accessible: bool,
108    // false if the path traverses a foreign `#[doc(hidden)]` item.
109    pub doc_visible: bool,
110    pub via_import: bool,
111    /// An extra note that should be issued if this item is suggested
112    pub note: Option<String>,
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            self.use_injections.drain(..)
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.module()) {
235            (ValueNS, _) => "value",
236            (MacroNS, _) => "macro",
237            (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
238            (TypeNS, Some(module)) if module.is_normal() => "module",
239            (TypeNS, Some(module)) if module.is_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, name },
258            false => errors::NameDefinedMultipleTimeLabel::Redefined { span, name },
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 => errors::NameDefinedMultipleTimeOldBindingLabel::Import {
266                        span,
267                        name,
268                        old_kind,
269                    },
270                    false => errors::NameDefinedMultipleTimeOldBindingLabel::Definition {
271                        span,
272                        name,
273                        old_kind,
274                    },
275                }
276            });
277
278        let mut err = self
279            .dcx()
280            .create_err(errors::NameDefinedMultipleTime {
281                span,
282                descr: ns.descr(),
283                container,
284                label,
285                old_binding_label,
286            })
287            .with_code(code);
288
289        // See https://github.com/rust-lang/rust/issues/32354
290        use NameBindingKind::Import;
291        let can_suggest = |binding: NameBinding<'_>, import: self::Import<'_>| {
292            !binding.span.is_dummy()
293                && !matches!(import.kind, ImportKind::MacroUse { .. } | ImportKind::MacroExport)
294        };
295        let import = match (&new_binding.kind, &old_binding.kind) {
296            // If there are two imports where one or both have attributes then prefer removing the
297            // import without attributes.
298            (Import { import: new, .. }, Import { import: old, .. })
299                if {
300                    (new.has_attributes || old.has_attributes)
301                        && can_suggest(old_binding, *old)
302                        && can_suggest(new_binding, *new)
303                } =>
304            {
305                if old.has_attributes {
306                    Some((*new, new_binding.span, true))
307                } else {
308                    Some((*old, old_binding.span, true))
309                }
310            }
311            // Otherwise prioritize the new binding.
312            (Import { import, .. }, other) if can_suggest(new_binding, *import) => {
313                Some((*import, new_binding.span, other.is_import()))
314            }
315            (other, Import { import, .. }) if can_suggest(old_binding, *import) => {
316                Some((*import, old_binding.span, other.is_import()))
317            }
318            _ => None,
319        };
320
321        // Check if the target of the use for both bindings is the same.
322        let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
323        let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
324        let from_item =
325            self.extern_prelude.get(&ident).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: Option<Finalize>,
472        path: &[Segment],
473        second_binding: Option<NameBinding<'_>>,
474    ) {
475        let Some(Finalize { node_id, root_span, .. }) = finalize else {
476            return;
477        };
478
479        let first_name = match path.get(0) {
480            // In the 2018 edition this lint is a hard error, so nothing to do
481            Some(seg) if seg.ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015() => {
482                seg.ident.name
483            }
484            _ => return,
485        };
486
487        // We're only interested in `use` paths which should start with
488        // `{{root}}` currently.
489        if first_name != kw::PathRoot {
490            return;
491        }
492
493        match path.get(1) {
494            // If this import looks like `crate::...` it's already good
495            Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
496            // Otherwise go below to see if it's an extern crate
497            Some(_) => {}
498            // If the path has length one (and it's `PathRoot` most likely)
499            // then we don't know whether we're gonna be importing a crate or an
500            // item in our crate. Defer this lint to elsewhere
501            None => return,
502        }
503
504        // If the first element of our path was actually resolved to an
505        // `ExternCrate` (also used for `crate::...`) then no need to issue a
506        // warning, this looks all good!
507        if let Some(binding) = second_binding
508            && let NameBindingKind::Import { import, .. } = binding.kind
509            // Careful: we still want to rewrite paths from renamed extern crates.
510            && let ImportKind::ExternCrate { source: None, .. } = import.kind
511        {
512            return;
513        }
514
515        let diag = BuiltinLintDiag::AbsPathWithModule(root_span);
516        self.lint_buffer.buffer_lint(
517            ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
518            node_id,
519            root_span,
520            diag,
521        );
522    }
523
524    pub(crate) fn add_module_candidates(
525        &mut self,
526        module: Module<'ra>,
527        names: &mut Vec<TypoSuggestion>,
528        filter_fn: &impl Fn(Res) -> bool,
529        ctxt: Option<SyntaxContext>,
530    ) {
531        module.for_each_child(self, |_this, ident, _ns, binding| {
532            let res = binding.res();
533            if filter_fn(res) && ctxt.is_none_or(|ctxt| ctxt == ident.span.ctxt()) {
534                names.push(TypoSuggestion::typo_from_ident(ident, res));
535            }
536        });
537    }
538
539    /// Combines an error with provided span and emits it.
540    ///
541    /// This takes the error provided, combines it with the span and any additional spans inside the
542    /// error and emits it.
543    pub(crate) fn report_error(
544        &mut self,
545        span: Span,
546        resolution_error: ResolutionError<'ra>,
547    ) -> ErrorGuaranteed {
548        self.into_struct_error(span, resolution_error).emit()
549    }
550
551    pub(crate) fn into_struct_error(
552        &mut self,
553        span: Span,
554        resolution_error: ResolutionError<'ra>,
555    ) -> Diag<'_> {
556        match resolution_error {
557            ResolutionError::GenericParamsFromOuterItem(
558                outer_res,
559                has_generic_params,
560                def_kind,
561            ) => {
562                use errs::GenericParamsFromOuterItemLabel as Label;
563                let static_or_const = match def_kind {
564                    DefKind::Static { .. } => {
565                        Some(errs::GenericParamsFromOuterItemStaticOrConst::Static)
566                    }
567                    DefKind::Const => Some(errs::GenericParamsFromOuterItemStaticOrConst::Const),
568                    _ => None,
569                };
570                let is_self =
571                    matches!(outer_res, Res::SelfTyParam { .. } | Res::SelfTyAlias { .. });
572                let mut err = errs::GenericParamsFromOuterItem {
573                    span,
574                    label: None,
575                    refer_to_type_directly: None,
576                    sugg: None,
577                    static_or_const,
578                    is_self,
579                };
580
581                let sm = self.tcx.sess.source_map();
582                let def_id = match outer_res {
583                    Res::SelfTyParam { .. } => {
584                        err.label = Some(Label::SelfTyParam(span));
585                        return self.dcx().create_err(err);
586                    }
587                    Res::SelfTyAlias { alias_to: def_id, .. } => {
588                        err.label = Some(Label::SelfTyAlias(reduce_impl_span_to_impl_keyword(
589                            sm,
590                            self.def_span(def_id),
591                        )));
592                        err.refer_to_type_directly = Some(span);
593                        return self.dcx().create_err(err);
594                    }
595                    Res::Def(DefKind::TyParam, def_id) => {
596                        err.label = Some(Label::TyParam(self.def_span(def_id)));
597                        def_id
598                    }
599                    Res::Def(DefKind::ConstParam, def_id) => {
600                        err.label = Some(Label::ConstParam(self.def_span(def_id)));
601                        def_id
602                    }
603                    _ => {
604                        bug!(
605                            "GenericParamsFromOuterItem should only be used with \
606                            Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
607                            DefKind::ConstParam"
608                        );
609                    }
610                };
611
612                if let HasGenericParams::Yes(span) = has_generic_params {
613                    let name = self.tcx.item_name(def_id);
614                    let (span, snippet) = if span.is_empty() {
615                        let snippet = format!("<{name}>");
616                        (span, snippet)
617                    } else {
618                        let span = sm.span_through_char(span, '<').shrink_to_hi();
619                        let snippet = format!("{name}, ");
620                        (span, snippet)
621                    };
622                    err.sugg = Some(errs::GenericParamsFromOuterItemSugg { span, snippet });
623                }
624
625                self.dcx().create_err(err)
626            }
627            ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
628                .dcx()
629                .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
630            ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
631                self.dcx().create_err(errs::MethodNotMemberOfTrait {
632                    span,
633                    method,
634                    trait_,
635                    sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
636                        span: method.span,
637                        candidate: c,
638                    }),
639                })
640            }
641            ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
642                self.dcx().create_err(errs::TypeNotMemberOfTrait {
643                    span,
644                    type_,
645                    trait_,
646                    sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
647                        span: type_.span,
648                        candidate: c,
649                    }),
650                })
651            }
652            ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
653                self.dcx().create_err(errs::ConstNotMemberOfTrait {
654                    span,
655                    const_,
656                    trait_,
657                    sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
658                        span: const_.span,
659                        candidate: c,
660                    }),
661                })
662            }
663            ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
664                let BindingError { name, target, origin, could_be_path } = binding_error;
665
666                let target_sp = target.iter().copied().collect::<Vec<_>>();
667                let origin_sp = origin.iter().copied().collect::<Vec<_>>();
668
669                let msp = MultiSpan::from_spans(target_sp.clone());
670                let mut err = self
671                    .dcx()
672                    .create_err(errors::VariableIsNotBoundInAllPatterns { multispan: msp, name });
673                for sp in target_sp {
674                    err.subdiagnostic(errors::PatternDoesntBindName { span: sp, name });
675                }
676                for sp in origin_sp {
677                    err.subdiagnostic(errors::VariableNotInAllPatterns { span: sp });
678                }
679                if could_be_path {
680                    let import_suggestions = self.lookup_import_candidates(
681                        name,
682                        Namespace::ValueNS,
683                        &parent_scope,
684                        &|res: Res| {
685                            matches!(
686                                res,
687                                Res::Def(
688                                    DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
689                                        | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
690                                        | DefKind::Const
691                                        | DefKind::AssocConst,
692                                    _,
693                                )
694                            )
695                        },
696                    );
697
698                    if import_suggestions.is_empty() {
699                        let help_msg = format!(
700                            "if you meant to match on a variant or a `const` item, consider \
701                             making the path in the pattern qualified: `path::to::ModOrType::{name}`",
702                        );
703                        err.span_help(span, help_msg);
704                    }
705                    show_candidates(
706                        self.tcx,
707                        &mut err,
708                        Some(span),
709                        &import_suggestions,
710                        Instead::No,
711                        FoundUse::Yes,
712                        DiagMode::Pattern,
713                        vec![],
714                        "",
715                    );
716                }
717                err
718            }
719            ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
720                self.dcx().create_err(errs::VariableBoundWithDifferentMode {
721                    span,
722                    first_binding_span,
723                    variable_name,
724                })
725            }
726            ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
727                .dcx()
728                .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
729            ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
730                .dcx()
731                .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
732            ResolutionError::UndeclaredLabel { name, suggestion } => {
733                let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
734                {
735                    // A reachable label with a similar name exists.
736                    Some((ident, true)) => (
737                        (
738                            Some(errs::LabelWithSimilarNameReachable(ident.span)),
739                            Some(errs::TryUsingSimilarlyNamedLabel {
740                                span,
741                                ident_name: ident.name,
742                            }),
743                        ),
744                        None,
745                    ),
746                    // An unreachable label with a similar name exists.
747                    Some((ident, false)) => (
748                        (None, None),
749                        Some(errs::UnreachableLabelWithSimilarNameExists {
750                            ident_span: ident.span,
751                        }),
752                    ),
753                    // No similarly-named labels exist.
754                    None => ((None, None), None),
755                };
756                self.dcx().create_err(errs::UndeclaredLabel {
757                    span,
758                    name,
759                    sub_reachable,
760                    sub_reachable_suggestion,
761                    sub_unreachable,
762                })
763            }
764            ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
765                // None of the suggestions below would help with a case like `use self`.
766                let (suggestion, mpart_suggestion) = if root {
767                    (None, None)
768                } else {
769                    // use foo::bar::self        -> foo::bar
770                    // use foo::bar::self as abc -> foo::bar as abc
771                    let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
772
773                    // use foo::bar::self        -> foo::bar::{self}
774                    // use foo::bar::self as abc -> foo::bar::{self as abc}
775                    let mpart_suggestion = errs::SelfImportsOnlyAllowedWithinMultipartSuggestion {
776                        multipart_start: span_with_rename.shrink_to_lo(),
777                        multipart_end: span_with_rename.shrink_to_hi(),
778                    };
779                    (Some(suggestion), Some(mpart_suggestion))
780                };
781                self.dcx().create_err(errs::SelfImportsOnlyAllowedWithin {
782                    span,
783                    suggestion,
784                    mpart_suggestion,
785                })
786            }
787            ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
788                self.dcx().create_err(errs::SelfImportCanOnlyAppearOnceInTheList { span })
789            }
790            ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
791                self.dcx().create_err(errs::SelfImportOnlyInImportListWithNonEmptyPrefix { span })
792            }
793            ResolutionError::FailedToResolve { segment, label, suggestion, module } => {
794                let mut err =
795                    struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {label}");
796                err.span_label(span, label);
797
798                if let Some((suggestions, msg, applicability)) = suggestion {
799                    if suggestions.is_empty() {
800                        err.help(msg);
801                        return err;
802                    }
803                    err.multipart_suggestion(msg, suggestions, applicability);
804                }
805                if let Some(ModuleOrUniformRoot::Module(module)) = module
806                    && let Some(module) = module.opt_def_id()
807                    && let Some(segment) = segment
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    /// Lookup typo candidate in scope for a macro or import.
1020    fn early_lookup_typo_candidate(
1021        &mut self,
1022        scope_set: ScopeSet<'ra>,
1023        parent_scope: &ParentScope<'ra>,
1024        ident: Ident,
1025        filter_fn: &impl Fn(Res) -> bool,
1026    ) -> Option<TypoSuggestion> {
1027        let mut suggestions = Vec::new();
1028        let ctxt = ident.span.ctxt();
1029        self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
1030            match scope {
1031                Scope::DeriveHelpers(expn_id) => {
1032                    let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1033                    if filter_fn(res) {
1034                        suggestions.extend(
1035                            this.helper_attrs
1036                                .get(&expn_id)
1037                                .into_iter()
1038                                .flatten()
1039                                .map(|(ident, _)| TypoSuggestion::typo_from_ident(*ident, res)),
1040                        );
1041                    }
1042                }
1043                Scope::DeriveHelpersCompat => {
1044                    let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1045                    if filter_fn(res) {
1046                        for derive in parent_scope.derives {
1047                            let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1048                            let Ok((Some(ext), _)) = this.resolve_macro_path(
1049                                derive,
1050                                Some(MacroKind::Derive),
1051                                parent_scope,
1052                                false,
1053                                false,
1054                                None,
1055                            ) else {
1056                                continue;
1057                            };
1058                            suggestions.extend(
1059                                ext.helper_attrs
1060                                    .iter()
1061                                    .map(|name| TypoSuggestion::typo_from_name(*name, res)),
1062                            );
1063                        }
1064                    }
1065                }
1066                Scope::MacroRules(macro_rules_scope) => {
1067                    if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1068                        let res = macro_rules_binding.binding.res();
1069                        if filter_fn(res) {
1070                            suggestions.push(TypoSuggestion::typo_from_ident(
1071                                macro_rules_binding.ident,
1072                                res,
1073                            ))
1074                        }
1075                    }
1076                }
1077                Scope::CrateRoot => {
1078                    let root_ident = Ident::new(kw::PathRoot, ident.span);
1079                    let root_module = this.resolve_crate_root(root_ident);
1080                    this.add_module_candidates(root_module, &mut suggestions, filter_fn, None);
1081                }
1082                Scope::Module(module, _) => {
1083                    this.add_module_candidates(module, &mut suggestions, filter_fn, None);
1084                }
1085                Scope::MacroUsePrelude => {
1086                    suggestions.extend(this.macro_use_prelude.iter().filter_map(
1087                        |(name, binding)| {
1088                            let res = binding.res();
1089                            filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1090                        },
1091                    ));
1092                }
1093                Scope::BuiltinAttrs => {
1094                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1095                    if filter_fn(res) {
1096                        suggestions.extend(
1097                            BUILTIN_ATTRIBUTES
1098                                .iter()
1099                                .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1100                        );
1101                    }
1102                }
1103                Scope::ExternPrelude => {
1104                    suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1105                        let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1106                        filter_fn(res).then_some(TypoSuggestion::typo_from_ident(*ident, res))
1107                    }));
1108                }
1109                Scope::ToolPrelude => {
1110                    let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1111                    suggestions.extend(
1112                        this.registered_tools
1113                            .iter()
1114                            .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
1115                    );
1116                }
1117                Scope::StdLibPrelude => {
1118                    if let Some(prelude) = this.prelude {
1119                        let mut tmp_suggestions = Vec::new();
1120                        this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1121                        suggestions.extend(
1122                            tmp_suggestions
1123                                .into_iter()
1124                                .filter(|s| use_prelude.into() || this.is_builtin_macro(s.res)),
1125                        );
1126                    }
1127                }
1128                Scope::BuiltinTypes => {
1129                    suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1130                        let res = Res::PrimTy(*prim_ty);
1131                        filter_fn(res)
1132                            .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1133                    }))
1134                }
1135            }
1136
1137            None::<()>
1138        });
1139
1140        // Make sure error reporting is deterministic.
1141        suggestions.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
1142
1143        match find_best_match_for_name(
1144            &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1145            ident.name,
1146            None,
1147        ) {
1148            Some(found) if found != ident.name => {
1149                suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1150            }
1151            _ => None,
1152        }
1153    }
1154
1155    fn lookup_import_candidates_from_module<FilterFn>(
1156        &mut self,
1157        lookup_ident: Ident,
1158        namespace: Namespace,
1159        parent_scope: &ParentScope<'ra>,
1160        start_module: Module<'ra>,
1161        crate_path: ThinVec<ast::PathSegment>,
1162        filter_fn: FilterFn,
1163    ) -> Vec<ImportSuggestion>
1164    where
1165        FilterFn: Fn(Res) -> bool,
1166    {
1167        let mut candidates = Vec::new();
1168        let mut seen_modules = FxHashSet::default();
1169        let start_did = start_module.def_id();
1170        let mut worklist = vec![(
1171            start_module,
1172            ThinVec::<ast::PathSegment>::new(),
1173            true,
1174            start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
1175        )];
1176        let mut worklist_via_import = vec![];
1177
1178        while let Some((in_module, path_segments, accessible, doc_visible)) = match worklist.pop() {
1179            None => worklist_via_import.pop(),
1180            Some(x) => Some(x),
1181        } {
1182            let in_module_is_extern = !in_module.def_id().is_local();
1183            in_module.for_each_child(self, |this, ident, ns, name_binding| {
1184                // avoid non-importable candidates
1185                if !name_binding.is_importable()
1186                    // FIXME(import_trait_associated_functions): remove this when `import_trait_associated_functions` is stable
1187                    || name_binding.is_assoc_const_or_fn()
1188                        && !this.tcx.features().import_trait_associated_functions()
1189                {
1190                    return;
1191                }
1192
1193                if ident.name == kw::Underscore {
1194                    return;
1195                }
1196
1197                let child_accessible =
1198                    accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1199
1200                // do not venture inside inaccessible items of other crates
1201                if in_module_is_extern && !child_accessible {
1202                    return;
1203                }
1204
1205                let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1206
1207                // There is an assumption elsewhere that paths of variants are in the enum's
1208                // declaration and not imported. With this assumption, the variant component is
1209                // chopped and the rest of the path is assumed to be the enum's own path. For
1210                // errors where a variant is used as the type instead of the enum, this causes
1211                // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1212                if via_import && name_binding.is_possibly_imported_variant() {
1213                    return;
1214                }
1215
1216                // #90113: Do not count an inaccessible reexported item as a candidate.
1217                if let NameBindingKind::Import { binding, .. } = name_binding.kind
1218                    && this.is_accessible_from(binding.vis, parent_scope.module)
1219                    && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1220                {
1221                    return;
1222                }
1223
1224                let res = name_binding.res();
1225                let did = match res {
1226                    Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1227                    _ => res.opt_def_id(),
1228                };
1229                let child_doc_visible = doc_visible
1230                    && did.is_none_or(|did| did.is_local() || !this.tcx.is_doc_hidden(did));
1231
1232                // collect results based on the filter function
1233                // avoid suggesting anything from the same module in which we are resolving
1234                // avoid suggesting anything with a hygienic name
1235                if ident.name == lookup_ident.name
1236                    && ns == namespace
1237                    && in_module != parent_scope.module
1238                    && !ident.span.normalize_to_macros_2_0().from_expansion()
1239                    && filter_fn(res)
1240                {
1241                    // create the path
1242                    let mut segms = if lookup_ident.span.at_least_rust_2018() {
1243                        // crate-local absolute paths start with `crate::` in edition 2018
1244                        // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1245                        crate_path.clone()
1246                    } else {
1247                        ThinVec::new()
1248                    };
1249                    segms.append(&mut path_segments.clone());
1250
1251                    segms.push(ast::PathSegment::from_ident(ident));
1252                    let path = Path { span: name_binding.span, segments: segms, tokens: None };
1253
1254                    if child_accessible
1255                        // Remove invisible match if exists
1256                        && let Some(idx) = candidates
1257                            .iter()
1258                            .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1259                    {
1260                        candidates.remove(idx);
1261                    }
1262
1263                    if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1264                        // See if we're recommending TryFrom, TryInto, or FromIterator and add
1265                        // a note about editions
1266                        let note = if let Some(did) = did {
1267                            let requires_note = !did.is_local()
1268                                && this.tcx.get_attrs(did, sym::rustc_diagnostic_item).any(
1269                                    |attr| {
1270                                        [sym::TryInto, sym::TryFrom, sym::FromIterator]
1271                                            .map(|x| Some(x))
1272                                            .contains(&attr.value_str())
1273                                    },
1274                                );
1275
1276                            requires_note.then(|| {
1277                                format!(
1278                                    "'{}' is included in the prelude starting in Edition 2021",
1279                                    path_names_to_string(&path)
1280                                )
1281                            })
1282                        } else {
1283                            None
1284                        };
1285
1286                        candidates.push(ImportSuggestion {
1287                            did,
1288                            descr: res.descr(),
1289                            path,
1290                            accessible: child_accessible,
1291                            doc_visible: child_doc_visible,
1292                            note,
1293                            via_import,
1294                        });
1295                    }
1296                }
1297
1298                // collect submodules to explore
1299                if let Some(module) = name_binding.module() {
1300                    // form the path
1301                    let mut path_segments = path_segments.clone();
1302                    path_segments.push(ast::PathSegment::from_ident(ident));
1303
1304                    let alias_import = if let NameBindingKind::Import { import, .. } =
1305                        name_binding.kind
1306                        && let ImportKind::ExternCrate { source: Some(_), .. } = import.kind
1307                        && import.parent_scope.expansion == parent_scope.expansion
1308                    {
1309                        true
1310                    } else {
1311                        false
1312                    };
1313
1314                    let is_extern_crate_that_also_appears_in_prelude =
1315                        name_binding.is_extern_crate() && lookup_ident.span.at_least_rust_2018();
1316
1317                    if !is_extern_crate_that_also_appears_in_prelude || alias_import {
1318                        // add the module to the lookup
1319                        if seen_modules.insert(module.def_id()) {
1320                            if via_import { &mut worklist_via_import } else { &mut worklist }
1321                                .push((module, path_segments, child_accessible, child_doc_visible));
1322                        }
1323                    }
1324                }
1325            })
1326        }
1327
1328        // If only some candidates are accessible, take just them
1329        if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1330            candidates.retain(|x| x.accessible)
1331        }
1332
1333        candidates
1334    }
1335
1336    /// When name resolution fails, this method can be used to look up candidate
1337    /// entities with the expected name. It allows filtering them using the
1338    /// supplied predicate (which should be used to only accept the types of
1339    /// definitions expected, e.g., traits). The lookup spans across all crates.
1340    ///
1341    /// N.B., the method does not look into imports, but this is not a problem,
1342    /// since we report the definitions (thus, the de-aliased imports).
1343    pub(crate) fn lookup_import_candidates<FilterFn>(
1344        &mut self,
1345        lookup_ident: Ident,
1346        namespace: Namespace,
1347        parent_scope: &ParentScope<'ra>,
1348        filter_fn: FilterFn,
1349    ) -> Vec<ImportSuggestion>
1350    where
1351        FilterFn: Fn(Res) -> bool,
1352    {
1353        let crate_path = thin_vec![ast::PathSegment::from_ident(Ident::with_dummy_span(kw::Crate))];
1354        let mut suggestions = self.lookup_import_candidates_from_module(
1355            lookup_ident,
1356            namespace,
1357            parent_scope,
1358            self.graph_root,
1359            crate_path,
1360            &filter_fn,
1361        );
1362
1363        if lookup_ident.span.at_least_rust_2018() {
1364            for ident in self.extern_prelude.clone().into_keys() {
1365                if ident.span.from_expansion() {
1366                    // Idents are adjusted to the root context before being
1367                    // resolved in the extern prelude, so reporting this to the
1368                    // user is no help. This skips the injected
1369                    // `extern crate std` in the 2018 edition, which would
1370                    // otherwise cause duplicate suggestions.
1371                    continue;
1372                }
1373                let Some(crate_id) = self.crate_loader(|c| c.maybe_process_path_extern(ident.name))
1374                else {
1375                    continue;
1376                };
1377
1378                let crate_def_id = crate_id.as_def_id();
1379                let crate_root = self.expect_module(crate_def_id);
1380
1381                // Check if there's already an item in scope with the same name as the crate.
1382                // If so, we have to disambiguate the potential import suggestions by making
1383                // the paths *global* (i.e., by prefixing them with `::`).
1384                let needs_disambiguation =
1385                    self.resolutions(parent_scope.module).borrow().iter().any(
1386                        |(key, name_resolution)| {
1387                            if key.ns == TypeNS
1388                                && key.ident == ident
1389                                && let Some(binding) = name_resolution.borrow().binding
1390                            {
1391                                match binding.res() {
1392                                    // No disambiguation needed if the identically named item we
1393                                    // found in scope actually refers to the crate in question.
1394                                    Res::Def(_, def_id) => def_id != crate_def_id,
1395                                    Res::PrimTy(_) => true,
1396                                    _ => false,
1397                                }
1398                            } else {
1399                                false
1400                            }
1401                        },
1402                    );
1403                let mut crate_path = ThinVec::new();
1404                if needs_disambiguation {
1405                    crate_path.push(ast::PathSegment::path_root(rustc_span::DUMMY_SP));
1406                }
1407                crate_path.push(ast::PathSegment::from_ident(ident));
1408
1409                suggestions.extend(self.lookup_import_candidates_from_module(
1410                    lookup_ident,
1411                    namespace,
1412                    parent_scope,
1413                    crate_root,
1414                    crate_path,
1415                    &filter_fn,
1416                ));
1417            }
1418        }
1419
1420        suggestions
1421    }
1422
1423    pub(crate) fn unresolved_macro_suggestions(
1424        &mut self,
1425        err: &mut Diag<'_>,
1426        macro_kind: MacroKind,
1427        parent_scope: &ParentScope<'ra>,
1428        ident: Ident,
1429        krate: &Crate,
1430    ) {
1431        let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1432        let suggestion = self.early_lookup_typo_candidate(
1433            ScopeSet::Macro(macro_kind),
1434            parent_scope,
1435            ident,
1436            is_expected,
1437        );
1438        self.add_typo_suggestion(err, suggestion, ident.span);
1439
1440        let import_suggestions =
1441            self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1442        let (span, found_use) = match parent_scope.module.nearest_parent_mod().as_local() {
1443            Some(def_id) => UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id]),
1444            None => (None, FoundUse::No),
1445        };
1446        show_candidates(
1447            self.tcx,
1448            err,
1449            span,
1450            &import_suggestions,
1451            Instead::No,
1452            found_use,
1453            DiagMode::Normal,
1454            vec![],
1455            "",
1456        );
1457
1458        if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1459            let label_span = ident.span.shrink_to_hi();
1460            let mut spans = MultiSpan::from_span(label_span);
1461            spans.push_span_label(label_span, "put a macro name here");
1462            err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1463            return;
1464        }
1465
1466        if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1467            err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1468            return;
1469        }
1470
1471        let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1472            if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1473        });
1474
1475        if let Some((def_id, unused_ident)) = unused_macro {
1476            let scope = self.local_macro_def_scopes[&def_id];
1477            let parent_nearest = parent_scope.module.nearest_parent_mod();
1478            if Some(parent_nearest) == scope.opt_def_id() {
1479                match macro_kind {
1480                    MacroKind::Bang => {
1481                        err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1482                        err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1483                    }
1484                    MacroKind::Attr => {
1485                        err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1486                    }
1487                    MacroKind::Derive => {
1488                        err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1489                    }
1490                }
1491
1492                return;
1493            }
1494        }
1495
1496        if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1497            err.subdiagnostic(AddedMacroUse);
1498            return;
1499        }
1500
1501        if ident.name == kw::Default
1502            && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1503        {
1504            let span = self.def_span(def_id);
1505            let source_map = self.tcx.sess.source_map();
1506            let head_span = source_map.guess_head_span(span);
1507            err.subdiagnostic(ConsiderAddingADerive {
1508                span: head_span.shrink_to_lo(),
1509                suggestion: "#[derive(Default)]\n".to_string(),
1510            });
1511        }
1512        for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1513            let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1514                ident,
1515                ScopeSet::All(ns),
1516                parent_scope,
1517                None,
1518                false,
1519                None,
1520                None,
1521            ) else {
1522                continue;
1523            };
1524
1525            let desc = match binding.res() {
1526                Res::Def(DefKind::Macro(MacroKind::Bang), _) => "a function-like macro".to_string(),
1527                Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1528                    format!("an attribute: `#[{ident}]`")
1529                }
1530                Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1531                    format!("a derive macro: `#[derive({ident})]`")
1532                }
1533                Res::ToolMod => {
1534                    // Don't confuse the user with tool modules.
1535                    continue;
1536                }
1537                Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1538                    "only a trait, without a derive macro".to_string()
1539                }
1540                res => format!(
1541                    "{} {}, not {} {}",
1542                    res.article(),
1543                    res.descr(),
1544                    macro_kind.article(),
1545                    macro_kind.descr_expected(),
1546                ),
1547            };
1548            if let crate::NameBindingKind::Import { import, .. } = binding.kind
1549                && !import.span.is_dummy()
1550            {
1551                let note = errors::IdentImporterHereButItIsDesc {
1552                    span: import.span,
1553                    imported_ident: ident,
1554                    imported_ident_desc: &desc,
1555                };
1556                err.subdiagnostic(note);
1557                // Silence the 'unused import' warning we might get,
1558                // since this diagnostic already covers that import.
1559                self.record_use(ident, binding, Used::Other);
1560                return;
1561            }
1562            let note = errors::IdentInScopeButItIsDesc {
1563                imported_ident: ident,
1564                imported_ident_desc: &desc,
1565            };
1566            err.subdiagnostic(note);
1567            return;
1568        }
1569    }
1570
1571    pub(crate) fn add_typo_suggestion(
1572        &self,
1573        err: &mut Diag<'_>,
1574        suggestion: Option<TypoSuggestion>,
1575        span: Span,
1576    ) -> bool {
1577        let suggestion = match suggestion {
1578            None => return false,
1579            // We shouldn't suggest underscore.
1580            Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1581            Some(suggestion) => suggestion,
1582        };
1583
1584        let mut did_label_def_span = false;
1585
1586        if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1587            if span.overlaps(def_span) {
1588                // Don't suggest typo suggestion for itself like in the following:
1589                // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1590                //   --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1591                //    |
1592                // LL | struct X {}
1593                //    | ----------- `X` defined here
1594                // LL |
1595                // LL | const Y: X = X("ö");
1596                //    | -------------^^^^^^- similarly named constant `Y` defined here
1597                //    |
1598                // help: use struct literal syntax instead
1599                //    |
1600                // LL | const Y: X = X {};
1601                //    |              ^^^^
1602                // help: a constant with a similar name exists
1603                //    |
1604                // LL | const Y: X = Y("ö");
1605                //    |              ^
1606                return false;
1607            }
1608            let span = self.tcx.sess.source_map().guess_head_span(def_span);
1609            let candidate_descr = suggestion.res.descr();
1610            let candidate = suggestion.candidate;
1611            let label = match suggestion.target {
1612                SuggestionTarget::SimilarlyNamed => {
1613                    errors::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
1614                }
1615                SuggestionTarget::SingleItem => {
1616                    errors::DefinedHere::SingleItem { span, candidate_descr, candidate }
1617                }
1618            };
1619            did_label_def_span = true;
1620            err.subdiagnostic(label);
1621        }
1622
1623        let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
1624            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1625            && let Some(span) = suggestion.span
1626            && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
1627            && snippet == candidate
1628        {
1629            let candidate = suggestion.candidate;
1630            // When the suggested binding change would be from `x` to `_x`, suggest changing the
1631            // original binding definition instead. (#60164)
1632            let msg = format!(
1633                "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
1634            );
1635            if !did_label_def_span {
1636                err.span_label(span, format!("`{candidate}` defined here"));
1637            }
1638            (span, msg, snippet)
1639        } else {
1640            let msg = match suggestion.target {
1641                SuggestionTarget::SimilarlyNamed => format!(
1642                    "{} {} with a similar name exists",
1643                    suggestion.res.article(),
1644                    suggestion.res.descr()
1645                ),
1646                SuggestionTarget::SingleItem => {
1647                    format!("maybe you meant this {}", suggestion.res.descr())
1648                }
1649            };
1650            (span, msg, suggestion.candidate.to_ident_string())
1651        };
1652        err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1653        true
1654    }
1655
1656    fn binding_description(&self, b: NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1657        let res = b.res();
1658        if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
1659            // These already contain the "built-in" prefix or look bad with it.
1660            let add_built_in =
1661                !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1662            let (built_in, from) = if from_prelude {
1663                ("", " from prelude")
1664            } else if b.is_extern_crate()
1665                && !b.is_import()
1666                && self.tcx.sess.opts.externs.get(ident.as_str()).is_some()
1667            {
1668                ("", " passed with `--extern`")
1669            } else if add_built_in {
1670                (" built-in", "")
1671            } else {
1672                ("", "")
1673            };
1674
1675            let a = if built_in.is_empty() { res.article() } else { "a" };
1676            format!("{a}{built_in} {thing}{from}", thing = res.descr())
1677        } else {
1678            let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1679            format!("the {thing} {introduced} here", thing = res.descr())
1680        }
1681    }
1682
1683    fn ambiguity_diagnostics(&self, ambiguity_error: &AmbiguityError<'_>) -> AmbiguityErrorDiag {
1684        let AmbiguityError { kind, ident, b1, b2, misc1, misc2, .. } = *ambiguity_error;
1685        let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1686            // We have to print the span-less alternative first, otherwise formatting looks bad.
1687            (b2, b1, misc2, misc1, true)
1688        } else {
1689            (b1, b2, misc1, misc2, false)
1690        };
1691        let could_refer_to = |b: NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1692            let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1693            let note_msg = format!("`{ident}` could{also} refer to {what}");
1694
1695            let thing = b.res().descr();
1696            let mut help_msgs = Vec::new();
1697            if b.is_glob_import()
1698                && (kind == AmbiguityKind::GlobVsGlob
1699                    || kind == AmbiguityKind::GlobVsExpanded
1700                    || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1701            {
1702                help_msgs.push(format!(
1703                    "consider adding an explicit import of `{ident}` to disambiguate"
1704                ))
1705            }
1706            if b.is_extern_crate() && ident.span.at_least_rust_2018() {
1707                help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1708            }
1709            match misc {
1710                AmbiguityErrorMisc::SuggestCrate => help_msgs
1711                    .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously")),
1712                AmbiguityErrorMisc::SuggestSelf => help_msgs
1713                    .push(format!("use `self::{ident}` to refer to this {thing} unambiguously")),
1714                AmbiguityErrorMisc::FromPrelude | AmbiguityErrorMisc::None => {}
1715            }
1716
1717            (
1718                b.span,
1719                note_msg,
1720                help_msgs
1721                    .iter()
1722                    .enumerate()
1723                    .map(|(i, help_msg)| {
1724                        let or = if i == 0 { "" } else { "or " };
1725                        format!("{or}{help_msg}")
1726                    })
1727                    .collect::<Vec<_>>(),
1728            )
1729        };
1730        let (b1_span, b1_note_msg, b1_help_msgs) = could_refer_to(b1, misc1, "");
1731        let (b2_span, b2_note_msg, b2_help_msgs) = could_refer_to(b2, misc2, " also");
1732
1733        AmbiguityErrorDiag {
1734            msg: format!("`{ident}` is ambiguous"),
1735            span: ident.span,
1736            label_span: ident.span,
1737            label_msg: "ambiguous name".to_string(),
1738            note_msg: format!("ambiguous because of {}", kind.descr()),
1739            b1_span,
1740            b1_note_msg,
1741            b1_help_msgs,
1742            b2_span,
1743            b2_note_msg,
1744            b2_help_msgs,
1745        }
1746    }
1747
1748    /// If the binding refers to a tuple struct constructor with fields,
1749    /// returns the span of its fields.
1750    fn ctor_fields_span(&self, binding: NameBinding<'_>) -> Option<Span> {
1751        let NameBindingKind::Res(Res::Def(
1752            DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
1753            ctor_def_id,
1754        )) = binding.kind
1755        else {
1756            return None;
1757        };
1758
1759        let def_id = self.tcx.parent(ctor_def_id);
1760        self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) // None for `struct Foo()`
1761    }
1762
1763    fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
1764        let PrivacyError { ident, binding, outermost_res, parent_scope, single_nested, dedup_span } =
1765            *privacy_error;
1766
1767        let res = binding.res();
1768        let ctor_fields_span = self.ctor_fields_span(binding);
1769        let plain_descr = res.descr().to_string();
1770        let nonimport_descr =
1771            if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1772        let import_descr = nonimport_descr.clone() + " import";
1773        let get_descr =
1774            |b: NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1775
1776        // Print the primary message.
1777        let ident_descr = get_descr(binding);
1778        let mut err =
1779            self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
1780
1781        let mut not_publicly_reexported = false;
1782        if let Some((this_res, outer_ident)) = outermost_res {
1783            let import_suggestions = self.lookup_import_candidates(
1784                outer_ident,
1785                this_res.ns().unwrap_or(Namespace::TypeNS),
1786                &parent_scope,
1787                &|res: Res| res == this_res,
1788            );
1789            let point_to_def = !show_candidates(
1790                self.tcx,
1791                &mut err,
1792                Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
1793                &import_suggestions,
1794                Instead::Yes,
1795                FoundUse::Yes,
1796                DiagMode::Import { append: single_nested },
1797                vec![],
1798                "",
1799            );
1800            // If we suggest importing a public re-export, don't point at the definition.
1801            if point_to_def && ident.span != outer_ident.span {
1802                not_publicly_reexported = true;
1803                let label = errors::OuterIdentIsNotPubliclyReexported {
1804                    span: outer_ident.span,
1805                    outer_ident_descr: this_res.descr(),
1806                    outer_ident,
1807                };
1808                err.subdiagnostic(label);
1809            }
1810        }
1811
1812        let mut non_exhaustive = None;
1813        // If an ADT is foreign and marked as `non_exhaustive`, then that's
1814        // probably why we have the privacy error.
1815        // Otherwise, point out if the struct has any private fields.
1816        if let Some(def_id) = res.opt_def_id()
1817            && !def_id.is_local()
1818            && let Some(attr) = self.tcx.get_attr(def_id, sym::non_exhaustive)
1819        {
1820            non_exhaustive = Some(attr.span());
1821        } else if let Some(span) = ctor_fields_span {
1822            let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
1823            err.subdiagnostic(label);
1824            if let Res::Def(_, d) = res
1825                && let Some(fields) = self.field_visibility_spans.get(&d)
1826            {
1827                let spans = fields.iter().map(|span| *span).collect();
1828                let sugg =
1829                    errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
1830                err.subdiagnostic(sugg);
1831            }
1832        }
1833
1834        let mut sugg_paths = vec![];
1835        if let Some(mut def_id) = res.opt_def_id() {
1836            // We can't use `def_path_str` in resolve.
1837            let mut path = vec![def_id];
1838            while let Some(parent) = self.tcx.opt_parent(def_id) {
1839                def_id = parent;
1840                if !def_id.is_top_level_module() {
1841                    path.push(def_id);
1842                } else {
1843                    break;
1844                }
1845            }
1846            // We will only suggest importing directly if it is accessible through that path.
1847            let path_names: Option<Vec<String>> = path
1848                .iter()
1849                .rev()
1850                .map(|def_id| {
1851                    self.tcx.opt_item_name(*def_id).map(|n| {
1852                        if def_id.is_top_level_module() {
1853                            "crate".to_string()
1854                        } else {
1855                            n.to_string()
1856                        }
1857                    })
1858                })
1859                .collect();
1860            if let Some(def_id) = path.get(0)
1861                && let Some(path) = path_names
1862            {
1863                if let Some(def_id) = def_id.as_local() {
1864                    if self.effective_visibilities.is_directly_public(def_id) {
1865                        sugg_paths.push((path, false));
1866                    }
1867                } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
1868                {
1869                    sugg_paths.push((path, false));
1870                }
1871            }
1872        }
1873
1874        // Print the whole import chain to make it easier to see what happens.
1875        let first_binding = binding;
1876        let mut next_binding = Some(binding);
1877        let mut next_ident = ident;
1878        let mut path = vec![];
1879        while let Some(binding) = next_binding {
1880            let name = next_ident;
1881            next_binding = match binding.kind {
1882                _ if res == Res::Err => None,
1883                NameBindingKind::Import { binding, import, .. } => match import.kind {
1884                    _ if binding.span.is_dummy() => None,
1885                    ImportKind::Single { source, .. } => {
1886                        next_ident = source;
1887                        Some(binding)
1888                    }
1889                    ImportKind::Glob { .. }
1890                    | ImportKind::MacroUse { .. }
1891                    | ImportKind::MacroExport => Some(binding),
1892                    ImportKind::ExternCrate { .. } => None,
1893                },
1894                _ => None,
1895            };
1896
1897            match binding.kind {
1898                NameBindingKind::Import { import, .. } => {
1899                    for segment in import.module_path.iter().skip(1) {
1900                        path.push(segment.ident.to_string());
1901                    }
1902                    sugg_paths.push((
1903                        path.iter()
1904                            .cloned()
1905                            .chain(vec![ident.to_string()].into_iter())
1906                            .collect::<Vec<_>>(),
1907                        true, // re-export
1908                    ));
1909                }
1910                NameBindingKind::Res(_) | NameBindingKind::Module(_) => {}
1911            }
1912            let first = binding == first_binding;
1913            let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
1914            let mut note_span = MultiSpan::from_span(def_span);
1915            if !first && binding.vis.is_public() {
1916                let desc = match binding.kind {
1917                    NameBindingKind::Import { .. } => "re-export",
1918                    _ => "directly",
1919                };
1920                note_span.push_span_label(def_span, format!("you could import this {desc}"));
1921            }
1922            // Final step in the import chain, point out if the ADT is `non_exhaustive`
1923            // which is probably why this privacy violation occurred.
1924            if next_binding.is_none()
1925                && let Some(span) = non_exhaustive
1926            {
1927                note_span.push_span_label(
1928                    span,
1929                    "cannot be constructed because it is `#[non_exhaustive]`",
1930                );
1931            }
1932            let note = errors::NoteAndRefersToTheItemDefinedHere {
1933                span: note_span,
1934                binding_descr: get_descr(binding),
1935                binding_name: name,
1936                first,
1937                dots: next_binding.is_some(),
1938            };
1939            err.subdiagnostic(note);
1940        }
1941        // We prioritize shorter paths, non-core imports and direct imports over the alternatives.
1942        sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0] == "core", *reexport));
1943        for (sugg, reexport) in sugg_paths {
1944            if not_publicly_reexported {
1945                break;
1946            }
1947            if sugg.len() <= 1 {
1948                // A single path segment suggestion is wrong. This happens on circular imports.
1949                // `tests/ui/imports/issue-55884-2.rs`
1950                continue;
1951            }
1952            let path = sugg.join("::");
1953            let sugg = if reexport {
1954                errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
1955            } else {
1956                errors::ImportIdent::Directly { span: dedup_span, ident, path }
1957            };
1958            err.subdiagnostic(sugg);
1959            break;
1960        }
1961
1962        err.emit();
1963    }
1964
1965    pub(crate) fn find_similarly_named_module_or_crate(
1966        &mut self,
1967        ident: Symbol,
1968        current_module: Module<'ra>,
1969    ) -> Option<Symbol> {
1970        let mut candidates = self
1971            .extern_prelude
1972            .keys()
1973            .map(|ident| ident.name)
1974            .chain(
1975                self.module_map
1976                    .iter()
1977                    .filter(|(_, module)| {
1978                        current_module.is_ancestor_of(**module) && current_module != **module
1979                    })
1980                    .flat_map(|(_, module)| module.kind.name()),
1981            )
1982            .filter(|c| !c.to_string().is_empty())
1983            .collect::<Vec<_>>();
1984        candidates.sort();
1985        candidates.dedup();
1986        find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
1987    }
1988
1989    pub(crate) fn report_path_resolution_error(
1990        &mut self,
1991        path: &[Segment],
1992        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1993        parent_scope: &ParentScope<'ra>,
1994        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1995        ignore_binding: Option<NameBinding<'ra>>,
1996        ignore_import: Option<Import<'ra>>,
1997        module: Option<ModuleOrUniformRoot<'ra>>,
1998        failed_segment_idx: usize,
1999        ident: Ident,
2000    ) -> (String, Option<Suggestion>) {
2001        let is_last = failed_segment_idx == path.len() - 1;
2002        let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2003        let module_res = match module {
2004            Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2005            _ => None,
2006        };
2007        if module_res == self.graph_root.res() {
2008            let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
2009            let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2010            candidates
2011                .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2012            if let Some(candidate) = candidates.get(0) {
2013                let path = {
2014                    // remove the possible common prefix of the path
2015                    let len = candidate.path.segments.len();
2016                    let start_index = (0..=failed_segment_idx.min(len - 1))
2017                        .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2018                        .unwrap_or_default();
2019                    let segments =
2020                        (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2021                    Path { segments, span: Span::default(), tokens: None }
2022                };
2023                (
2024                    String::from("unresolved import"),
2025                    Some((
2026                        vec![(ident.span, pprust::path_to_string(&path))],
2027                        String::from("a similar path exists"),
2028                        Applicability::MaybeIncorrect,
2029                    )),
2030                )
2031            } else if ident.name == sym::core {
2032                (
2033                    format!("you might be missing crate `{ident}`"),
2034                    Some((
2035                        vec![(ident.span, "std".to_string())],
2036                        "try using `std` instead of `core`".to_string(),
2037                        Applicability::MaybeIncorrect,
2038                    )),
2039                )
2040            } else if ident.name == kw::Underscore {
2041                (format!("`_` is not a valid crate or module name"), None)
2042            } else if self.tcx.sess.is_rust_2015() {
2043                (
2044                    format!("use of unresolved module or unlinked crate `{ident}`"),
2045                    Some((
2046                        vec![(
2047                            self.current_crate_outer_attr_insert_span,
2048                            format!("extern crate {ident};\n"),
2049                        )],
2050                        if was_invoked_from_cargo() {
2051                            format!(
2052                                "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2053                             to add it to your `Cargo.toml` and import it in your code",
2054                            )
2055                        } else {
2056                            format!(
2057                                "you might be missing a crate named `{ident}`, add it to your \
2058                                 project and import it in your code",
2059                            )
2060                        },
2061                        Applicability::MaybeIncorrect,
2062                    )),
2063                )
2064            } else {
2065                (format!("could not find `{ident}` in the crate root"), None)
2066            }
2067        } else if failed_segment_idx > 0 {
2068            let parent = path[failed_segment_idx - 1].ident.name;
2069            let parent = match parent {
2070                // ::foo is mounted at the crate root for 2015, and is the extern
2071                // prelude for 2018+
2072                kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2073                    "the list of imported crates".to_owned()
2074                }
2075                kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2076                _ => format!("`{parent}`"),
2077            };
2078
2079            let mut msg = format!("could not find `{ident}` in {parent}");
2080            if ns == TypeNS || ns == ValueNS {
2081                let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2082                let binding = if let Some(module) = module {
2083                    self.resolve_ident_in_module(
2084                        module,
2085                        ident,
2086                        ns_to_try,
2087                        parent_scope,
2088                        None,
2089                        ignore_binding,
2090                        ignore_import,
2091                    )
2092                    .ok()
2093                } else if let Some(ribs) = ribs
2094                    && let Some(TypeNS | ValueNS) = opt_ns
2095                {
2096                    assert!(ignore_import.is_none());
2097                    match self.resolve_ident_in_lexical_scope(
2098                        ident,
2099                        ns_to_try,
2100                        parent_scope,
2101                        None,
2102                        &ribs[ns_to_try],
2103                        ignore_binding,
2104                    ) {
2105                        // we found a locally-imported or available item/module
2106                        Some(LexicalScopeBinding::Item(binding)) => Some(binding),
2107                        _ => None,
2108                    }
2109                } else {
2110                    self.early_resolve_ident_in_lexical_scope(
2111                        ident,
2112                        ScopeSet::All(ns_to_try),
2113                        parent_scope,
2114                        None,
2115                        false,
2116                        ignore_binding,
2117                        ignore_import,
2118                    )
2119                    .ok()
2120                };
2121                if let Some(binding) = binding {
2122                    let mut found = |what| {
2123                        msg = format!(
2124                            "expected {}, found {} `{}` in {}",
2125                            ns.descr(),
2126                            what,
2127                            ident,
2128                            parent
2129                        )
2130                    };
2131                    if binding.module().is_some() {
2132                        found("module")
2133                    } else {
2134                        match binding.res() {
2135                            // Avoid using TyCtxt::def_kind_descr in the resolver, because it
2136                            // indirectly *calls* the resolver, and would cause a query cycle.
2137                            Res::Def(kind, id) => found(kind.descr(id)),
2138                            _ => found(ns_to_try.descr()),
2139                        }
2140                    }
2141                };
2142            }
2143            (msg, None)
2144        } else if ident.name == kw::SelfUpper {
2145            // As mentioned above, `opt_ns` being `None` indicates a module path in import.
2146            // We can use this to improve a confusing error for, e.g. `use Self::Variant` in an
2147            // impl
2148            if opt_ns.is_none() {
2149                ("`Self` cannot be used in imports".to_string(), None)
2150            } else {
2151                (
2152                    "`Self` is only available in impls, traits, and type definitions".to_string(),
2153                    None,
2154                )
2155            }
2156        } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2157            // Check whether the name refers to an item in the value namespace.
2158            let binding = if let Some(ribs) = ribs {
2159                assert!(ignore_import.is_none());
2160                self.resolve_ident_in_lexical_scope(
2161                    ident,
2162                    ValueNS,
2163                    parent_scope,
2164                    None,
2165                    &ribs[ValueNS],
2166                    ignore_binding,
2167                )
2168            } else {
2169                None
2170            };
2171            let match_span = match binding {
2172                // Name matches a local variable. For example:
2173                // ```
2174                // fn f() {
2175                //     let Foo: &str = "";
2176                //     println!("{}", Foo::Bar); // Name refers to local
2177                //                               // variable `Foo`.
2178                // }
2179                // ```
2180                Some(LexicalScopeBinding::Res(Res::Local(id))) => {
2181                    Some(*self.pat_span_map.get(&id).unwrap())
2182                }
2183                // Name matches item from a local name binding
2184                // created by `use` declaration. For example:
2185                // ```
2186                // pub Foo: &str = "";
2187                //
2188                // mod submod {
2189                //     use super::Foo;
2190                //     println!("{}", Foo::Bar); // Name refers to local
2191                //                               // binding `Foo`.
2192                // }
2193                // ```
2194                Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
2195                _ => None,
2196            };
2197            let suggestion = match_span.map(|span| {
2198                (
2199                    vec![(span, String::from(""))],
2200                    format!("`{ident}` is defined here, but is not a type"),
2201                    Applicability::MaybeIncorrect,
2202                )
2203            });
2204
2205            (format!("use of undeclared type `{ident}`"), suggestion)
2206        } else {
2207            let mut suggestion = None;
2208            if ident.name == sym::alloc {
2209                suggestion = Some((
2210                    vec![],
2211                    String::from("add `extern crate alloc` to use the `alloc` crate"),
2212                    Applicability::MaybeIncorrect,
2213                ))
2214            }
2215
2216            suggestion = suggestion.or_else(|| {
2217                self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2218                    |sugg| {
2219                        (
2220                            vec![(ident.span, sugg.to_string())],
2221                            String::from("there is a crate or module with a similar name"),
2222                            Applicability::MaybeIncorrect,
2223                        )
2224                    },
2225                )
2226            });
2227            if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
2228                ident,
2229                ScopeSet::All(ValueNS),
2230                parent_scope,
2231                None,
2232                false,
2233                ignore_binding,
2234                ignore_import,
2235            ) {
2236                let descr = binding.res().descr();
2237                (format!("{descr} `{ident}` is not a crate or module"), suggestion)
2238            } else {
2239                let suggestion = if suggestion.is_some() {
2240                    suggestion
2241                } else if was_invoked_from_cargo() {
2242                    Some((
2243                        vec![],
2244                        format!(
2245                            "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2246                             to add it to your `Cargo.toml`",
2247                        ),
2248                        Applicability::MaybeIncorrect,
2249                    ))
2250                } else {
2251                    Some((
2252                        vec![],
2253                        format!("you might be missing a crate named `{ident}`",),
2254                        Applicability::MaybeIncorrect,
2255                    ))
2256                };
2257                (format!("use of unresolved module or unlinked crate `{ident}`"), suggestion)
2258            }
2259        }
2260    }
2261
2262    /// Adds suggestions for a path that cannot be resolved.
2263    #[instrument(level = "debug", skip(self, parent_scope))]
2264    pub(crate) fn make_path_suggestion(
2265        &mut self,
2266        mut path: Vec<Segment>,
2267        parent_scope: &ParentScope<'ra>,
2268    ) -> Option<(Vec<Segment>, Option<String>)> {
2269        match path[..] {
2270            // `{{root}}::ident::...` on both editions.
2271            // On 2015 `{{root}}` is usually added implicitly.
2272            [first, second, ..]
2273                if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2274            // `ident::...` on 2018.
2275            [first, ..]
2276                if first.ident.span.at_least_rust_2018()
2277                    && !first.ident.is_path_segment_keyword() =>
2278            {
2279                // Insert a placeholder that's later replaced by `self`/`super`/etc.
2280                path.insert(0, Segment::from_ident(Ident::dummy()));
2281            }
2282            _ => return None,
2283        }
2284
2285        self.make_missing_self_suggestion(path.clone(), parent_scope)
2286            .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2287            .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2288            .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2289    }
2290
2291    /// Suggest a missing `self::` if that resolves to an correct module.
2292    ///
2293    /// ```text
2294    ///    |
2295    /// LL | use foo::Bar;
2296    ///    |     ^^^ did you mean `self::foo`?
2297    /// ```
2298    #[instrument(level = "debug", skip(self, parent_scope))]
2299    fn make_missing_self_suggestion(
2300        &mut self,
2301        mut path: Vec<Segment>,
2302        parent_scope: &ParentScope<'ra>,
2303    ) -> Option<(Vec<Segment>, Option<String>)> {
2304        // Replace first ident with `self` and check if that is valid.
2305        path[0].ident.name = kw::SelfLower;
2306        let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2307        debug!(?path, ?result);
2308        if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2309    }
2310
2311    /// Suggests a missing `crate::` if that resolves to an correct module.
2312    ///
2313    /// ```text
2314    ///    |
2315    /// LL | use foo::Bar;
2316    ///    |     ^^^ did you mean `crate::foo`?
2317    /// ```
2318    #[instrument(level = "debug", skip(self, parent_scope))]
2319    fn make_missing_crate_suggestion(
2320        &mut self,
2321        mut path: Vec<Segment>,
2322        parent_scope: &ParentScope<'ra>,
2323    ) -> Option<(Vec<Segment>, Option<String>)> {
2324        // Replace first ident with `crate` and check if that is valid.
2325        path[0].ident.name = kw::Crate;
2326        let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2327        debug!(?path, ?result);
2328        if let PathResult::Module(..) = result {
2329            Some((
2330                path,
2331                Some(
2332                    "`use` statements changed in Rust 2018; read more at \
2333                     <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2334                     clarity.html>"
2335                        .to_string(),
2336                ),
2337            ))
2338        } else {
2339            None
2340        }
2341    }
2342
2343    /// Suggests a missing `super::` if that resolves to an correct module.
2344    ///
2345    /// ```text
2346    ///    |
2347    /// LL | use foo::Bar;
2348    ///    |     ^^^ did you mean `super::foo`?
2349    /// ```
2350    #[instrument(level = "debug", skip(self, parent_scope))]
2351    fn make_missing_super_suggestion(
2352        &mut self,
2353        mut path: Vec<Segment>,
2354        parent_scope: &ParentScope<'ra>,
2355    ) -> Option<(Vec<Segment>, Option<String>)> {
2356        // Replace first ident with `crate` and check if that is valid.
2357        path[0].ident.name = kw::Super;
2358        let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2359        debug!(?path, ?result);
2360        if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2361    }
2362
2363    /// Suggests a missing external crate name if that resolves to an correct module.
2364    ///
2365    /// ```text
2366    ///    |
2367    /// LL | use foobar::Baz;
2368    ///    |     ^^^^^^ did you mean `baz::foobar`?
2369    /// ```
2370    ///
2371    /// Used when importing a submodule of an external crate but missing that crate's
2372    /// name as the first part of path.
2373    #[instrument(level = "debug", skip(self, parent_scope))]
2374    fn make_external_crate_suggestion(
2375        &mut self,
2376        mut path: Vec<Segment>,
2377        parent_scope: &ParentScope<'ra>,
2378    ) -> Option<(Vec<Segment>, Option<String>)> {
2379        if path[1].ident.span.is_rust_2015() {
2380            return None;
2381        }
2382
2383        // Sort extern crate names in *reverse* order to get
2384        // 1) some consistent ordering for emitted diagnostics, and
2385        // 2) `std` suggestions before `core` suggestions.
2386        let mut extern_crate_names =
2387            self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2388        extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
2389
2390        for name in extern_crate_names.into_iter() {
2391            // Replace first ident with a crate name and check if that is valid.
2392            path[0].ident.name = name;
2393            let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2394            debug!(?path, ?name, ?result);
2395            if let PathResult::Module(..) = result {
2396                return Some((path, None));
2397            }
2398        }
2399
2400        None
2401    }
2402
2403    /// Suggests importing a macro from the root of the crate rather than a module within
2404    /// the crate.
2405    ///
2406    /// ```text
2407    /// help: a macro with this name exists at the root of the crate
2408    ///    |
2409    /// LL | use issue_59764::makro;
2410    ///    |     ^^^^^^^^^^^^^^^^^^
2411    ///    |
2412    ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
2413    ///            at the root of the crate instead of the module where it is defined
2414    /// ```
2415    pub(crate) fn check_for_module_export_macro(
2416        &mut self,
2417        import: Import<'ra>,
2418        module: ModuleOrUniformRoot<'ra>,
2419        ident: Ident,
2420    ) -> Option<(Option<Suggestion>, Option<String>)> {
2421        let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2422            return None;
2423        };
2424
2425        while let Some(parent) = crate_module.parent {
2426            crate_module = parent;
2427        }
2428
2429        if module == ModuleOrUniformRoot::Module(crate_module) {
2430            // Don't make a suggestion if the import was already from the root of the crate.
2431            return None;
2432        }
2433
2434        let resolutions = self.resolutions(crate_module).borrow();
2435        let binding_key = BindingKey::new(ident, MacroNS);
2436        let resolution = resolutions.get(&binding_key)?;
2437        let binding = resolution.borrow().binding()?;
2438        let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() else {
2439            return None;
2440        };
2441        let module_name = crate_module.kind.name().unwrap_or(kw::Empty);
2442        let import_snippet = match import.kind {
2443            ImportKind::Single { source, target, .. } if source != target => {
2444                format!("{source} as {target}")
2445            }
2446            _ => format!("{ident}"),
2447        };
2448
2449        let mut corrections: Vec<(Span, String)> = Vec::new();
2450        if !import.is_nested() {
2451            // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2452            // intermediate segments.
2453            corrections.push((import.span, format!("{module_name}::{import_snippet}")));
2454        } else {
2455            // Find the binding span (and any trailing commas and spaces).
2456            //   ie. `use a::b::{c, d, e};`
2457            //                      ^^^
2458            let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2459                self.tcx.sess,
2460                import.span,
2461                import.use_span,
2462            );
2463            debug!(found_closing_brace, ?binding_span);
2464
2465            let mut removal_span = binding_span;
2466
2467            // If the binding span ended with a closing brace, as in the below example:
2468            //   ie. `use a::b::{c, d};`
2469            //                      ^
2470            // Then expand the span of characters to remove to include the previous
2471            // binding's trailing comma.
2472            //   ie. `use a::b::{c, d};`
2473            //                    ^^^
2474            if found_closing_brace
2475                && let Some(previous_span) =
2476                    extend_span_to_previous_binding(self.tcx.sess, binding_span)
2477            {
2478                debug!(?previous_span);
2479                removal_span = removal_span.with_lo(previous_span.lo());
2480            }
2481            debug!(?removal_span);
2482
2483            // Remove the `removal_span`.
2484            corrections.push((removal_span, "".to_string()));
2485
2486            // Find the span after the crate name and if it has nested imports immediately
2487            // after the crate name already.
2488            //   ie. `use a::b::{c, d};`
2489            //               ^^^^^^^^^
2490            //   or  `use a::{b, c, d}};`
2491            //               ^^^^^^^^^^^
2492            let (has_nested, after_crate_name) =
2493                find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
2494            debug!(has_nested, ?after_crate_name);
2495
2496            let source_map = self.tcx.sess.source_map();
2497
2498            // Make sure this is actually crate-relative.
2499            let is_definitely_crate = import
2500                .module_path
2501                .first()
2502                .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
2503
2504            // Add the import to the start, with a `{` if required.
2505            let start_point = source_map.start_point(after_crate_name);
2506            if is_definitely_crate
2507                && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
2508            {
2509                corrections.push((
2510                    start_point,
2511                    if has_nested {
2512                        // In this case, `start_snippet` must equal '{'.
2513                        format!("{start_snippet}{import_snippet}, ")
2514                    } else {
2515                        // In this case, add a `{`, then the moved import, then whatever
2516                        // was there before.
2517                        format!("{{{import_snippet}, {start_snippet}")
2518                    },
2519                ));
2520
2521                // Add a `};` to the end if nested, matching the `{` added at the start.
2522                if !has_nested {
2523                    corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2524                }
2525            } else {
2526                // If the root import is module-relative, add the import separately
2527                corrections.push((
2528                    import.use_span.shrink_to_lo(),
2529                    format!("use {module_name}::{import_snippet};\n"),
2530                ));
2531            }
2532        }
2533
2534        let suggestion = Some((
2535            corrections,
2536            String::from("a macro with this name exists at the root of the crate"),
2537            Applicability::MaybeIncorrect,
2538        ));
2539        Some((
2540            suggestion,
2541            Some(
2542                "this could be because a macro annotated with `#[macro_export]` will be exported \
2543            at the root of the crate instead of the module where it is defined"
2544                    .to_string(),
2545            ),
2546        ))
2547    }
2548
2549    /// Finds a cfg-ed out item inside `module` with the matching name.
2550    pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
2551        let local_items;
2552        let symbols = if module.is_local() {
2553            local_items = self
2554                .stripped_cfg_items
2555                .iter()
2556                .filter_map(|item| {
2557                    let parent_module = self.opt_local_def_id(item.parent_module)?.to_def_id();
2558                    Some(StrippedCfgItem { parent_module, name: item.name, cfg: item.cfg.clone() })
2559                })
2560                .collect::<Vec<_>>();
2561            local_items.as_slice()
2562        } else {
2563            self.tcx.stripped_cfg_items(module.krate)
2564        };
2565
2566        for &StrippedCfgItem { parent_module, name, ref cfg } in symbols {
2567            if parent_module != module || name.name != *segment {
2568                continue;
2569            }
2570
2571            let note = errors::FoundItemConfigureOut { span: name.span };
2572            err.subdiagnostic(note);
2573
2574            if let MetaItemKind::List(nested) = &cfg.kind
2575                && let MetaItemInner::MetaItem(meta_item) = &nested[0]
2576                && let MetaItemKind::NameValue(feature_name) = &meta_item.kind
2577            {
2578                let note = errors::ItemWasBehindFeature {
2579                    feature: feature_name.symbol,
2580                    span: meta_item.span,
2581                };
2582                err.subdiagnostic(note);
2583            } else {
2584                let note = errors::ItemWasCfgOut { span: cfg.span };
2585                err.subdiagnostic(note);
2586            }
2587        }
2588    }
2589}
2590
2591/// Given a `binding_span` of a binding within a use statement:
2592///
2593/// ```ignore (illustrative)
2594/// use foo::{a, b, c};
2595/// //           ^
2596/// ```
2597///
2598/// then return the span until the next binding or the end of the statement:
2599///
2600/// ```ignore (illustrative)
2601/// use foo::{a, b, c};
2602/// //           ^^^
2603/// ```
2604fn find_span_of_binding_until_next_binding(
2605    sess: &Session,
2606    binding_span: Span,
2607    use_span: Span,
2608) -> (bool, Span) {
2609    let source_map = sess.source_map();
2610
2611    // Find the span of everything after the binding.
2612    //   ie. `a, e};` or `a};`
2613    let binding_until_end = binding_span.with_hi(use_span.hi());
2614
2615    // Find everything after the binding but not including the binding.
2616    //   ie. `, e};` or `};`
2617    let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2618
2619    // Keep characters in the span until we encounter something that isn't a comma or
2620    // whitespace.
2621    //   ie. `, ` or ``.
2622    //
2623    // Also note whether a closing brace character was encountered. If there
2624    // was, then later go backwards to remove any trailing commas that are left.
2625    let mut found_closing_brace = false;
2626    let after_binding_until_next_binding =
2627        source_map.span_take_while(after_binding_until_end, |&ch| {
2628            if ch == '}' {
2629                found_closing_brace = true;
2630            }
2631            ch == ' ' || ch == ','
2632        });
2633
2634    // Combine the two spans.
2635    //   ie. `a, ` or `a`.
2636    //
2637    // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2638    let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2639
2640    (found_closing_brace, span)
2641}
2642
2643/// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2644/// binding.
2645///
2646/// ```ignore (illustrative)
2647/// use foo::a::{a, b, c};
2648/// //            ^^--- binding span
2649/// //            |
2650/// //            returned span
2651///
2652/// use foo::{a, b, c};
2653/// //        --- binding span
2654/// ```
2655fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2656    let source_map = sess.source_map();
2657
2658    // `prev_source` will contain all of the source that came before the span.
2659    // Then split based on a command and take the first (ie. closest to our span)
2660    // snippet. In the example, this is a space.
2661    let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2662
2663    let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2664    let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2665    if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2666        return None;
2667    }
2668
2669    let prev_comma = prev_comma.first().unwrap();
2670    let prev_starting_brace = prev_starting_brace.first().unwrap();
2671
2672    // If the amount of source code before the comma is greater than
2673    // the amount of source code before the starting brace then we've only
2674    // got one item in the nested item (eg. `issue_52891::{self}`).
2675    if prev_comma.len() > prev_starting_brace.len() {
2676        return None;
2677    }
2678
2679    Some(binding_span.with_lo(BytePos(
2680        // Take away the number of bytes for the characters we've found and an
2681        // extra for the comma.
2682        binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2683    )))
2684}
2685
2686/// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2687/// it is a nested use tree.
2688///
2689/// ```ignore (illustrative)
2690/// use foo::a::{b, c};
2691/// //       ^^^^^^^^^^ -- false
2692///
2693/// use foo::{a, b, c};
2694/// //       ^^^^^^^^^^ -- true
2695///
2696/// use foo::{a, b::{c, d}};
2697/// //       ^^^^^^^^^^^^^^^ -- true
2698/// ```
2699#[instrument(level = "debug", skip(sess))]
2700fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
2701    let source_map = sess.source_map();
2702
2703    // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2704    let mut num_colons = 0;
2705    // Find second colon.. `use issue_59764:`
2706    let until_second_colon = source_map.span_take_while(use_span, |c| {
2707        if *c == ':' {
2708            num_colons += 1;
2709        }
2710        !matches!(c, ':' if num_colons == 2)
2711    });
2712    // Find everything after the second colon.. `foo::{baz, makro};`
2713    let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2714
2715    let mut found_a_non_whitespace_character = false;
2716    // Find the first non-whitespace character in `from_second_colon`.. `f`
2717    let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2718        if found_a_non_whitespace_character {
2719            return false;
2720        }
2721        if !c.is_whitespace() {
2722            found_a_non_whitespace_character = true;
2723        }
2724        true
2725    });
2726
2727    // Find the first `{` in from_second_colon.. `foo::{`
2728    let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2729
2730    (next_left_bracket == after_second_colon, from_second_colon)
2731}
2732
2733/// A suggestion has already been emitted, change the wording slightly to clarify that both are
2734/// independent options.
2735enum Instead {
2736    Yes,
2737    No,
2738}
2739
2740/// Whether an existing place with an `use` item was found.
2741enum FoundUse {
2742    Yes,
2743    No,
2744}
2745
2746/// Whether a binding is part of a pattern or a use statement. Used for diagnostics.
2747pub(crate) enum DiagMode {
2748    Normal,
2749    /// The binding is part of a pattern
2750    Pattern,
2751    /// The binding is part of a use statement
2752    Import {
2753        /// `true` mean add the tips afterward for case `use a::{b,c}`,
2754        /// rather than replacing within.
2755        append: bool,
2756    },
2757}
2758
2759pub(crate) fn import_candidates(
2760    tcx: TyCtxt<'_>,
2761    err: &mut Diag<'_>,
2762    // This is `None` if all placement locations are inside expansions
2763    use_placement_span: Option<Span>,
2764    candidates: &[ImportSuggestion],
2765    mode: DiagMode,
2766    append: &str,
2767) {
2768    show_candidates(
2769        tcx,
2770        err,
2771        use_placement_span,
2772        candidates,
2773        Instead::Yes,
2774        FoundUse::Yes,
2775        mode,
2776        vec![],
2777        append,
2778    );
2779}
2780
2781type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
2782
2783/// When an entity with a given name is not available in scope, we search for
2784/// entities with that name in all crates. This method allows outputting the
2785/// results of this search in a programmer-friendly way. If any entities are
2786/// found and suggested, returns `true`, otherwise returns `false`.
2787fn show_candidates(
2788    tcx: TyCtxt<'_>,
2789    err: &mut Diag<'_>,
2790    // This is `None` if all placement locations are inside expansions
2791    use_placement_span: Option<Span>,
2792    candidates: &[ImportSuggestion],
2793    instead: Instead,
2794    found_use: FoundUse,
2795    mode: DiagMode,
2796    path: Vec<Segment>,
2797    append: &str,
2798) -> bool {
2799    if candidates.is_empty() {
2800        return false;
2801    }
2802
2803    let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
2804    let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
2805
2806    candidates.iter().for_each(|c| {
2807        if c.accessible {
2808            // Don't suggest `#[doc(hidden)]` items from other crates
2809            if c.doc_visible {
2810                accessible_path_strings.push((
2811                    pprust::path_to_string(&c.path),
2812                    c.descr,
2813                    c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
2814                    &c.note,
2815                    c.via_import,
2816                ))
2817            }
2818        } else {
2819            inaccessible_path_strings.push((
2820                pprust::path_to_string(&c.path),
2821                c.descr,
2822                c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
2823                &c.note,
2824                c.via_import,
2825            ))
2826        }
2827    });
2828
2829    // we want consistent results across executions, but candidates are produced
2830    // by iterating through a hash map, so make sure they are ordered:
2831    for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2832        path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2833        path_strings.dedup_by(|a, b| a.0 == b.0);
2834        let core_path_strings =
2835            path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
2836        let std_path_strings =
2837            path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
2838        let foreign_crate_path_strings =
2839            path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
2840
2841        // We list the `crate` local paths first.
2842        // Then we list the `std`/`core` paths.
2843        if std_path_strings.len() == core_path_strings.len() {
2844            // Do not list `core::` paths if we are already listing the `std::` ones.
2845            path_strings.extend(std_path_strings);
2846        } else {
2847            path_strings.extend(std_path_strings);
2848            path_strings.extend(core_path_strings);
2849        }
2850        // List all paths from foreign crates last.
2851        path_strings.extend(foreign_crate_path_strings);
2852    }
2853
2854    if !accessible_path_strings.is_empty() {
2855        let (determiner, kind, s, name, through) =
2856            if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
2857                (
2858                    "this",
2859                    *descr,
2860                    "",
2861                    format!(" `{name}`"),
2862                    if *via_import { " through its public re-export" } else { "" },
2863                )
2864            } else {
2865                // Get the unique item kinds and if there's only one, we use the right kind name
2866                // instead of the more generic "items".
2867                let kinds = accessible_path_strings
2868                    .iter()
2869                    .map(|(_, descr, _, _, _)| *descr)
2870                    .collect::<UnordSet<&str>>();
2871                let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
2872                let s = if kind.ends_with('s') { "es" } else { "s" };
2873
2874                ("one of these", kind, s, String::new(), "")
2875            };
2876
2877        let instead = if let Instead::Yes = instead { " instead" } else { "" };
2878        let mut msg = if let DiagMode::Pattern = mode {
2879            format!(
2880                "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
2881                 pattern",
2882            )
2883        } else {
2884            format!("consider importing {determiner} {kind}{s}{through}{instead}")
2885        };
2886
2887        for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2888            err.note(note.clone());
2889        }
2890
2891        let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
2892            msg.push(':');
2893
2894            for candidate in accessible_path_strings {
2895                msg.push('\n');
2896                msg.push_str(&candidate.0);
2897            }
2898        };
2899
2900        if let Some(span) = use_placement_span {
2901            let (add_use, trailing) = match mode {
2902                DiagMode::Pattern => {
2903                    err.span_suggestions(
2904                        span,
2905                        msg,
2906                        accessible_path_strings.into_iter().map(|a| a.0),
2907                        Applicability::MaybeIncorrect,
2908                    );
2909                    return true;
2910                }
2911                DiagMode::Import { .. } => ("", ""),
2912                DiagMode::Normal => ("use ", ";\n"),
2913            };
2914            for candidate in &mut accessible_path_strings {
2915                // produce an additional newline to separate the new use statement
2916                // from the directly following item.
2917                let additional_newline = if let FoundUse::No = found_use
2918                    && let DiagMode::Normal = mode
2919                {
2920                    "\n"
2921                } else {
2922                    ""
2923                };
2924                candidate.0 =
2925                    format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
2926            }
2927
2928            match mode {
2929                DiagMode::Import { append: true, .. } => {
2930                    append_candidates(&mut msg, accessible_path_strings);
2931                    err.span_help(span, msg);
2932                }
2933                _ => {
2934                    err.span_suggestions_with_style(
2935                        span,
2936                        msg,
2937                        accessible_path_strings.into_iter().map(|a| a.0),
2938                        Applicability::MaybeIncorrect,
2939                        SuggestionStyle::ShowAlways,
2940                    );
2941                }
2942            }
2943
2944            if let [first, .., last] = &path[..] {
2945                let sp = first.ident.span.until(last.ident.span);
2946                // Our suggestion is empty, so make sure the span is not empty (or we'd ICE).
2947                // Can happen for derive-generated spans.
2948                if sp.can_be_used_for_suggestions() && !sp.is_empty() {
2949                    err.span_suggestion_verbose(
2950                        sp,
2951                        format!("if you import `{}`, refer to it directly", last.ident),
2952                        "",
2953                        Applicability::Unspecified,
2954                    );
2955                }
2956            }
2957        } else {
2958            append_candidates(&mut msg, accessible_path_strings);
2959            err.help(msg);
2960        }
2961        true
2962    } else if !(inaccessible_path_strings.is_empty() || matches!(mode, DiagMode::Import { .. })) {
2963        let prefix =
2964            if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
2965        if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
2966            let msg = format!(
2967                "{prefix}{descr} `{name}`{} exists but is inaccessible",
2968                if let DiagMode::Pattern = mode { ", which" } else { "" }
2969            );
2970
2971            if let Some(source_span) = source_span {
2972                let span = tcx.sess.source_map().guess_head_span(*source_span);
2973                let mut multi_span = MultiSpan::from_span(span);
2974                multi_span.push_span_label(span, "not accessible");
2975                err.span_note(multi_span, msg);
2976            } else {
2977                err.note(msg);
2978            }
2979            if let Some(note) = (*note).as_deref() {
2980                err.note(note.to_string());
2981            }
2982        } else {
2983            let (_, descr_first, _, _, _) = &inaccessible_path_strings[0];
2984            let descr = if inaccessible_path_strings
2985                .iter()
2986                .skip(1)
2987                .all(|(_, descr, _, _, _)| descr == descr_first)
2988            {
2989                descr_first
2990            } else {
2991                "item"
2992            };
2993            let plural_descr =
2994                if descr.ends_with('s') { format!("{descr}es") } else { format!("{descr}s") };
2995
2996            let mut msg = format!("{prefix}these {plural_descr} exist but are inaccessible");
2997            let mut has_colon = false;
2998
2999            let mut spans = Vec::new();
3000            for (name, _, source_span, _, _) in &inaccessible_path_strings {
3001                if let Some(source_span) = source_span {
3002                    let span = tcx.sess.source_map().guess_head_span(*source_span);
3003                    spans.push((name, span));
3004                } else {
3005                    if !has_colon {
3006                        msg.push(':');
3007                        has_colon = true;
3008                    }
3009                    msg.push('\n');
3010                    msg.push_str(name);
3011                }
3012            }
3013
3014            let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3015            for (name, span) in spans {
3016                multi_span.push_span_label(span, format!("`{name}`: not accessible"));
3017            }
3018
3019            for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3020                err.note(note.clone());
3021            }
3022
3023            err.span_note(multi_span, msg);
3024        }
3025        true
3026    } else {
3027        false
3028    }
3029}
3030
3031#[derive(Debug)]
3032struct UsePlacementFinder {
3033    target_module: NodeId,
3034    first_legal_span: Option<Span>,
3035    first_use_span: Option<Span>,
3036}
3037
3038impl UsePlacementFinder {
3039    fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3040        let mut finder =
3041            UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3042        finder.visit_crate(krate);
3043        if let Some(use_span) = finder.first_use_span {
3044            (Some(use_span), FoundUse::Yes)
3045        } else {
3046            (finder.first_legal_span, FoundUse::No)
3047        }
3048    }
3049}
3050
3051impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
3052    fn visit_crate(&mut self, c: &Crate) {
3053        if self.target_module == CRATE_NODE_ID {
3054            let inject = c.spans.inject_use_span;
3055            if is_span_suitable_for_use_injection(inject) {
3056                self.first_legal_span = Some(inject);
3057            }
3058            self.first_use_span = search_for_any_use_in_items(&c.items);
3059        } else {
3060            visit::walk_crate(self, c);
3061        }
3062    }
3063
3064    fn visit_item(&mut self, item: &'tcx ast::Item) {
3065        if self.target_module == item.id {
3066            if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans, _)) = &item.kind {
3067                let inject = mod_spans.inject_use_span;
3068                if is_span_suitable_for_use_injection(inject) {
3069                    self.first_legal_span = Some(inject);
3070                }
3071                self.first_use_span = search_for_any_use_in_items(items);
3072            }
3073        } else {
3074            visit::walk_item(self, item);
3075        }
3076    }
3077}
3078
3079fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
3080    for item in items {
3081        if let ItemKind::Use(..) = item.kind
3082            && is_span_suitable_for_use_injection(item.span)
3083        {
3084            let mut lo = item.span.lo();
3085            for attr in &item.attrs {
3086                if attr.span.eq_ctxt(item.span) {
3087                    lo = std::cmp::min(lo, attr.span.lo());
3088                }
3089            }
3090            return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3091        }
3092    }
3093    None
3094}
3095
3096fn is_span_suitable_for_use_injection(s: Span) -> bool {
3097    // don't suggest placing a use before the prelude
3098    // import or other generated ones
3099    !s.from_expansion()
3100}