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