rustc_resolve/
diagnostics.rs

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