rustc_resolve/
diagnostics.rs

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