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