rustc_resolve/
diagnostics.rs

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