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    report_ambiguity_error, 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::builtin::{
26    ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS,
27    MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
28};
29use rustc_session::lint::{AmbiguityErrorDiag, BuiltinLintDiag};
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;
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_diagnostics(ambiguity_error);
149            if ambiguity_error.warning {
150                let NameBindingKind::Import { import, .. } = ambiguity_error.b1.0.kind else {
151                    unreachable!()
152                };
153                self.lint_buffer.buffer_lint(
154                    AMBIGUOUS_GLOB_IMPORTS,
155                    import.root_id,
156                    ambiguity_error.ident.span,
157                    BuiltinLintDiag::AmbiguousGlobImports { diag },
158                );
159            } else {
160                let mut err = struct_span_code_err!(self.dcx(), diag.span, E0659, "{}", diag.msg);
161                report_ambiguity_error(&mut err, diag);
162                err.emit();
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/issue-64792-bad-unicode-ctor.rs:3: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(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_diagnostics(&self, ambiguity_error: &AmbiguityError<'ra>) -> AmbiguityErrorDiag {
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                b.span,
2042                note_msg,
2043                help_msgs
2044                    .iter()
2045                    .enumerate()
2046                    .map(|(i, help_msg)| {
2047                        let or = if i == 0 { "" } else { "or " };
2048                        format!("{or}{help_msg}")
2049                    })
2050                    .collect::<Vec<_>>(),
2051            )
2052        };
2053        let (b1_span, b1_note_msg, b1_help_msgs) = could_refer_to(b1, misc1, "");
2054        let (b2_span, b2_note_msg, b2_help_msgs) = could_refer_to(b2, misc2, " also");
2055
2056        AmbiguityErrorDiag {
2057            msg: format!("`{ident}` is ambiguous"),
2058            span: ident.span,
2059            label_span: ident.span,
2060            label_msg: "ambiguous name".to_string(),
2061            note_msg: format!("ambiguous because of {}", kind.descr()),
2062            b1_span,
2063            b1_note_msg,
2064            b1_help_msgs,
2065            b2_span,
2066            b2_note_msg,
2067            b2_help_msgs,
2068        }
2069    }
2070
2071    /// If the binding refers to a tuple struct constructor with fields,
2072    /// returns the span of its fields.
2073    fn ctor_fields_span(&self, binding: NameBinding<'_>) -> Option<Span> {
2074        let NameBindingKind::Res(Res::Def(
2075            DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
2076            ctor_def_id,
2077        )) = binding.kind
2078        else {
2079            return None;
2080        };
2081
2082        let def_id = self.tcx.parent(ctor_def_id);
2083        self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) // None for `struct Foo()`
2084    }
2085
2086    fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
2087        let PrivacyError {
2088            ident,
2089            binding,
2090            outermost_res,
2091            parent_scope,
2092            single_nested,
2093            dedup_span,
2094            ref source,
2095        } = *privacy_error;
2096
2097        let res = binding.res();
2098        let ctor_fields_span = self.ctor_fields_span(binding);
2099        let plain_descr = res.descr().to_string();
2100        let nonimport_descr =
2101            if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
2102        let import_descr = nonimport_descr.clone() + " import";
2103        let get_descr =
2104            |b: NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
2105
2106        // Print the primary message.
2107        let ident_descr = get_descr(binding);
2108        let mut err =
2109            self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
2110
2111        self.mention_default_field_values(source, ident, &mut err);
2112
2113        let mut not_publicly_reexported = false;
2114        if let Some((this_res, outer_ident)) = outermost_res {
2115            let import_suggestions = self.lookup_import_candidates(
2116                outer_ident,
2117                this_res.ns().unwrap_or(Namespace::TypeNS),
2118                &parent_scope,
2119                &|res: Res| res == this_res,
2120            );
2121            let point_to_def = !show_candidates(
2122                self.tcx,
2123                &mut err,
2124                Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
2125                &import_suggestions,
2126                Instead::Yes,
2127                FoundUse::Yes,
2128                DiagMode::Import { append: single_nested, unresolved_import: false },
2129                vec![],
2130                "",
2131            );
2132            // If we suggest importing a public re-export, don't point at the definition.
2133            if point_to_def && ident.span != outer_ident.span {
2134                not_publicly_reexported = true;
2135                let label = errors::OuterIdentIsNotPubliclyReexported {
2136                    span: outer_ident.span,
2137                    outer_ident_descr: this_res.descr(),
2138                    outer_ident,
2139                };
2140                err.subdiagnostic(label);
2141            }
2142        }
2143
2144        let mut non_exhaustive = None;
2145        // If an ADT is foreign and marked as `non_exhaustive`, then that's
2146        // probably why we have the privacy error.
2147        // Otherwise, point out if the struct has any private fields.
2148        if let Some(def_id) = res.opt_def_id()
2149            && !def_id.is_local()
2150            && let Some(attr_span) = find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::NonExhaustive(span) => *span)
2151        {
2152            non_exhaustive = Some(attr_span);
2153        } else if let Some(span) = ctor_fields_span {
2154            let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
2155            err.subdiagnostic(label);
2156            if let Res::Def(_, d) = res
2157                && let Some(fields) = self.field_visibility_spans.get(&d)
2158            {
2159                let spans = fields.iter().map(|span| *span).collect();
2160                let sugg =
2161                    errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
2162                err.subdiagnostic(sugg);
2163            }
2164        }
2165
2166        let mut sugg_paths: Vec<(Vec<Ident>, bool)> = vec![];
2167        if let Some(mut def_id) = res.opt_def_id() {
2168            // We can't use `def_path_str` in resolve.
2169            let mut path = vec![def_id];
2170            while let Some(parent) = self.tcx.opt_parent(def_id) {
2171                def_id = parent;
2172                if !def_id.is_top_level_module() {
2173                    path.push(def_id);
2174                } else {
2175                    break;
2176                }
2177            }
2178            // We will only suggest importing directly if it is accessible through that path.
2179            let path_names: Option<Vec<Ident>> = path
2180                .iter()
2181                .rev()
2182                .map(|def_id| {
2183                    self.tcx.opt_item_name(*def_id).map(|name| {
2184                        Ident::with_dummy_span(if def_id.is_top_level_module() {
2185                            kw::Crate
2186                        } else {
2187                            name
2188                        })
2189                    })
2190                })
2191                .collect();
2192            if let Some(def_id) = path.get(0)
2193                && let Some(path) = path_names
2194            {
2195                if let Some(def_id) = def_id.as_local() {
2196                    if self.effective_visibilities.is_directly_public(def_id) {
2197                        sugg_paths.push((path, false));
2198                    }
2199                } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
2200                {
2201                    sugg_paths.push((path, false));
2202                }
2203            }
2204        }
2205
2206        // Print the whole import chain to make it easier to see what happens.
2207        let first_binding = binding;
2208        let mut next_binding = Some(binding);
2209        let mut next_ident = ident;
2210        let mut path = vec![];
2211        while let Some(binding) = next_binding {
2212            let name = next_ident;
2213            next_binding = match binding.kind {
2214                _ if res == Res::Err => None,
2215                NameBindingKind::Import { binding, import, .. } => match import.kind {
2216                    _ if binding.span.is_dummy() => None,
2217                    ImportKind::Single { source, .. } => {
2218                        next_ident = source;
2219                        Some(binding)
2220                    }
2221                    ImportKind::Glob { .. }
2222                    | ImportKind::MacroUse { .. }
2223                    | ImportKind::MacroExport => Some(binding),
2224                    ImportKind::ExternCrate { .. } => None,
2225                },
2226                _ => None,
2227            };
2228
2229            match binding.kind {
2230                NameBindingKind::Import { import, .. } => {
2231                    for segment in import.module_path.iter().skip(1) {
2232                        path.push(segment.ident);
2233                    }
2234                    sugg_paths.push((
2235                        path.iter().cloned().chain(std::iter::once(ident)).collect::<Vec<_>>(),
2236                        true, // re-export
2237                    ));
2238                }
2239                NameBindingKind::Res(_) => {}
2240            }
2241            let first = binding == first_binding;
2242            let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
2243            let mut note_span = MultiSpan::from_span(def_span);
2244            if !first && binding.vis.is_public() {
2245                let desc = match binding.kind {
2246                    NameBindingKind::Import { .. } => "re-export",
2247                    _ => "directly",
2248                };
2249                note_span.push_span_label(def_span, format!("you could import this {desc}"));
2250            }
2251            // Final step in the import chain, point out if the ADT is `non_exhaustive`
2252            // which is probably why this privacy violation occurred.
2253            if next_binding.is_none()
2254                && let Some(span) = non_exhaustive
2255            {
2256                note_span.push_span_label(
2257                    span,
2258                    "cannot be constructed because it is `#[non_exhaustive]`",
2259                );
2260            }
2261            let note = errors::NoteAndRefersToTheItemDefinedHere {
2262                span: note_span,
2263                binding_descr: get_descr(binding),
2264                binding_name: name,
2265                first,
2266                dots: next_binding.is_some(),
2267            };
2268            err.subdiagnostic(note);
2269        }
2270        // We prioritize shorter paths, non-core imports and direct imports over the alternatives.
2271        sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0].name == sym::core, *reexport));
2272        for (sugg, reexport) in sugg_paths {
2273            if not_publicly_reexported {
2274                break;
2275            }
2276            if sugg.len() <= 1 {
2277                // A single path segment suggestion is wrong. This happens on circular imports.
2278                // `tests/ui/imports/issue-55884-2.rs`
2279                continue;
2280            }
2281            let path = join_path_idents(sugg);
2282            let sugg = if reexport {
2283                errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
2284            } else {
2285                errors::ImportIdent::Directly { span: dedup_span, ident, path }
2286            };
2287            err.subdiagnostic(sugg);
2288            break;
2289        }
2290
2291        err.emit();
2292    }
2293
2294    /// When a private field is being set that has a default field value, we suggest using `..` and
2295    /// setting the value of that field implicitly with its default.
2296    ///
2297    /// If we encounter code like
2298    /// ```text
2299    /// struct Priv;
2300    /// pub struct S {
2301    ///     pub field: Priv = Priv,
2302    /// }
2303    /// ```
2304    /// which is used from a place where `Priv` isn't accessible
2305    /// ```text
2306    /// let _ = S { field: m::Priv1 {} };
2307    /// //                    ^^^^^ private struct
2308    /// ```
2309    /// we will suggest instead using the `default_field_values` syntax instead:
2310    /// ```text
2311    /// let _ = S { .. };
2312    /// ```
2313    fn mention_default_field_values(
2314        &self,
2315        source: &Option<ast::Expr>,
2316        ident: Ident,
2317        err: &mut Diag<'_>,
2318    ) {
2319        let Some(expr) = source else { return };
2320        let ast::ExprKind::Struct(struct_expr) = &expr.kind else { return };
2321        // We don't have to handle type-relative paths because they're forbidden in ADT
2322        // expressions, but that would change with `#[feature(more_qualified_paths)]`.
2323        let Some(segment) = struct_expr.path.segments.last() else { return };
2324        let Some(partial_res) = self.partial_res_map.get(&segment.id) else { return };
2325        let Some(Res::Def(_, def_id)) = partial_res.full_res() else {
2326            return;
2327        };
2328        let Some(default_fields) = self.field_defaults(def_id) else { return };
2329        if struct_expr.fields.is_empty() {
2330            return;
2331        }
2332        let last_span = struct_expr.fields.iter().last().unwrap().span;
2333        let mut iter = struct_expr.fields.iter().peekable();
2334        let mut prev: Option<Span> = None;
2335        while let Some(field) = iter.next() {
2336            if field.expr.span.overlaps(ident.span) {
2337                err.span_label(field.ident.span, "while setting this field");
2338                if default_fields.contains(&field.ident.name) {
2339                    let sugg = if last_span == field.span {
2340                        vec![(field.span, "..".to_string())]
2341                    } else {
2342                        vec![
2343                            (
2344                                // Account for trailing commas and ensure we remove them.
2345                                match (prev, iter.peek()) {
2346                                    (_, Some(next)) => field.span.with_hi(next.span.lo()),
2347                                    (Some(prev), _) => field.span.with_lo(prev.hi()),
2348                                    (None, None) => field.span,
2349                                },
2350                                String::new(),
2351                            ),
2352                            (last_span.shrink_to_hi(), ", ..".to_string()),
2353                        ]
2354                    };
2355                    err.multipart_suggestion_verbose(
2356                        format!(
2357                            "the type `{ident}` of field `{}` is private, but you can construct \
2358                             the default value defined for it in `{}` using `..` in the struct \
2359                             initializer expression",
2360                            field.ident,
2361                            self.tcx.item_name(def_id),
2362                        ),
2363                        sugg,
2364                        Applicability::MachineApplicable,
2365                    );
2366                    break;
2367                }
2368            }
2369            prev = Some(field.span);
2370        }
2371    }
2372
2373    pub(crate) fn find_similarly_named_module_or_crate(
2374        &self,
2375        ident: Symbol,
2376        current_module: Module<'ra>,
2377    ) -> Option<Symbol> {
2378        let mut candidates = self
2379            .extern_prelude
2380            .keys()
2381            .map(|ident| ident.name)
2382            .chain(
2383                self.local_module_map
2384                    .iter()
2385                    .filter(|(_, module)| {
2386                        current_module.is_ancestor_of(**module) && current_module != **module
2387                    })
2388                    .flat_map(|(_, module)| module.kind.name()),
2389            )
2390            .chain(
2391                self.extern_module_map
2392                    .borrow()
2393                    .iter()
2394                    .filter(|(_, module)| {
2395                        current_module.is_ancestor_of(**module) && current_module != **module
2396                    })
2397                    .flat_map(|(_, module)| module.kind.name()),
2398            )
2399            .filter(|c| !c.to_string().is_empty())
2400            .collect::<Vec<_>>();
2401        candidates.sort();
2402        candidates.dedup();
2403        find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
2404    }
2405
2406    pub(crate) fn report_path_resolution_error(
2407        &mut self,
2408        path: &[Segment],
2409        opt_ns: Option<Namespace>, // `None` indicates a module path in import
2410        parent_scope: &ParentScope<'ra>,
2411        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
2412        ignore_binding: Option<NameBinding<'ra>>,
2413        ignore_import: Option<Import<'ra>>,
2414        module: Option<ModuleOrUniformRoot<'ra>>,
2415        failed_segment_idx: usize,
2416        ident: Ident,
2417        diag_metadata: Option<&DiagMetadata<'_>>,
2418    ) -> (String, Option<Suggestion>) {
2419        let is_last = failed_segment_idx == path.len() - 1;
2420        let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2421        let module_res = match module {
2422            Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2423            _ => None,
2424        };
2425        if module_res == self.graph_root.res() {
2426            let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
2427            let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2428            candidates
2429                .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2430            if let Some(candidate) = candidates.get(0) {
2431                let path = {
2432                    // remove the possible common prefix of the path
2433                    let len = candidate.path.segments.len();
2434                    let start_index = (0..=failed_segment_idx.min(len - 1))
2435                        .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2436                        .unwrap_or_default();
2437                    let segments =
2438                        (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2439                    Path { segments, span: Span::default(), tokens: None }
2440                };
2441                (
2442                    String::from("unresolved import"),
2443                    Some((
2444                        vec![(ident.span, pprust::path_to_string(&path))],
2445                        String::from("a similar path exists"),
2446                        Applicability::MaybeIncorrect,
2447                    )),
2448                )
2449            } else if ident.name == sym::core {
2450                (
2451                    format!("you might be missing crate `{ident}`"),
2452                    Some((
2453                        vec![(ident.span, "std".to_string())],
2454                        "try using `std` instead of `core`".to_string(),
2455                        Applicability::MaybeIncorrect,
2456                    )),
2457                )
2458            } else if ident.name == kw::Underscore {
2459                (format!("`_` is not a valid crate or module name"), None)
2460            } else if self.tcx.sess.is_rust_2015() {
2461                (
2462                    format!("use of unresolved module or unlinked crate `{ident}`"),
2463                    Some((
2464                        vec![(
2465                            self.current_crate_outer_attr_insert_span,
2466                            format!("extern crate {ident};\n"),
2467                        )],
2468                        if was_invoked_from_cargo() {
2469                            format!(
2470                                "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2471                             to add it to your `Cargo.toml` and import it in your code",
2472                            )
2473                        } else {
2474                            format!(
2475                                "you might be missing a crate named `{ident}`, add it to your \
2476                                 project and import it in your code",
2477                            )
2478                        },
2479                        Applicability::MaybeIncorrect,
2480                    )),
2481                )
2482            } else {
2483                (format!("could not find `{ident}` in the crate root"), None)
2484            }
2485        } else if failed_segment_idx > 0 {
2486            let parent = path[failed_segment_idx - 1].ident.name;
2487            let parent = match parent {
2488                // ::foo is mounted at the crate root for 2015, and is the extern
2489                // prelude for 2018+
2490                kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2491                    "the list of imported crates".to_owned()
2492                }
2493                kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2494                _ => format!("`{parent}`"),
2495            };
2496
2497            let mut msg = format!("could not find `{ident}` in {parent}");
2498            if ns == TypeNS || ns == ValueNS {
2499                let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2500                let binding = if let Some(module) = module {
2501                    self.cm()
2502                        .resolve_ident_in_module(
2503                            module,
2504                            ident,
2505                            ns_to_try,
2506                            parent_scope,
2507                            None,
2508                            ignore_binding,
2509                            ignore_import,
2510                        )
2511                        .ok()
2512                } else if let Some(ribs) = ribs
2513                    && let Some(TypeNS | ValueNS) = opt_ns
2514                {
2515                    assert!(ignore_import.is_none());
2516                    match self.resolve_ident_in_lexical_scope(
2517                        ident,
2518                        ns_to_try,
2519                        parent_scope,
2520                        None,
2521                        &ribs[ns_to_try],
2522                        ignore_binding,
2523                        diag_metadata,
2524                    ) {
2525                        // we found a locally-imported or available item/module
2526                        Some(LexicalScopeBinding::Item(binding)) => Some(binding),
2527                        _ => None,
2528                    }
2529                } else {
2530                    self.cm()
2531                        .resolve_ident_in_scope_set(
2532                            ident,
2533                            ScopeSet::All(ns_to_try),
2534                            parent_scope,
2535                            None,
2536                            false,
2537                            ignore_binding,
2538                            ignore_import,
2539                        )
2540                        .ok()
2541                };
2542                if let Some(binding) = binding {
2543                    msg = format!(
2544                        "expected {}, found {} `{ident}` in {parent}",
2545                        ns.descr(),
2546                        binding.res().descr(),
2547                    );
2548                };
2549            }
2550            (msg, None)
2551        } else if ident.name == kw::SelfUpper {
2552            // As mentioned above, `opt_ns` being `None` indicates a module path in import.
2553            // We can use this to improve a confusing error for, e.g. `use Self::Variant` in an
2554            // impl
2555            if opt_ns.is_none() {
2556                ("`Self` cannot be used in imports".to_string(), None)
2557            } else {
2558                (
2559                    "`Self` is only available in impls, traits, and type definitions".to_string(),
2560                    None,
2561                )
2562            }
2563        } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2564            // Check whether the name refers to an item in the value namespace.
2565            let binding = if let Some(ribs) = ribs {
2566                assert!(ignore_import.is_none());
2567                self.resolve_ident_in_lexical_scope(
2568                    ident,
2569                    ValueNS,
2570                    parent_scope,
2571                    None,
2572                    &ribs[ValueNS],
2573                    ignore_binding,
2574                    diag_metadata,
2575                )
2576            } else {
2577                None
2578            };
2579            let match_span = match binding {
2580                // Name matches a local variable. For example:
2581                // ```
2582                // fn f() {
2583                //     let Foo: &str = "";
2584                //     println!("{}", Foo::Bar); // Name refers to local
2585                //                               // variable `Foo`.
2586                // }
2587                // ```
2588                Some(LexicalScopeBinding::Res(Res::Local(id))) => {
2589                    Some(*self.pat_span_map.get(&id).unwrap())
2590                }
2591                // Name matches item from a local name binding
2592                // created by `use` declaration. For example:
2593                // ```
2594                // pub Foo: &str = "";
2595                //
2596                // mod submod {
2597                //     use super::Foo;
2598                //     println!("{}", Foo::Bar); // Name refers to local
2599                //                               // binding `Foo`.
2600                // }
2601                // ```
2602                Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
2603                _ => None,
2604            };
2605            let suggestion = match_span.map(|span| {
2606                (
2607                    vec![(span, String::from(""))],
2608                    format!("`{ident}` is defined here, but is not a type"),
2609                    Applicability::MaybeIncorrect,
2610                )
2611            });
2612
2613            (format!("use of undeclared type `{ident}`"), suggestion)
2614        } else {
2615            let mut suggestion = None;
2616            if ident.name == sym::alloc {
2617                suggestion = Some((
2618                    vec![],
2619                    String::from("add `extern crate alloc` to use the `alloc` crate"),
2620                    Applicability::MaybeIncorrect,
2621                ))
2622            }
2623
2624            suggestion = suggestion.or_else(|| {
2625                self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2626                    |sugg| {
2627                        (
2628                            vec![(ident.span, sugg.to_string())],
2629                            String::from("there is a crate or module with a similar name"),
2630                            Applicability::MaybeIncorrect,
2631                        )
2632                    },
2633                )
2634            });
2635            if let Ok(binding) = self.cm().resolve_ident_in_scope_set(
2636                ident,
2637                ScopeSet::All(ValueNS),
2638                parent_scope,
2639                None,
2640                false,
2641                ignore_binding,
2642                ignore_import,
2643            ) {
2644                let descr = binding.res().descr();
2645                (format!("{descr} `{ident}` is not a crate or module"), suggestion)
2646            } else {
2647                let suggestion = if suggestion.is_some() {
2648                    suggestion
2649                } else if let Some(m) = self.undeclared_module_exists(ident) {
2650                    self.undeclared_module_suggest_declare(ident, m)
2651                } else if was_invoked_from_cargo() {
2652                    Some((
2653                        vec![],
2654                        format!(
2655                            "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2656                             to add it to your `Cargo.toml`",
2657                        ),
2658                        Applicability::MaybeIncorrect,
2659                    ))
2660                } else {
2661                    Some((
2662                        vec![],
2663                        format!("you might be missing a crate named `{ident}`",),
2664                        Applicability::MaybeIncorrect,
2665                    ))
2666                };
2667                (format!("use of unresolved module or unlinked crate `{ident}`"), suggestion)
2668            }
2669        }
2670    }
2671
2672    fn undeclared_module_suggest_declare(
2673        &self,
2674        ident: Ident,
2675        path: std::path::PathBuf,
2676    ) -> Option<(Vec<(Span, String)>, String, Applicability)> {
2677        Some((
2678            vec![(self.current_crate_outer_attr_insert_span, format!("mod {ident};\n"))],
2679            format!(
2680                "to make use of source file {}, use `mod {ident}` \
2681                 in this file to declare the module",
2682                path.display()
2683            ),
2684            Applicability::MaybeIncorrect,
2685        ))
2686    }
2687
2688    fn undeclared_module_exists(&self, ident: Ident) -> Option<std::path::PathBuf> {
2689        let map = self.tcx.sess.source_map();
2690
2691        let src = map.span_to_filename(ident.span).into_local_path()?;
2692        let i = ident.as_str();
2693        // FIXME: add case where non parent using undeclared module (hard?)
2694        let dir = src.parent()?;
2695        let src = src.file_stem()?.to_str()?;
2696        for file in [
2697            // …/x.rs
2698            dir.join(i).with_extension("rs"),
2699            // …/x/mod.rs
2700            dir.join(i).join("mod.rs"),
2701        ] {
2702            if file.exists() {
2703                return Some(file);
2704            }
2705        }
2706        if !matches!(src, "main" | "lib" | "mod") {
2707            for file in [
2708                // …/x/y.rs
2709                dir.join(src).join(i).with_extension("rs"),
2710                // …/x/y/mod.rs
2711                dir.join(src).join(i).join("mod.rs"),
2712            ] {
2713                if file.exists() {
2714                    return Some(file);
2715                }
2716            }
2717        }
2718        None
2719    }
2720
2721    /// Adds suggestions for a path that cannot be resolved.
2722    #[instrument(level = "debug", skip(self, parent_scope))]
2723    pub(crate) fn make_path_suggestion(
2724        &mut self,
2725        mut path: Vec<Segment>,
2726        parent_scope: &ParentScope<'ra>,
2727    ) -> Option<(Vec<Segment>, Option<String>)> {
2728        match path[..] {
2729            // `{{root}}::ident::...` on both editions.
2730            // On 2015 `{{root}}` is usually added implicitly.
2731            [first, second, ..]
2732                if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2733            // `ident::...` on 2018.
2734            [first, ..]
2735                if first.ident.span.at_least_rust_2018()
2736                    && !first.ident.is_path_segment_keyword() =>
2737            {
2738                // Insert a placeholder that's later replaced by `self`/`super`/etc.
2739                path.insert(0, Segment::from_ident(Ident::dummy()));
2740            }
2741            _ => return None,
2742        }
2743
2744        self.make_missing_self_suggestion(path.clone(), parent_scope)
2745            .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2746            .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2747            .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2748    }
2749
2750    /// Suggest a missing `self::` if that resolves to an correct module.
2751    ///
2752    /// ```text
2753    ///    |
2754    /// LL | use foo::Bar;
2755    ///    |     ^^^ did you mean `self::foo`?
2756    /// ```
2757    #[instrument(level = "debug", skip(self, parent_scope))]
2758    fn make_missing_self_suggestion(
2759        &mut self,
2760        mut path: Vec<Segment>,
2761        parent_scope: &ParentScope<'ra>,
2762    ) -> Option<(Vec<Segment>, Option<String>)> {
2763        // Replace first ident with `self` and check if that is valid.
2764        path[0].ident.name = kw::SelfLower;
2765        let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2766        debug!(?path, ?result);
2767        if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2768    }
2769
2770    /// Suggests a missing `crate::` if that resolves to an correct module.
2771    ///
2772    /// ```text
2773    ///    |
2774    /// LL | use foo::Bar;
2775    ///    |     ^^^ did you mean `crate::foo`?
2776    /// ```
2777    #[instrument(level = "debug", skip(self, parent_scope))]
2778    fn make_missing_crate_suggestion(
2779        &mut self,
2780        mut path: Vec<Segment>,
2781        parent_scope: &ParentScope<'ra>,
2782    ) -> Option<(Vec<Segment>, Option<String>)> {
2783        // Replace first ident with `crate` and check if that is valid.
2784        path[0].ident.name = kw::Crate;
2785        let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2786        debug!(?path, ?result);
2787        if let PathResult::Module(..) = result {
2788            Some((
2789                path,
2790                Some(
2791                    "`use` statements changed in Rust 2018; read more at \
2792                     <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2793                     clarity.html>"
2794                        .to_string(),
2795                ),
2796            ))
2797        } else {
2798            None
2799        }
2800    }
2801
2802    /// Suggests a missing `super::` if that resolves to an correct module.
2803    ///
2804    /// ```text
2805    ///    |
2806    /// LL | use foo::Bar;
2807    ///    |     ^^^ did you mean `super::foo`?
2808    /// ```
2809    #[instrument(level = "debug", skip(self, parent_scope))]
2810    fn make_missing_super_suggestion(
2811        &mut self,
2812        mut path: Vec<Segment>,
2813        parent_scope: &ParentScope<'ra>,
2814    ) -> Option<(Vec<Segment>, Option<String>)> {
2815        // Replace first ident with `crate` and check if that is valid.
2816        path[0].ident.name = kw::Super;
2817        let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2818        debug!(?path, ?result);
2819        if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2820    }
2821
2822    /// Suggests a missing external crate name if that resolves to an correct module.
2823    ///
2824    /// ```text
2825    ///    |
2826    /// LL | use foobar::Baz;
2827    ///    |     ^^^^^^ did you mean `baz::foobar`?
2828    /// ```
2829    ///
2830    /// Used when importing a submodule of an external crate but missing that crate's
2831    /// name as the first part of path.
2832    #[instrument(level = "debug", skip(self, parent_scope))]
2833    fn make_external_crate_suggestion(
2834        &mut self,
2835        mut path: Vec<Segment>,
2836        parent_scope: &ParentScope<'ra>,
2837    ) -> Option<(Vec<Segment>, Option<String>)> {
2838        if path[1].ident.span.is_rust_2015() {
2839            return None;
2840        }
2841
2842        // Sort extern crate names in *reverse* order to get
2843        // 1) some consistent ordering for emitted diagnostics, and
2844        // 2) `std` suggestions before `core` suggestions.
2845        let mut extern_crate_names =
2846            self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2847        extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
2848
2849        for name in extern_crate_names.into_iter() {
2850            // Replace first ident with a crate name and check if that is valid.
2851            path[0].ident.name = name;
2852            let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2853            debug!(?path, ?name, ?result);
2854            if let PathResult::Module(..) = result {
2855                return Some((path, None));
2856            }
2857        }
2858
2859        None
2860    }
2861
2862    /// Suggests importing a macro from the root of the crate rather than a module within
2863    /// the crate.
2864    ///
2865    /// ```text
2866    /// help: a macro with this name exists at the root of the crate
2867    ///    |
2868    /// LL | use issue_59764::makro;
2869    ///    |     ^^^^^^^^^^^^^^^^^^
2870    ///    |
2871    ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
2872    ///            at the root of the crate instead of the module where it is defined
2873    /// ```
2874    pub(crate) fn check_for_module_export_macro(
2875        &mut self,
2876        import: Import<'ra>,
2877        module: ModuleOrUniformRoot<'ra>,
2878        ident: Ident,
2879    ) -> Option<(Option<Suggestion>, Option<String>)> {
2880        let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2881            return None;
2882        };
2883
2884        while let Some(parent) = crate_module.parent {
2885            crate_module = parent;
2886        }
2887
2888        if module == ModuleOrUniformRoot::Module(crate_module) {
2889            // Don't make a suggestion if the import was already from the root of the crate.
2890            return None;
2891        }
2892
2893        let binding_key = BindingKey::new(ident, MacroNS);
2894        let binding = self.resolution(crate_module, binding_key)?.binding()?;
2895        let Res::Def(DefKind::Macro(kinds), _) = binding.res() else {
2896            return None;
2897        };
2898        if !kinds.contains(MacroKinds::BANG) {
2899            return None;
2900        }
2901        let module_name = crate_module.kind.name().unwrap_or(kw::Crate);
2902        let import_snippet = match import.kind {
2903            ImportKind::Single { source, target, .. } if source != target => {
2904                format!("{source} as {target}")
2905            }
2906            _ => format!("{ident}"),
2907        };
2908
2909        let mut corrections: Vec<(Span, String)> = Vec::new();
2910        if !import.is_nested() {
2911            // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2912            // intermediate segments.
2913            corrections.push((import.span, format!("{module_name}::{import_snippet}")));
2914        } else {
2915            // Find the binding span (and any trailing commas and spaces).
2916            //   ie. `use a::b::{c, d, e};`
2917            //                      ^^^
2918            let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2919                self.tcx.sess,
2920                import.span,
2921                import.use_span,
2922            );
2923            debug!(found_closing_brace, ?binding_span);
2924
2925            let mut removal_span = binding_span;
2926
2927            // If the binding span ended with a closing brace, as in the below example:
2928            //   ie. `use a::b::{c, d};`
2929            //                      ^
2930            // Then expand the span of characters to remove to include the previous
2931            // binding's trailing comma.
2932            //   ie. `use a::b::{c, d};`
2933            //                    ^^^
2934            if found_closing_brace
2935                && let Some(previous_span) =
2936                    extend_span_to_previous_binding(self.tcx.sess, binding_span)
2937            {
2938                debug!(?previous_span);
2939                removal_span = removal_span.with_lo(previous_span.lo());
2940            }
2941            debug!(?removal_span);
2942
2943            // Remove the `removal_span`.
2944            corrections.push((removal_span, "".to_string()));
2945
2946            // Find the span after the crate name and if it has nested imports immediately
2947            // after the crate name already.
2948            //   ie. `use a::b::{c, d};`
2949            //               ^^^^^^^^^
2950            //   or  `use a::{b, c, d}};`
2951            //               ^^^^^^^^^^^
2952            let (has_nested, after_crate_name) =
2953                find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
2954            debug!(has_nested, ?after_crate_name);
2955
2956            let source_map = self.tcx.sess.source_map();
2957
2958            // Make sure this is actually crate-relative.
2959            let is_definitely_crate = import
2960                .module_path
2961                .first()
2962                .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
2963
2964            // Add the import to the start, with a `{` if required.
2965            let start_point = source_map.start_point(after_crate_name);
2966            if is_definitely_crate
2967                && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
2968            {
2969                corrections.push((
2970                    start_point,
2971                    if has_nested {
2972                        // In this case, `start_snippet` must equal '{'.
2973                        format!("{start_snippet}{import_snippet}, ")
2974                    } else {
2975                        // In this case, add a `{`, then the moved import, then whatever
2976                        // was there before.
2977                        format!("{{{import_snippet}, {start_snippet}")
2978                    },
2979                ));
2980
2981                // Add a `};` to the end if nested, matching the `{` added at the start.
2982                if !has_nested {
2983                    corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2984                }
2985            } else {
2986                // If the root import is module-relative, add the import separately
2987                corrections.push((
2988                    import.use_span.shrink_to_lo(),
2989                    format!("use {module_name}::{import_snippet};\n"),
2990                ));
2991            }
2992        }
2993
2994        let suggestion = Some((
2995            corrections,
2996            String::from("a macro with this name exists at the root of the crate"),
2997            Applicability::MaybeIncorrect,
2998        ));
2999        Some((
3000            suggestion,
3001            Some(
3002                "this could be because a macro annotated with `#[macro_export]` will be exported \
3003            at the root of the crate instead of the module where it is defined"
3004                    .to_string(),
3005            ),
3006        ))
3007    }
3008
3009    /// Finds a cfg-ed out item inside `module` with the matching name.
3010    pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
3011        let local_items;
3012        let symbols = if module.is_local() {
3013            local_items = self
3014                .stripped_cfg_items
3015                .iter()
3016                .filter_map(|item| {
3017                    let parent_module = self.opt_local_def_id(item.parent_module)?.to_def_id();
3018                    Some(StrippedCfgItem {
3019                        parent_module,
3020                        ident: item.ident,
3021                        cfg: item.cfg.clone(),
3022                    })
3023                })
3024                .collect::<Vec<_>>();
3025            local_items.as_slice()
3026        } else {
3027            self.tcx.stripped_cfg_items(module.krate)
3028        };
3029
3030        for &StrippedCfgItem { parent_module, ident, ref cfg } in symbols {
3031            if ident.name != *segment {
3032                continue;
3033            }
3034
3035            fn comes_from_same_module_for_glob(
3036                r: &Resolver<'_, '_>,
3037                parent_module: DefId,
3038                module: DefId,
3039                visited: &mut FxHashMap<DefId, bool>,
3040            ) -> bool {
3041                if let Some(&cached) = visited.get(&parent_module) {
3042                    // this branch is prevent from being called recursively infinity,
3043                    // because there has some cycles in globs imports,
3044                    // see more spec case at `tests/ui/cfg/diagnostics-reexport-2.rs#reexport32`
3045                    return cached;
3046                }
3047                visited.insert(parent_module, false);
3048                let m = r.expect_module(parent_module);
3049                let mut res = false;
3050                for importer in m.glob_importers.borrow().iter() {
3051                    if let Some(next_parent_module) = importer.parent_scope.module.opt_def_id() {
3052                        if next_parent_module == module
3053                            || comes_from_same_module_for_glob(
3054                                r,
3055                                next_parent_module,
3056                                module,
3057                                visited,
3058                            )
3059                        {
3060                            res = true;
3061                            break;
3062                        }
3063                    }
3064                }
3065                visited.insert(parent_module, res);
3066                res
3067            }
3068
3069            let comes_from_same_module = parent_module == module
3070                || comes_from_same_module_for_glob(
3071                    self,
3072                    parent_module,
3073                    module,
3074                    &mut Default::default(),
3075                );
3076            if !comes_from_same_module {
3077                continue;
3078            }
3079
3080            let item_was = if let CfgEntry::NameValue { value: Some((feature, _)), .. } = cfg.0 {
3081                errors::ItemWas::BehindFeature { feature, span: cfg.1 }
3082            } else {
3083                errors::ItemWas::CfgOut { span: cfg.1 }
3084            };
3085            let note = errors::FoundItemConfigureOut { span: ident.span, item_was };
3086            err.subdiagnostic(note);
3087        }
3088    }
3089}
3090
3091/// Given a `binding_span` of a binding within a use statement:
3092///
3093/// ```ignore (illustrative)
3094/// use foo::{a, b, c};
3095/// //           ^
3096/// ```
3097///
3098/// then return the span until the next binding or the end of the statement:
3099///
3100/// ```ignore (illustrative)
3101/// use foo::{a, b, c};
3102/// //           ^^^
3103/// ```
3104fn find_span_of_binding_until_next_binding(
3105    sess: &Session,
3106    binding_span: Span,
3107    use_span: Span,
3108) -> (bool, Span) {
3109    let source_map = sess.source_map();
3110
3111    // Find the span of everything after the binding.
3112    //   ie. `a, e};` or `a};`
3113    let binding_until_end = binding_span.with_hi(use_span.hi());
3114
3115    // Find everything after the binding but not including the binding.
3116    //   ie. `, e};` or `};`
3117    let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
3118
3119    // Keep characters in the span until we encounter something that isn't a comma or
3120    // whitespace.
3121    //   ie. `, ` or ``.
3122    //
3123    // Also note whether a closing brace character was encountered. If there
3124    // was, then later go backwards to remove any trailing commas that are left.
3125    let mut found_closing_brace = false;
3126    let after_binding_until_next_binding =
3127        source_map.span_take_while(after_binding_until_end, |&ch| {
3128            if ch == '}' {
3129                found_closing_brace = true;
3130            }
3131            ch == ' ' || ch == ','
3132        });
3133
3134    // Combine the two spans.
3135    //   ie. `a, ` or `a`.
3136    //
3137    // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
3138    let span = binding_span.with_hi(after_binding_until_next_binding.hi());
3139
3140    (found_closing_brace, span)
3141}
3142
3143/// Given a `binding_span`, return the span through to the comma or opening brace of the previous
3144/// binding.
3145///
3146/// ```ignore (illustrative)
3147/// use foo::a::{a, b, c};
3148/// //            ^^--- binding span
3149/// //            |
3150/// //            returned span
3151///
3152/// use foo::{a, b, c};
3153/// //        --- binding span
3154/// ```
3155fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
3156    let source_map = sess.source_map();
3157
3158    // `prev_source` will contain all of the source that came before the span.
3159    // Then split based on a command and take the first (ie. closest to our span)
3160    // snippet. In the example, this is a space.
3161    let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
3162
3163    let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
3164    let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
3165    if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
3166        return None;
3167    }
3168
3169    let prev_comma = prev_comma.first().unwrap();
3170    let prev_starting_brace = prev_starting_brace.first().unwrap();
3171
3172    // If the amount of source code before the comma is greater than
3173    // the amount of source code before the starting brace then we've only
3174    // got one item in the nested item (eg. `issue_52891::{self}`).
3175    if prev_comma.len() > prev_starting_brace.len() {
3176        return None;
3177    }
3178
3179    Some(binding_span.with_lo(BytePos(
3180        // Take away the number of bytes for the characters we've found and an
3181        // extra for the comma.
3182        binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
3183    )))
3184}
3185
3186/// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
3187/// it is a nested use tree.
3188///
3189/// ```ignore (illustrative)
3190/// use foo::a::{b, c};
3191/// //       ^^^^^^^^^^ -- false
3192///
3193/// use foo::{a, b, c};
3194/// //       ^^^^^^^^^^ -- true
3195///
3196/// use foo::{a, b::{c, d}};
3197/// //       ^^^^^^^^^^^^^^^ -- true
3198/// ```
3199#[instrument(level = "debug", skip(sess))]
3200fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
3201    let source_map = sess.source_map();
3202
3203    // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
3204    let mut num_colons = 0;
3205    // Find second colon.. `use issue_59764:`
3206    let until_second_colon = source_map.span_take_while(use_span, |c| {
3207        if *c == ':' {
3208            num_colons += 1;
3209        }
3210        !matches!(c, ':' if num_colons == 2)
3211    });
3212    // Find everything after the second colon.. `foo::{baz, makro};`
3213    let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
3214
3215    let mut found_a_non_whitespace_character = false;
3216    // Find the first non-whitespace character in `from_second_colon`.. `f`
3217    let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
3218        if found_a_non_whitespace_character {
3219            return false;
3220        }
3221        if !c.is_whitespace() {
3222            found_a_non_whitespace_character = true;
3223        }
3224        true
3225    });
3226
3227    // Find the first `{` in from_second_colon.. `foo::{`
3228    let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
3229
3230    (next_left_bracket == after_second_colon, from_second_colon)
3231}
3232
3233/// A suggestion has already been emitted, change the wording slightly to clarify that both are
3234/// independent options.
3235enum Instead {
3236    Yes,
3237    No,
3238}
3239
3240/// Whether an existing place with an `use` item was found.
3241enum FoundUse {
3242    Yes,
3243    No,
3244}
3245
3246/// Whether a binding is part of a pattern or a use statement. Used for diagnostics.
3247pub(crate) enum DiagMode {
3248    Normal,
3249    /// The binding is part of a pattern
3250    Pattern,
3251    /// The binding is part of a use statement
3252    Import {
3253        /// `true` means diagnostics is for unresolved import
3254        unresolved_import: bool,
3255        /// `true` mean add the tips afterward for case `use a::{b,c}`,
3256        /// rather than replacing within.
3257        append: bool,
3258    },
3259}
3260
3261pub(crate) fn import_candidates(
3262    tcx: TyCtxt<'_>,
3263    err: &mut Diag<'_>,
3264    // This is `None` if all placement locations are inside expansions
3265    use_placement_span: Option<Span>,
3266    candidates: &[ImportSuggestion],
3267    mode: DiagMode,
3268    append: &str,
3269) {
3270    show_candidates(
3271        tcx,
3272        err,
3273        use_placement_span,
3274        candidates,
3275        Instead::Yes,
3276        FoundUse::Yes,
3277        mode,
3278        vec![],
3279        append,
3280    );
3281}
3282
3283type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
3284
3285/// When an entity with a given name is not available in scope, we search for
3286/// entities with that name in all crates. This method allows outputting the
3287/// results of this search in a programmer-friendly way. If any entities are
3288/// found and suggested, returns `true`, otherwise returns `false`.
3289fn show_candidates(
3290    tcx: TyCtxt<'_>,
3291    err: &mut Diag<'_>,
3292    // This is `None` if all placement locations are inside expansions
3293    use_placement_span: Option<Span>,
3294    candidates: &[ImportSuggestion],
3295    instead: Instead,
3296    found_use: FoundUse,
3297    mode: DiagMode,
3298    path: Vec<Segment>,
3299    append: &str,
3300) -> bool {
3301    if candidates.is_empty() {
3302        return false;
3303    }
3304
3305    let mut showed = false;
3306    let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
3307    let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
3308
3309    candidates.iter().for_each(|c| {
3310        if c.accessible {
3311            // Don't suggest `#[doc(hidden)]` items from other crates
3312            if c.doc_visible {
3313                accessible_path_strings.push((
3314                    pprust::path_to_string(&c.path),
3315                    c.descr,
3316                    c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3317                    &c.note,
3318                    c.via_import,
3319                ))
3320            }
3321        } else {
3322            inaccessible_path_strings.push((
3323                pprust::path_to_string(&c.path),
3324                c.descr,
3325                c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3326                &c.note,
3327                c.via_import,
3328            ))
3329        }
3330    });
3331
3332    // we want consistent results across executions, but candidates are produced
3333    // by iterating through a hash map, so make sure they are ordered:
3334    for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
3335        path_strings.sort_by(|a, b| a.0.cmp(&b.0));
3336        path_strings.dedup_by(|a, b| a.0 == b.0);
3337        let core_path_strings =
3338            path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
3339        let std_path_strings =
3340            path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
3341        let foreign_crate_path_strings =
3342            path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
3343
3344        // We list the `crate` local paths first.
3345        // Then we list the `std`/`core` paths.
3346        if std_path_strings.len() == core_path_strings.len() {
3347            // Do not list `core::` paths if we are already listing the `std::` ones.
3348            path_strings.extend(std_path_strings);
3349        } else {
3350            path_strings.extend(std_path_strings);
3351            path_strings.extend(core_path_strings);
3352        }
3353        // List all paths from foreign crates last.
3354        path_strings.extend(foreign_crate_path_strings);
3355    }
3356
3357    if !accessible_path_strings.is_empty() {
3358        let (determiner, kind, s, name, through) =
3359            if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
3360                (
3361                    "this",
3362                    *descr,
3363                    "",
3364                    format!(" `{name}`"),
3365                    if *via_import { " through its public re-export" } else { "" },
3366                )
3367            } else {
3368                // Get the unique item kinds and if there's only one, we use the right kind name
3369                // instead of the more generic "items".
3370                let kinds = accessible_path_strings
3371                    .iter()
3372                    .map(|(_, descr, _, _, _)| *descr)
3373                    .collect::<UnordSet<&str>>();
3374                let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
3375                let s = if kind.ends_with('s') { "es" } else { "s" };
3376
3377                ("one of these", kind, s, String::new(), "")
3378            };
3379
3380        let instead = if let Instead::Yes = instead { " instead" } else { "" };
3381        let mut msg = if let DiagMode::Pattern = mode {
3382            format!(
3383                "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
3384                 pattern",
3385            )
3386        } else {
3387            format!("consider importing {determiner} {kind}{s}{through}{instead}")
3388        };
3389
3390        for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3391            err.note(note.clone());
3392        }
3393
3394        let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
3395            msg.push(':');
3396
3397            for candidate in accessible_path_strings {
3398                msg.push('\n');
3399                msg.push_str(&candidate.0);
3400            }
3401        };
3402
3403        if let Some(span) = use_placement_span {
3404            let (add_use, trailing) = match mode {
3405                DiagMode::Pattern => {
3406                    err.span_suggestions(
3407                        span,
3408                        msg,
3409                        accessible_path_strings.into_iter().map(|a| a.0),
3410                        Applicability::MaybeIncorrect,
3411                    );
3412                    return true;
3413                }
3414                DiagMode::Import { .. } => ("", ""),
3415                DiagMode::Normal => ("use ", ";\n"),
3416            };
3417            for candidate in &mut accessible_path_strings {
3418                // produce an additional newline to separate the new use statement
3419                // from the directly following item.
3420                let additional_newline = if let FoundUse::No = found_use
3421                    && let DiagMode::Normal = mode
3422                {
3423                    "\n"
3424                } else {
3425                    ""
3426                };
3427                candidate.0 =
3428                    format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
3429            }
3430
3431            match mode {
3432                DiagMode::Import { append: true, .. } => {
3433                    append_candidates(&mut msg, accessible_path_strings);
3434                    err.span_help(span, msg);
3435                }
3436                _ => {
3437                    err.span_suggestions_with_style(
3438                        span,
3439                        msg,
3440                        accessible_path_strings.into_iter().map(|a| a.0),
3441                        Applicability::MaybeIncorrect,
3442                        SuggestionStyle::ShowAlways,
3443                    );
3444                }
3445            }
3446
3447            if let [first, .., last] = &path[..] {
3448                let sp = first.ident.span.until(last.ident.span);
3449                // Our suggestion is empty, so make sure the span is not empty (or we'd ICE).
3450                // Can happen for derive-generated spans.
3451                if sp.can_be_used_for_suggestions() && !sp.is_empty() {
3452                    err.span_suggestion_verbose(
3453                        sp,
3454                        format!("if you import `{}`, refer to it directly", last.ident),
3455                        "",
3456                        Applicability::Unspecified,
3457                    );
3458                }
3459            }
3460        } else {
3461            append_candidates(&mut msg, accessible_path_strings);
3462            err.help(msg);
3463        }
3464        showed = true;
3465    }
3466    if !inaccessible_path_strings.is_empty()
3467        && (!matches!(mode, DiagMode::Import { unresolved_import: false, .. }))
3468    {
3469        let prefix =
3470            if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
3471        if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
3472            let msg = format!(
3473                "{prefix}{descr} `{name}`{} exists but is inaccessible",
3474                if let DiagMode::Pattern = mode { ", which" } else { "" }
3475            );
3476
3477            if let Some(source_span) = source_span {
3478                let span = tcx.sess.source_map().guess_head_span(*source_span);
3479                let mut multi_span = MultiSpan::from_span(span);
3480                multi_span.push_span_label(span, "not accessible");
3481                err.span_note(multi_span, msg);
3482            } else {
3483                err.note(msg);
3484            }
3485            if let Some(note) = (*note).as_deref() {
3486                err.note(note.to_string());
3487            }
3488        } else {
3489            let descr = inaccessible_path_strings
3490                .iter()
3491                .map(|&(_, descr, _, _, _)| descr)
3492                .all_equal_value()
3493                .unwrap_or("item");
3494            let plural_descr =
3495                if descr.ends_with('s') { format!("{descr}es") } else { format!("{descr}s") };
3496
3497            let mut msg = format!("{prefix}these {plural_descr} exist but are inaccessible");
3498            let mut has_colon = false;
3499
3500            let mut spans = Vec::new();
3501            for (name, _, source_span, _, _) in &inaccessible_path_strings {
3502                if let Some(source_span) = source_span {
3503                    let span = tcx.sess.source_map().guess_head_span(*source_span);
3504                    spans.push((name, span));
3505                } else {
3506                    if !has_colon {
3507                        msg.push(':');
3508                        has_colon = true;
3509                    }
3510                    msg.push('\n');
3511                    msg.push_str(name);
3512                }
3513            }
3514
3515            let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3516            for (name, span) in spans {
3517                multi_span.push_span_label(span, format!("`{name}`: not accessible"));
3518            }
3519
3520            for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3521                err.note(note.clone());
3522            }
3523
3524            err.span_note(multi_span, msg);
3525        }
3526        showed = true;
3527    }
3528    showed
3529}
3530
3531#[derive(Debug)]
3532struct UsePlacementFinder {
3533    target_module: NodeId,
3534    first_legal_span: Option<Span>,
3535    first_use_span: Option<Span>,
3536}
3537
3538impl UsePlacementFinder {
3539    fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3540        let mut finder =
3541            UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3542        finder.visit_crate(krate);
3543        if let Some(use_span) = finder.first_use_span {
3544            (Some(use_span), FoundUse::Yes)
3545        } else {
3546            (finder.first_legal_span, FoundUse::No)
3547        }
3548    }
3549}
3550
3551impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
3552    fn visit_crate(&mut self, c: &Crate) {
3553        if self.target_module == CRATE_NODE_ID {
3554            let inject = c.spans.inject_use_span;
3555            if is_span_suitable_for_use_injection(inject) {
3556                self.first_legal_span = Some(inject);
3557            }
3558            self.first_use_span = search_for_any_use_in_items(&c.items);
3559        } else {
3560            visit::walk_crate(self, c);
3561        }
3562    }
3563
3564    fn visit_item(&mut self, item: &'tcx ast::Item) {
3565        if self.target_module == item.id {
3566            if let ItemKind::Mod(_, _, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
3567                let inject = mod_spans.inject_use_span;
3568                if is_span_suitable_for_use_injection(inject) {
3569                    self.first_legal_span = Some(inject);
3570                }
3571                self.first_use_span = search_for_any_use_in_items(items);
3572            }
3573        } else {
3574            visit::walk_item(self, item);
3575        }
3576    }
3577}
3578
3579#[derive(Default)]
3580struct BindingVisitor {
3581    identifiers: Vec<Symbol>,
3582    spans: FxHashMap<Symbol, Vec<Span>>,
3583}
3584
3585impl<'tcx> Visitor<'tcx> for BindingVisitor {
3586    fn visit_pat(&mut self, pat: &ast::Pat) {
3587        if let ast::PatKind::Ident(_, ident, _) = pat.kind {
3588            self.identifiers.push(ident.name);
3589            self.spans.entry(ident.name).or_default().push(ident.span);
3590        }
3591        visit::walk_pat(self, pat);
3592    }
3593}
3594
3595fn search_for_any_use_in_items(items: &[Box<ast::Item>]) -> Option<Span> {
3596    for item in items {
3597        if let ItemKind::Use(..) = item.kind
3598            && is_span_suitable_for_use_injection(item.span)
3599        {
3600            let mut lo = item.span.lo();
3601            for attr in &item.attrs {
3602                if attr.span.eq_ctxt(item.span) {
3603                    lo = std::cmp::min(lo, attr.span.lo());
3604                }
3605            }
3606            return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3607        }
3608    }
3609    None
3610}
3611
3612fn is_span_suitable_for_use_injection(s: Span) -> bool {
3613    // don't suggest placing a use before the prelude
3614    // import or other generated ones
3615    !s.from_expansion()
3616}