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