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
53pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
55
56pub(crate) type LabelSuggestion = (Ident, bool);
59
60#[derive(Debug)]
61pub(crate) enum SuggestionTarget {
62 SimilarlyNamed,
64 SingleItem,
66}
67
68#[derive(Debug)]
69pub(crate) struct TypoSuggestion {
70 pub candidate: Symbol,
71 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#[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 pub doc_visible: bool,
109 pub via_import: bool,
110 pub note: Option<String>,
112 pub is_stable: bool,
113}
114
115fn 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 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 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 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 (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 (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 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 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 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 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 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 let (found_closing_brace, span) =
448 find_span_of_binding_until_next_binding(self.tcx.sess, binding_span, import.use_span);
449
450 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 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 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 if first_name != kw::PathRoot {
488 return;
489 }
490
491 match path.get(1) {
492 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
494 Some(_) => {}
496 None => return,
500 }
501
502 if let Some(binding) = second_binding
506 && let NameBindingKind::Import { import, .. } = binding.kind
507 && 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 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 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 Some((ident, false)) => (
746 (None, None),
747 Some(errs::UnreachableLabelWithSimilarNameExists {
748 ident_span: ident.span,
749 }),
750 ),
751 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 let (suggestion, mpart_suggestion) = if root {
765 (None, None)
766 } else {
767 let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
770
771 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 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 Some((ident, true)) => (
930 (
931 Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
932 Some(errs::UnreachableLabelSubSuggestion {
933 span,
934 ident_name: ident.name,
937 }),
938 ),
939 None,
940 ),
941 Some((ident, false)) => (
943 (None, None),
944 Some(errs::UnreachableLabelSubLabelUnreachable {
945 ident_span: ident.span,
946 }),
947 ),
948 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 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 parent_scope: &ParentScope<'ra>,
1024 ctxt: SyntaxContext,
1025 filter_fn: &impl Fn(Res) -> bool,
1026 ) {
1027 self.cm().visit_scopes(scope_set, parent_scope, ctxt, |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 }
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 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 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 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 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 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 if via_import && name_binding.is_possibly_imported_variant() {
1202 return;
1203 }
1204
1205 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 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 let mut segms = if lookup_ident.span.at_least_rust_2018() {
1232 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 && 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 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 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 if let Some(def_id) = name_binding.res().module_like_def_id() {
1311 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 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 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 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 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 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 self.cm().visit_scopes(
1475 ScopeSet::Macro(MacroKind::Derive),
1476 &parent_scope,
1477 ident.span.ctxt(),
1478 |this, scope, _use_prelude, _ctxt| {
1479 let Scope::Module(m, _) = scope else {
1480 return None;
1481 };
1482 for (_, resolution) in this.resolutions(m).borrow().iter() {
1483 let Some(binding) = resolution.borrow().best_binding() else {
1484 continue;
1485 };
1486 let Res::Def(DefKind::Macro(kinds), def_id) = binding.res() else {
1487 continue;
1488 };
1489 if !kinds.intersects(MacroKinds::ATTR | MacroKinds::DERIVE) {
1490 continue;
1491 }
1492 let _ = this.get_macro_by_def_id(def_id);
1495 }
1496 None::<()>
1497 },
1498 );
1499
1500 let is_expected =
1501 &|res: Res| res.macro_kinds().is_some_and(|k| k.contains(macro_kind.into()));
1502 let suggestion = self.early_lookup_typo_candidate(
1503 ScopeSet::Macro(macro_kind),
1504 parent_scope,
1505 ident,
1506 is_expected,
1507 );
1508 if !self.add_typo_suggestion(err, suggestion, ident.span) {
1509 self.detect_derive_attribute(err, ident, parent_scope, sugg_span);
1510 }
1511
1512 let import_suggestions =
1513 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1514 let (span, found_use) = match parent_scope.module.nearest_parent_mod().as_local() {
1515 Some(def_id) => UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id)),
1516 None => (None, FoundUse::No),
1517 };
1518 show_candidates(
1519 self.tcx,
1520 err,
1521 span,
1522 &import_suggestions,
1523 Instead::No,
1524 found_use,
1525 DiagMode::Normal,
1526 vec![],
1527 "",
1528 );
1529
1530 if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1531 let label_span = ident.span.shrink_to_hi();
1532 let mut spans = MultiSpan::from_span(label_span);
1533 spans.push_span_label(label_span, "put a macro name here");
1534 err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1535 return;
1536 }
1537
1538 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1539 err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1540 return;
1541 }
1542
1543 let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1544 if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1545 });
1546
1547 if let Some((def_id, unused_ident)) = unused_macro {
1548 let scope = self.local_macro_def_scopes[&def_id];
1549 let parent_nearest = parent_scope.module.nearest_parent_mod();
1550 let unused_macro_kinds = self.local_macro_map[def_id].ext.macro_kinds();
1551 if !unused_macro_kinds.contains(macro_kind.into()) {
1552 match macro_kind {
1553 MacroKind::Bang => {
1554 err.subdiagnostic(MacroRulesNot::Func { span: unused_ident.span, ident });
1555 }
1556 MacroKind::Attr => {
1557 err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1558 }
1559 MacroKind::Derive => {
1560 err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1561 }
1562 }
1563 return;
1564 }
1565 if Some(parent_nearest) == scope.opt_def_id() {
1566 err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1567 err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1568 return;
1569 }
1570 }
1571
1572 if ident.name == kw::Default
1573 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1574 {
1575 let span = self.def_span(def_id);
1576 let source_map = self.tcx.sess.source_map();
1577 let head_span = source_map.guess_head_span(span);
1578 err.subdiagnostic(ConsiderAddingADerive {
1579 span: head_span.shrink_to_lo(),
1580 suggestion: "#[derive(Default)]\n".to_string(),
1581 });
1582 }
1583 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1584 let Ok(binding) = self.cm().early_resolve_ident_in_lexical_scope(
1585 ident,
1586 ScopeSet::All(ns),
1587 parent_scope,
1588 None,
1589 false,
1590 None,
1591 None,
1592 ) else {
1593 continue;
1594 };
1595
1596 let desc = match binding.res() {
1597 Res::Def(DefKind::Macro(MacroKinds::BANG), _) => {
1598 "a function-like macro".to_string()
1599 }
1600 Res::Def(DefKind::Macro(MacroKinds::ATTR), _) | Res::NonMacroAttr(..) => {
1601 format!("an attribute: `#[{ident}]`")
1602 }
1603 Res::Def(DefKind::Macro(MacroKinds::DERIVE), _) => {
1604 format!("a derive macro: `#[derive({ident})]`")
1605 }
1606 Res::Def(DefKind::Macro(kinds), _) => {
1607 format!("{} {}", kinds.article(), kinds.descr())
1608 }
1609 Res::ToolMod => {
1610 continue;
1612 }
1613 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1614 "only a trait, without a derive macro".to_string()
1615 }
1616 res => format!(
1617 "{} {}, not {} {}",
1618 res.article(),
1619 res.descr(),
1620 macro_kind.article(),
1621 macro_kind.descr_expected(),
1622 ),
1623 };
1624 if let crate::NameBindingKind::Import { import, .. } = binding.kind
1625 && !import.span.is_dummy()
1626 {
1627 let note = errors::IdentImporterHereButItIsDesc {
1628 span: import.span,
1629 imported_ident: ident,
1630 imported_ident_desc: &desc,
1631 };
1632 err.subdiagnostic(note);
1633 self.record_use(ident, binding, Used::Other);
1636 return;
1637 }
1638 let note = errors::IdentInScopeButItIsDesc {
1639 imported_ident: ident,
1640 imported_ident_desc: &desc,
1641 };
1642 err.subdiagnostic(note);
1643 return;
1644 }
1645
1646 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1647 err.subdiagnostic(AddedMacroUse);
1648 return;
1649 }
1650 }
1651
1652 fn detect_derive_attribute(
1655 &self,
1656 err: &mut Diag<'_>,
1657 ident: Ident,
1658 parent_scope: &ParentScope<'ra>,
1659 sugg_span: Option<Span>,
1660 ) {
1661 let mut derives = vec![];
1666 let mut all_attrs: UnordMap<Symbol, Vec<_>> = UnordMap::default();
1667 #[allow(rustc::potential_query_instability)]
1669 for (def_id, data) in self
1670 .local_macro_map
1671 .iter()
1672 .map(|(local_id, data)| (local_id.to_def_id(), data))
1673 .chain(self.extern_macro_map.borrow().iter().map(|(id, d)| (*id, d)))
1674 {
1675 for helper_attr in &data.ext.helper_attrs {
1676 let item_name = self.tcx.item_name(def_id);
1677 all_attrs.entry(*helper_attr).or_default().push(item_name);
1678 if helper_attr == &ident.name {
1679 derives.push(item_name);
1680 }
1681 }
1682 }
1683 let kind = MacroKind::Derive.descr();
1684 if !derives.is_empty() {
1685 let mut derives: Vec<String> = derives.into_iter().map(|d| d.to_string()).collect();
1687 derives.sort();
1688 derives.dedup();
1689 let msg = match &derives[..] {
1690 [derive] => format!(" `{derive}`"),
1691 [start @ .., last] => format!(
1692 "s {} and `{last}`",
1693 start.iter().map(|d| format!("`{d}`")).collect::<Vec<_>>().join(", ")
1694 ),
1695 [] => unreachable!("we checked for this to be non-empty 10 lines above!?"),
1696 };
1697 let msg = format!(
1698 "`{}` is an attribute that can be used by the {kind}{msg}, you might be \
1699 missing a `derive` attribute",
1700 ident.name,
1701 );
1702 let sugg_span = if let ModuleKind::Def(DefKind::Enum, id, _) = parent_scope.module.kind
1703 {
1704 let span = self.def_span(id);
1705 if span.from_expansion() {
1706 None
1707 } else {
1708 Some(span.shrink_to_lo())
1710 }
1711 } else {
1712 sugg_span
1714 };
1715 match sugg_span {
1716 Some(span) => {
1717 err.span_suggestion_verbose(
1718 span,
1719 msg,
1720 format!("#[derive({})]\n", derives.join(", ")),
1721 Applicability::MaybeIncorrect,
1722 );
1723 }
1724 None => {
1725 err.note(msg);
1726 }
1727 }
1728 } else {
1729 let all_attr_names = all_attrs.keys().map(|s| *s).into_sorted_stable_ord();
1731 if let Some(best_match) = find_best_match_for_name(&all_attr_names, ident.name, None)
1732 && let Some(macros) = all_attrs.get(&best_match)
1733 {
1734 let mut macros: Vec<String> = macros.into_iter().map(|d| d.to_string()).collect();
1735 macros.sort();
1736 macros.dedup();
1737 let msg = match ¯os[..] {
1738 [] => return,
1739 [name] => format!(" `{name}` accepts"),
1740 [start @ .., end] => format!(
1741 "s {} and `{end}` accept",
1742 start.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", "),
1743 ),
1744 };
1745 let msg = format!("the {kind}{msg} the similarly named `{best_match}` attribute");
1746 err.span_suggestion_verbose(
1747 ident.span,
1748 msg,
1749 best_match,
1750 Applicability::MaybeIncorrect,
1751 );
1752 }
1753 }
1754 }
1755
1756 pub(crate) fn add_typo_suggestion(
1757 &self,
1758 err: &mut Diag<'_>,
1759 suggestion: Option<TypoSuggestion>,
1760 span: Span,
1761 ) -> bool {
1762 let suggestion = match suggestion {
1763 None => return false,
1764 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1766 Some(suggestion) => suggestion,
1767 };
1768
1769 let mut did_label_def_span = false;
1770
1771 if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1772 if span.overlaps(def_span) {
1773 return false;
1792 }
1793 let span = self.tcx.sess.source_map().guess_head_span(def_span);
1794 let candidate_descr = suggestion.res.descr();
1795 let candidate = suggestion.candidate;
1796 let label = match suggestion.target {
1797 SuggestionTarget::SimilarlyNamed => {
1798 errors::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
1799 }
1800 SuggestionTarget::SingleItem => {
1801 errors::DefinedHere::SingleItem { span, candidate_descr, candidate }
1802 }
1803 };
1804 did_label_def_span = true;
1805 err.subdiagnostic(label);
1806 }
1807
1808 let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
1809 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1810 && let Some(span) = suggestion.span
1811 && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
1812 && snippet == candidate
1813 {
1814 let candidate = suggestion.candidate;
1815 let msg = format!(
1818 "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
1819 );
1820 if !did_label_def_span {
1821 err.span_label(span, format!("`{candidate}` defined here"));
1822 }
1823 (span, msg, snippet)
1824 } else {
1825 let msg = match suggestion.target {
1826 SuggestionTarget::SimilarlyNamed => format!(
1827 "{} {} with a similar name exists",
1828 suggestion.res.article(),
1829 suggestion.res.descr()
1830 ),
1831 SuggestionTarget::SingleItem => {
1832 format!("maybe you meant this {}", suggestion.res.descr())
1833 }
1834 };
1835 (span, msg, suggestion.candidate.to_ident_string())
1836 };
1837 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1838 true
1839 }
1840
1841 fn binding_description(&self, b: NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1842 let res = b.res();
1843 if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
1844 let add_built_in =
1846 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1847 let (built_in, from) = if from_prelude {
1848 ("", " from prelude")
1849 } else if b.is_extern_crate()
1850 && !b.is_import()
1851 && self.tcx.sess.opts.externs.get(ident.as_str()).is_some()
1852 {
1853 ("", " passed with `--extern`")
1854 } else if add_built_in {
1855 (" built-in", "")
1856 } else {
1857 ("", "")
1858 };
1859
1860 let a = if built_in.is_empty() { res.article() } else { "a" };
1861 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1862 } else {
1863 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1864 format!("the {thing} {introduced} here", thing = res.descr())
1865 }
1866 }
1867
1868 fn ambiguity_diagnostics(&self, ambiguity_error: &AmbiguityError<'ra>) -> AmbiguityErrorDiag {
1869 let AmbiguityError { kind, ident, b1, b2, misc1, misc2, .. } = *ambiguity_error;
1870 let extern_prelude_ambiguity = || {
1871 self.extern_prelude.get(&Macros20NormalizedIdent::new(ident)).is_some_and(|entry| {
1872 entry.item_binding == Some(b1) && entry.flag_binding.get() == Some(b2)
1873 })
1874 };
1875 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1876 (b2, b1, misc2, misc1, true)
1878 } else {
1879 (b1, b2, misc1, misc2, false)
1880 };
1881
1882 let could_refer_to = |b: NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1883 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1884 let note_msg = format!("`{ident}` could{also} refer to {what}");
1885
1886 let thing = b.res().descr();
1887 let mut help_msgs = Vec::new();
1888 if b.is_glob_import()
1889 && (kind == AmbiguityKind::GlobVsGlob
1890 || kind == AmbiguityKind::GlobVsExpanded
1891 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1892 {
1893 help_msgs.push(format!(
1894 "consider adding an explicit import of `{ident}` to disambiguate"
1895 ))
1896 }
1897 if b.is_extern_crate() && ident.span.at_least_rust_2018() && !extern_prelude_ambiguity()
1898 {
1899 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1900 }
1901 match misc {
1902 AmbiguityErrorMisc::SuggestCrate => help_msgs
1903 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously")),
1904 AmbiguityErrorMisc::SuggestSelf => help_msgs
1905 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously")),
1906 AmbiguityErrorMisc::FromPrelude | AmbiguityErrorMisc::None => {}
1907 }
1908
1909 (
1910 b.span,
1911 note_msg,
1912 help_msgs
1913 .iter()
1914 .enumerate()
1915 .map(|(i, help_msg)| {
1916 let or = if i == 0 { "" } else { "or " };
1917 format!("{or}{help_msg}")
1918 })
1919 .collect::<Vec<_>>(),
1920 )
1921 };
1922 let (b1_span, b1_note_msg, b1_help_msgs) = could_refer_to(b1, misc1, "");
1923 let (b2_span, b2_note_msg, b2_help_msgs) = could_refer_to(b2, misc2, " also");
1924
1925 AmbiguityErrorDiag {
1926 msg: format!("`{ident}` is ambiguous"),
1927 span: ident.span,
1928 label_span: ident.span,
1929 label_msg: "ambiguous name".to_string(),
1930 note_msg: format!("ambiguous because of {}", kind.descr()),
1931 b1_span,
1932 b1_note_msg,
1933 b1_help_msgs,
1934 b2_span,
1935 b2_note_msg,
1936 b2_help_msgs,
1937 }
1938 }
1939
1940 fn ctor_fields_span(&self, binding: NameBinding<'_>) -> Option<Span> {
1943 let NameBindingKind::Res(Res::Def(
1944 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
1945 ctor_def_id,
1946 )) = binding.kind
1947 else {
1948 return None;
1949 };
1950
1951 let def_id = self.tcx.parent(ctor_def_id);
1952 self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) }
1954
1955 fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
1956 let PrivacyError {
1957 ident,
1958 binding,
1959 outermost_res,
1960 parent_scope,
1961 single_nested,
1962 dedup_span,
1963 ref source,
1964 } = *privacy_error;
1965
1966 let res = binding.res();
1967 let ctor_fields_span = self.ctor_fields_span(binding);
1968 let plain_descr = res.descr().to_string();
1969 let nonimport_descr =
1970 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1971 let import_descr = nonimport_descr.clone() + " import";
1972 let get_descr =
1973 |b: NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1974
1975 let ident_descr = get_descr(binding);
1977 let mut err =
1978 self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
1979
1980 self.mention_default_field_values(source, ident, &mut err);
1981
1982 let mut not_publicly_reexported = false;
1983 if let Some((this_res, outer_ident)) = outermost_res {
1984 let import_suggestions = self.lookup_import_candidates(
1985 outer_ident,
1986 this_res.ns().unwrap_or(Namespace::TypeNS),
1987 &parent_scope,
1988 &|res: Res| res == this_res,
1989 );
1990 let point_to_def = !show_candidates(
1991 self.tcx,
1992 &mut err,
1993 Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
1994 &import_suggestions,
1995 Instead::Yes,
1996 FoundUse::Yes,
1997 DiagMode::Import { append: single_nested, unresolved_import: false },
1998 vec![],
1999 "",
2000 );
2001 if point_to_def && ident.span != outer_ident.span {
2003 not_publicly_reexported = true;
2004 let label = errors::OuterIdentIsNotPubliclyReexported {
2005 span: outer_ident.span,
2006 outer_ident_descr: this_res.descr(),
2007 outer_ident,
2008 };
2009 err.subdiagnostic(label);
2010 }
2011 }
2012
2013 let mut non_exhaustive = None;
2014 if let Some(def_id) = res.opt_def_id()
2018 && !def_id.is_local()
2019 && let Some(attr_span) = find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::NonExhaustive(span) => *span)
2020 {
2021 non_exhaustive = Some(attr_span);
2022 } else if let Some(span) = ctor_fields_span {
2023 let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
2024 err.subdiagnostic(label);
2025 if let Res::Def(_, d) = res
2026 && let Some(fields) = self.field_visibility_spans.get(&d)
2027 {
2028 let spans = fields.iter().map(|span| *span).collect();
2029 let sugg =
2030 errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
2031 err.subdiagnostic(sugg);
2032 }
2033 }
2034
2035 let mut sugg_paths: Vec<(Vec<Ident>, bool)> = vec![];
2036 if let Some(mut def_id) = res.opt_def_id() {
2037 let mut path = vec![def_id];
2039 while let Some(parent) = self.tcx.opt_parent(def_id) {
2040 def_id = parent;
2041 if !def_id.is_top_level_module() {
2042 path.push(def_id);
2043 } else {
2044 break;
2045 }
2046 }
2047 let path_names: Option<Vec<Ident>> = path
2049 .iter()
2050 .rev()
2051 .map(|def_id| {
2052 self.tcx.opt_item_name(*def_id).map(|name| {
2053 Ident::with_dummy_span(if def_id.is_top_level_module() {
2054 kw::Crate
2055 } else {
2056 name
2057 })
2058 })
2059 })
2060 .collect();
2061 if let Some(def_id) = path.get(0)
2062 && let Some(path) = path_names
2063 {
2064 if let Some(def_id) = def_id.as_local() {
2065 if self.effective_visibilities.is_directly_public(def_id) {
2066 sugg_paths.push((path, false));
2067 }
2068 } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
2069 {
2070 sugg_paths.push((path, false));
2071 }
2072 }
2073 }
2074
2075 let first_binding = binding;
2077 let mut next_binding = Some(binding);
2078 let mut next_ident = ident;
2079 let mut path = vec![];
2080 while let Some(binding) = next_binding {
2081 let name = next_ident;
2082 next_binding = match binding.kind {
2083 _ if res == Res::Err => None,
2084 NameBindingKind::Import { binding, import, .. } => match import.kind {
2085 _ if binding.span.is_dummy() => None,
2086 ImportKind::Single { source, .. } => {
2087 next_ident = source;
2088 Some(binding)
2089 }
2090 ImportKind::Glob { .. }
2091 | ImportKind::MacroUse { .. }
2092 | ImportKind::MacroExport => Some(binding),
2093 ImportKind::ExternCrate { .. } => None,
2094 },
2095 _ => None,
2096 };
2097
2098 match binding.kind {
2099 NameBindingKind::Import { import, .. } => {
2100 for segment in import.module_path.iter().skip(1) {
2101 path.push(segment.ident);
2102 }
2103 sugg_paths.push((
2104 path.iter().cloned().chain(std::iter::once(ident)).collect::<Vec<_>>(),
2105 true, ));
2107 }
2108 NameBindingKind::Res(_) => {}
2109 }
2110 let first = binding == first_binding;
2111 let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
2112 let mut note_span = MultiSpan::from_span(def_span);
2113 if !first && binding.vis.is_public() {
2114 let desc = match binding.kind {
2115 NameBindingKind::Import { .. } => "re-export",
2116 _ => "directly",
2117 };
2118 note_span.push_span_label(def_span, format!("you could import this {desc}"));
2119 }
2120 if next_binding.is_none()
2123 && let Some(span) = non_exhaustive
2124 {
2125 note_span.push_span_label(
2126 span,
2127 "cannot be constructed because it is `#[non_exhaustive]`",
2128 );
2129 }
2130 let note = errors::NoteAndRefersToTheItemDefinedHere {
2131 span: note_span,
2132 binding_descr: get_descr(binding),
2133 binding_name: name,
2134 first,
2135 dots: next_binding.is_some(),
2136 };
2137 err.subdiagnostic(note);
2138 }
2139 sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0].name == sym::core, *reexport));
2141 for (sugg, reexport) in sugg_paths {
2142 if not_publicly_reexported {
2143 break;
2144 }
2145 if sugg.len() <= 1 {
2146 continue;
2149 }
2150 let path = join_path_idents(sugg);
2151 let sugg = if reexport {
2152 errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
2153 } else {
2154 errors::ImportIdent::Directly { span: dedup_span, ident, path }
2155 };
2156 err.subdiagnostic(sugg);
2157 break;
2158 }
2159
2160 err.emit();
2161 }
2162
2163 fn mention_default_field_values(
2183 &self,
2184 source: &Option<ast::Expr>,
2185 ident: Ident,
2186 err: &mut Diag<'_>,
2187 ) {
2188 let Some(expr) = source else { return };
2189 let ast::ExprKind::Struct(struct_expr) = &expr.kind else { return };
2190 let Some(Res::Def(_, def_id)) =
2193 self.partial_res_map[&struct_expr.path.segments.iter().last().unwrap().id].full_res()
2194 else {
2195 return;
2196 };
2197 let Some(default_fields) = self.field_defaults(def_id) else { return };
2198 if struct_expr.fields.is_empty() {
2199 return;
2200 }
2201 let last_span = struct_expr.fields.iter().last().unwrap().span;
2202 let mut iter = struct_expr.fields.iter().peekable();
2203 let mut prev: Option<Span> = None;
2204 while let Some(field) = iter.next() {
2205 if field.expr.span.overlaps(ident.span) {
2206 err.span_label(field.ident.span, "while setting this field");
2207 if default_fields.contains(&field.ident.name) {
2208 let sugg = if last_span == field.span {
2209 vec![(field.span, "..".to_string())]
2210 } else {
2211 vec![
2212 (
2213 match (prev, iter.peek()) {
2215 (_, Some(next)) => field.span.with_hi(next.span.lo()),
2216 (Some(prev), _) => field.span.with_lo(prev.hi()),
2217 (None, None) => field.span,
2218 },
2219 String::new(),
2220 ),
2221 (last_span.shrink_to_hi(), ", ..".to_string()),
2222 ]
2223 };
2224 err.multipart_suggestion_verbose(
2225 format!(
2226 "the type `{ident}` of field `{}` is private, but you can construct \
2227 the default value defined for it in `{}` using `..` in the struct \
2228 initializer expression",
2229 field.ident,
2230 self.tcx.item_name(def_id),
2231 ),
2232 sugg,
2233 Applicability::MachineApplicable,
2234 );
2235 break;
2236 }
2237 }
2238 prev = Some(field.span);
2239 }
2240 }
2241
2242 pub(crate) fn find_similarly_named_module_or_crate(
2243 &self,
2244 ident: Symbol,
2245 current_module: Module<'ra>,
2246 ) -> Option<Symbol> {
2247 let mut candidates = self
2248 .extern_prelude
2249 .keys()
2250 .map(|ident| ident.name)
2251 .chain(
2252 self.local_module_map
2253 .iter()
2254 .filter(|(_, module)| {
2255 current_module.is_ancestor_of(**module) && current_module != **module
2256 })
2257 .flat_map(|(_, module)| module.kind.name()),
2258 )
2259 .chain(
2260 self.extern_module_map
2261 .borrow()
2262 .iter()
2263 .filter(|(_, module)| {
2264 current_module.is_ancestor_of(**module) && current_module != **module
2265 })
2266 .flat_map(|(_, module)| module.kind.name()),
2267 )
2268 .filter(|c| !c.to_string().is_empty())
2269 .collect::<Vec<_>>();
2270 candidates.sort();
2271 candidates.dedup();
2272 find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
2273 }
2274
2275 pub(crate) fn report_path_resolution_error(
2276 &mut self,
2277 path: &[Segment],
2278 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
2280 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
2281 ignore_binding: Option<NameBinding<'ra>>,
2282 ignore_import: Option<Import<'ra>>,
2283 module: Option<ModuleOrUniformRoot<'ra>>,
2284 failed_segment_idx: usize,
2285 ident: Ident,
2286 ) -> (String, Option<Suggestion>) {
2287 let is_last = failed_segment_idx == path.len() - 1;
2288 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2289 let module_res = match module {
2290 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2291 _ => None,
2292 };
2293 if module_res == self.graph_root.res() {
2294 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
2295 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2296 candidates
2297 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2298 if let Some(candidate) = candidates.get(0) {
2299 let path = {
2300 let len = candidate.path.segments.len();
2302 let start_index = (0..=failed_segment_idx.min(len - 1))
2303 .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2304 .unwrap_or_default();
2305 let segments =
2306 (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2307 Path { segments, span: Span::default(), tokens: None }
2308 };
2309 (
2310 String::from("unresolved import"),
2311 Some((
2312 vec![(ident.span, pprust::path_to_string(&path))],
2313 String::from("a similar path exists"),
2314 Applicability::MaybeIncorrect,
2315 )),
2316 )
2317 } else if ident.name == sym::core {
2318 (
2319 format!("you might be missing crate `{ident}`"),
2320 Some((
2321 vec![(ident.span, "std".to_string())],
2322 "try using `std` instead of `core`".to_string(),
2323 Applicability::MaybeIncorrect,
2324 )),
2325 )
2326 } else if ident.name == kw::Underscore {
2327 (format!("`_` is not a valid crate or module name"), None)
2328 } else if self.tcx.sess.is_rust_2015() {
2329 (
2330 format!("use of unresolved module or unlinked crate `{ident}`"),
2331 Some((
2332 vec![(
2333 self.current_crate_outer_attr_insert_span,
2334 format!("extern crate {ident};\n"),
2335 )],
2336 if was_invoked_from_cargo() {
2337 format!(
2338 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2339 to add it to your `Cargo.toml` and import it in your code",
2340 )
2341 } else {
2342 format!(
2343 "you might be missing a crate named `{ident}`, add it to your \
2344 project and import it in your code",
2345 )
2346 },
2347 Applicability::MaybeIncorrect,
2348 )),
2349 )
2350 } else {
2351 (format!("could not find `{ident}` in the crate root"), None)
2352 }
2353 } else if failed_segment_idx > 0 {
2354 let parent = path[failed_segment_idx - 1].ident.name;
2355 let parent = match parent {
2356 kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2359 "the list of imported crates".to_owned()
2360 }
2361 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2362 _ => format!("`{parent}`"),
2363 };
2364
2365 let mut msg = format!("could not find `{ident}` in {parent}");
2366 if ns == TypeNS || ns == ValueNS {
2367 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2368 let binding = if let Some(module) = module {
2369 self.cm()
2370 .resolve_ident_in_module(
2371 module,
2372 ident,
2373 ns_to_try,
2374 parent_scope,
2375 None,
2376 ignore_binding,
2377 ignore_import,
2378 )
2379 .ok()
2380 } else if let Some(ribs) = ribs
2381 && let Some(TypeNS | ValueNS) = opt_ns
2382 {
2383 assert!(ignore_import.is_none());
2384 match self.resolve_ident_in_lexical_scope(
2385 ident,
2386 ns_to_try,
2387 parent_scope,
2388 None,
2389 &ribs[ns_to_try],
2390 ignore_binding,
2391 ) {
2392 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
2394 _ => None,
2395 }
2396 } else {
2397 self.cm()
2398 .early_resolve_ident_in_lexical_scope(
2399 ident,
2400 ScopeSet::All(ns_to_try),
2401 parent_scope,
2402 None,
2403 false,
2404 ignore_binding,
2405 ignore_import,
2406 )
2407 .ok()
2408 };
2409 if let Some(binding) = binding {
2410 msg = format!(
2411 "expected {}, found {} `{ident}` in {parent}",
2412 ns.descr(),
2413 binding.res().descr(),
2414 );
2415 };
2416 }
2417 (msg, None)
2418 } else if ident.name == kw::SelfUpper {
2419 if opt_ns.is_none() {
2423 ("`Self` cannot be used in imports".to_string(), None)
2424 } else {
2425 (
2426 "`Self` is only available in impls, traits, and type definitions".to_string(),
2427 None,
2428 )
2429 }
2430 } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2431 let binding = if let Some(ribs) = ribs {
2433 assert!(ignore_import.is_none());
2434 self.resolve_ident_in_lexical_scope(
2435 ident,
2436 ValueNS,
2437 parent_scope,
2438 None,
2439 &ribs[ValueNS],
2440 ignore_binding,
2441 )
2442 } else {
2443 None
2444 };
2445 let match_span = match binding {
2446 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
2455 Some(*self.pat_span_map.get(&id).unwrap())
2456 }
2457 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
2469 _ => None,
2470 };
2471 let suggestion = match_span.map(|span| {
2472 (
2473 vec![(span, String::from(""))],
2474 format!("`{ident}` is defined here, but is not a type"),
2475 Applicability::MaybeIncorrect,
2476 )
2477 });
2478
2479 (format!("use of undeclared type `{ident}`"), suggestion)
2480 } else {
2481 let mut suggestion = None;
2482 if ident.name == sym::alloc {
2483 suggestion = Some((
2484 vec![],
2485 String::from("add `extern crate alloc` to use the `alloc` crate"),
2486 Applicability::MaybeIncorrect,
2487 ))
2488 }
2489
2490 suggestion = suggestion.or_else(|| {
2491 self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2492 |sugg| {
2493 (
2494 vec![(ident.span, sugg.to_string())],
2495 String::from("there is a crate or module with a similar name"),
2496 Applicability::MaybeIncorrect,
2497 )
2498 },
2499 )
2500 });
2501 if let Ok(binding) = self.cm().early_resolve_ident_in_lexical_scope(
2502 ident,
2503 ScopeSet::All(ValueNS),
2504 parent_scope,
2505 None,
2506 false,
2507 ignore_binding,
2508 ignore_import,
2509 ) {
2510 let descr = binding.res().descr();
2511 (format!("{descr} `{ident}` is not a crate or module"), suggestion)
2512 } else {
2513 let suggestion = if suggestion.is_some() {
2514 suggestion
2515 } else if let Some(m) = self.undeclared_module_exists(ident) {
2516 self.undeclared_module_suggest_declare(ident, m)
2517 } else if was_invoked_from_cargo() {
2518 Some((
2519 vec![],
2520 format!(
2521 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2522 to add it to your `Cargo.toml`",
2523 ),
2524 Applicability::MaybeIncorrect,
2525 ))
2526 } else {
2527 Some((
2528 vec![],
2529 format!("you might be missing a crate named `{ident}`",),
2530 Applicability::MaybeIncorrect,
2531 ))
2532 };
2533 (format!("use of unresolved module or unlinked crate `{ident}`"), suggestion)
2534 }
2535 }
2536 }
2537
2538 fn undeclared_module_suggest_declare(
2539 &self,
2540 ident: Ident,
2541 path: std::path::PathBuf,
2542 ) -> Option<(Vec<(Span, String)>, String, Applicability)> {
2543 Some((
2544 vec![(self.current_crate_outer_attr_insert_span, format!("mod {ident};\n"))],
2545 format!(
2546 "to make use of source file {}, use `mod {ident}` \
2547 in this file to declare the module",
2548 path.display()
2549 ),
2550 Applicability::MaybeIncorrect,
2551 ))
2552 }
2553
2554 fn undeclared_module_exists(&self, ident: Ident) -> Option<std::path::PathBuf> {
2555 let map = self.tcx.sess.source_map();
2556
2557 let src = map.span_to_filename(ident.span).into_local_path()?;
2558 let i = ident.as_str();
2559 let dir = src.parent()?;
2561 let src = src.file_stem()?.to_str()?;
2562 for file in [
2563 dir.join(i).with_extension("rs"),
2565 dir.join(i).join("mod.rs"),
2567 ] {
2568 if file.exists() {
2569 return Some(file);
2570 }
2571 }
2572 if !matches!(src, "main" | "lib" | "mod") {
2573 for file in [
2574 dir.join(src).join(i).with_extension("rs"),
2576 dir.join(src).join(i).join("mod.rs"),
2578 ] {
2579 if file.exists() {
2580 return Some(file);
2581 }
2582 }
2583 }
2584 None
2585 }
2586
2587 #[instrument(level = "debug", skip(self, parent_scope))]
2589 pub(crate) fn make_path_suggestion(
2590 &mut self,
2591 mut path: Vec<Segment>,
2592 parent_scope: &ParentScope<'ra>,
2593 ) -> Option<(Vec<Segment>, Option<String>)> {
2594 match path[..] {
2595 [first, second, ..]
2598 if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2599 [first, ..]
2601 if first.ident.span.at_least_rust_2018()
2602 && !first.ident.is_path_segment_keyword() =>
2603 {
2604 path.insert(0, Segment::from_ident(Ident::dummy()));
2606 }
2607 _ => return None,
2608 }
2609
2610 self.make_missing_self_suggestion(path.clone(), parent_scope)
2611 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2612 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2613 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2614 }
2615
2616 #[instrument(level = "debug", skip(self, parent_scope))]
2624 fn make_missing_self_suggestion(
2625 &mut self,
2626 mut path: Vec<Segment>,
2627 parent_scope: &ParentScope<'ra>,
2628 ) -> Option<(Vec<Segment>, Option<String>)> {
2629 path[0].ident.name = kw::SelfLower;
2631 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2632 debug!(?path, ?result);
2633 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2634 }
2635
2636 #[instrument(level = "debug", skip(self, parent_scope))]
2644 fn make_missing_crate_suggestion(
2645 &mut self,
2646 mut path: Vec<Segment>,
2647 parent_scope: &ParentScope<'ra>,
2648 ) -> Option<(Vec<Segment>, Option<String>)> {
2649 path[0].ident.name = kw::Crate;
2651 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2652 debug!(?path, ?result);
2653 if let PathResult::Module(..) = result {
2654 Some((
2655 path,
2656 Some(
2657 "`use` statements changed in Rust 2018; read more at \
2658 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2659 clarity.html>"
2660 .to_string(),
2661 ),
2662 ))
2663 } else {
2664 None
2665 }
2666 }
2667
2668 #[instrument(level = "debug", skip(self, parent_scope))]
2676 fn make_missing_super_suggestion(
2677 &mut self,
2678 mut path: Vec<Segment>,
2679 parent_scope: &ParentScope<'ra>,
2680 ) -> Option<(Vec<Segment>, Option<String>)> {
2681 path[0].ident.name = kw::Super;
2683 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2684 debug!(?path, ?result);
2685 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2686 }
2687
2688 #[instrument(level = "debug", skip(self, parent_scope))]
2699 fn make_external_crate_suggestion(
2700 &mut self,
2701 mut path: Vec<Segment>,
2702 parent_scope: &ParentScope<'ra>,
2703 ) -> Option<(Vec<Segment>, Option<String>)> {
2704 if path[1].ident.span.is_rust_2015() {
2705 return None;
2706 }
2707
2708 let mut extern_crate_names =
2712 self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2713 extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
2714
2715 for name in extern_crate_names.into_iter() {
2716 path[0].ident.name = name;
2718 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2719 debug!(?path, ?name, ?result);
2720 if let PathResult::Module(..) = result {
2721 return Some((path, None));
2722 }
2723 }
2724
2725 None
2726 }
2727
2728 pub(crate) fn check_for_module_export_macro(
2741 &mut self,
2742 import: Import<'ra>,
2743 module: ModuleOrUniformRoot<'ra>,
2744 ident: Ident,
2745 ) -> Option<(Option<Suggestion>, Option<String>)> {
2746 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2747 return None;
2748 };
2749
2750 while let Some(parent) = crate_module.parent {
2751 crate_module = parent;
2752 }
2753
2754 if module == ModuleOrUniformRoot::Module(crate_module) {
2755 return None;
2757 }
2758
2759 let binding_key = BindingKey::new(ident, MacroNS);
2760 let binding = self.resolution(crate_module, binding_key)?.binding()?;
2761 let Res::Def(DefKind::Macro(kinds), _) = binding.res() else {
2762 return None;
2763 };
2764 if !kinds.contains(MacroKinds::BANG) {
2765 return None;
2766 }
2767 let module_name = crate_module.kind.name().unwrap_or(kw::Crate);
2768 let import_snippet = match import.kind {
2769 ImportKind::Single { source, target, .. } if source != target => {
2770 format!("{source} as {target}")
2771 }
2772 _ => format!("{ident}"),
2773 };
2774
2775 let mut corrections: Vec<(Span, String)> = Vec::new();
2776 if !import.is_nested() {
2777 corrections.push((import.span, format!("{module_name}::{import_snippet}")));
2780 } else {
2781 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2785 self.tcx.sess,
2786 import.span,
2787 import.use_span,
2788 );
2789 debug!(found_closing_brace, ?binding_span);
2790
2791 let mut removal_span = binding_span;
2792
2793 if found_closing_brace
2801 && let Some(previous_span) =
2802 extend_span_to_previous_binding(self.tcx.sess, binding_span)
2803 {
2804 debug!(?previous_span);
2805 removal_span = removal_span.with_lo(previous_span.lo());
2806 }
2807 debug!(?removal_span);
2808
2809 corrections.push((removal_span, "".to_string()));
2811
2812 let (has_nested, after_crate_name) =
2819 find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
2820 debug!(has_nested, ?after_crate_name);
2821
2822 let source_map = self.tcx.sess.source_map();
2823
2824 let is_definitely_crate = import
2826 .module_path
2827 .first()
2828 .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
2829
2830 let start_point = source_map.start_point(after_crate_name);
2832 if is_definitely_crate
2833 && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
2834 {
2835 corrections.push((
2836 start_point,
2837 if has_nested {
2838 format!("{start_snippet}{import_snippet}, ")
2840 } else {
2841 format!("{{{import_snippet}, {start_snippet}")
2844 },
2845 ));
2846
2847 if !has_nested {
2849 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2850 }
2851 } else {
2852 corrections.push((
2854 import.use_span.shrink_to_lo(),
2855 format!("use {module_name}::{import_snippet};\n"),
2856 ));
2857 }
2858 }
2859
2860 let suggestion = Some((
2861 corrections,
2862 String::from("a macro with this name exists at the root of the crate"),
2863 Applicability::MaybeIncorrect,
2864 ));
2865 Some((
2866 suggestion,
2867 Some(
2868 "this could be because a macro annotated with `#[macro_export]` will be exported \
2869 at the root of the crate instead of the module where it is defined"
2870 .to_string(),
2871 ),
2872 ))
2873 }
2874
2875 pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
2877 let local_items;
2878 let symbols = if module.is_local() {
2879 local_items = self
2880 .stripped_cfg_items
2881 .iter()
2882 .filter_map(|item| {
2883 let parent_module = self.opt_local_def_id(item.parent_module)?.to_def_id();
2884 Some(StrippedCfgItem {
2885 parent_module,
2886 ident: item.ident,
2887 cfg: item.cfg.clone(),
2888 })
2889 })
2890 .collect::<Vec<_>>();
2891 local_items.as_slice()
2892 } else {
2893 self.tcx.stripped_cfg_items(module.krate)
2894 };
2895
2896 for &StrippedCfgItem { parent_module, ident, ref cfg } in symbols {
2897 if ident.name != *segment {
2898 continue;
2899 }
2900
2901 fn comes_from_same_module_for_glob(
2902 r: &Resolver<'_, '_>,
2903 parent_module: DefId,
2904 module: DefId,
2905 visited: &mut FxHashMap<DefId, bool>,
2906 ) -> bool {
2907 if let Some(&cached) = visited.get(&parent_module) {
2908 return cached;
2912 }
2913 visited.insert(parent_module, false);
2914 let m = r.expect_module(parent_module);
2915 let mut res = false;
2916 for importer in m.glob_importers.borrow().iter() {
2917 if let Some(next_parent_module) = importer.parent_scope.module.opt_def_id() {
2918 if next_parent_module == module
2919 || comes_from_same_module_for_glob(
2920 r,
2921 next_parent_module,
2922 module,
2923 visited,
2924 )
2925 {
2926 res = true;
2927 break;
2928 }
2929 }
2930 }
2931 visited.insert(parent_module, res);
2932 res
2933 }
2934
2935 let comes_from_same_module = parent_module == module
2936 || comes_from_same_module_for_glob(
2937 self,
2938 parent_module,
2939 module,
2940 &mut Default::default(),
2941 );
2942 if !comes_from_same_module {
2943 continue;
2944 }
2945
2946 let item_was = if let CfgEntry::NameValue { value: Some((feature, _)), .. } = cfg.0 {
2947 errors::ItemWas::BehindFeature { feature, span: cfg.1 }
2948 } else {
2949 errors::ItemWas::CfgOut { span: cfg.1 }
2950 };
2951 let note = errors::FoundItemConfigureOut { span: ident.span, item_was };
2952 err.subdiagnostic(note);
2953 }
2954 }
2955}
2956
2957fn find_span_of_binding_until_next_binding(
2971 sess: &Session,
2972 binding_span: Span,
2973 use_span: Span,
2974) -> (bool, Span) {
2975 let source_map = sess.source_map();
2976
2977 let binding_until_end = binding_span.with_hi(use_span.hi());
2980
2981 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2984
2985 let mut found_closing_brace = false;
2992 let after_binding_until_next_binding =
2993 source_map.span_take_while(after_binding_until_end, |&ch| {
2994 if ch == '}' {
2995 found_closing_brace = true;
2996 }
2997 ch == ' ' || ch == ','
2998 });
2999
3000 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
3005
3006 (found_closing_brace, span)
3007}
3008
3009fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
3022 let source_map = sess.source_map();
3023
3024 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
3028
3029 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
3030 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
3031 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
3032 return None;
3033 }
3034
3035 let prev_comma = prev_comma.first().unwrap();
3036 let prev_starting_brace = prev_starting_brace.first().unwrap();
3037
3038 if prev_comma.len() > prev_starting_brace.len() {
3042 return None;
3043 }
3044
3045 Some(binding_span.with_lo(BytePos(
3046 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
3049 )))
3050}
3051
3052#[instrument(level = "debug", skip(sess))]
3066fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
3067 let source_map = sess.source_map();
3068
3069 let mut num_colons = 0;
3071 let until_second_colon = source_map.span_take_while(use_span, |c| {
3073 if *c == ':' {
3074 num_colons += 1;
3075 }
3076 !matches!(c, ':' if num_colons == 2)
3077 });
3078 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
3080
3081 let mut found_a_non_whitespace_character = false;
3082 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
3084 if found_a_non_whitespace_character {
3085 return false;
3086 }
3087 if !c.is_whitespace() {
3088 found_a_non_whitespace_character = true;
3089 }
3090 true
3091 });
3092
3093 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
3095
3096 (next_left_bracket == after_second_colon, from_second_colon)
3097}
3098
3099enum Instead {
3102 Yes,
3103 No,
3104}
3105
3106enum FoundUse {
3108 Yes,
3109 No,
3110}
3111
3112pub(crate) enum DiagMode {
3114 Normal,
3115 Pattern,
3117 Import {
3119 unresolved_import: bool,
3121 append: bool,
3124 },
3125}
3126
3127pub(crate) fn import_candidates(
3128 tcx: TyCtxt<'_>,
3129 err: &mut Diag<'_>,
3130 use_placement_span: Option<Span>,
3132 candidates: &[ImportSuggestion],
3133 mode: DiagMode,
3134 append: &str,
3135) {
3136 show_candidates(
3137 tcx,
3138 err,
3139 use_placement_span,
3140 candidates,
3141 Instead::Yes,
3142 FoundUse::Yes,
3143 mode,
3144 vec![],
3145 append,
3146 );
3147}
3148
3149type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
3150
3151fn show_candidates(
3156 tcx: TyCtxt<'_>,
3157 err: &mut Diag<'_>,
3158 use_placement_span: Option<Span>,
3160 candidates: &[ImportSuggestion],
3161 instead: Instead,
3162 found_use: FoundUse,
3163 mode: DiagMode,
3164 path: Vec<Segment>,
3165 append: &str,
3166) -> bool {
3167 if candidates.is_empty() {
3168 return false;
3169 }
3170
3171 let mut showed = false;
3172 let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
3173 let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
3174
3175 candidates.iter().for_each(|c| {
3176 if c.accessible {
3177 if c.doc_visible {
3179 accessible_path_strings.push((
3180 pprust::path_to_string(&c.path),
3181 c.descr,
3182 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3183 &c.note,
3184 c.via_import,
3185 ))
3186 }
3187 } else {
3188 inaccessible_path_strings.push((
3189 pprust::path_to_string(&c.path),
3190 c.descr,
3191 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3192 &c.note,
3193 c.via_import,
3194 ))
3195 }
3196 });
3197
3198 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
3201 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
3202 path_strings.dedup_by(|a, b| a.0 == b.0);
3203 let core_path_strings =
3204 path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
3205 let std_path_strings =
3206 path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
3207 let foreign_crate_path_strings =
3208 path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
3209
3210 if std_path_strings.len() == core_path_strings.len() {
3213 path_strings.extend(std_path_strings);
3215 } else {
3216 path_strings.extend(std_path_strings);
3217 path_strings.extend(core_path_strings);
3218 }
3219 path_strings.extend(foreign_crate_path_strings);
3221 }
3222
3223 if !accessible_path_strings.is_empty() {
3224 let (determiner, kind, s, name, through) =
3225 if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
3226 (
3227 "this",
3228 *descr,
3229 "",
3230 format!(" `{name}`"),
3231 if *via_import { " through its public re-export" } else { "" },
3232 )
3233 } else {
3234 let kinds = accessible_path_strings
3237 .iter()
3238 .map(|(_, descr, _, _, _)| *descr)
3239 .collect::<UnordSet<&str>>();
3240 let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
3241 let s = if kind.ends_with('s') { "es" } else { "s" };
3242
3243 ("one of these", kind, s, String::new(), "")
3244 };
3245
3246 let instead = if let Instead::Yes = instead { " instead" } else { "" };
3247 let mut msg = if let DiagMode::Pattern = mode {
3248 format!(
3249 "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
3250 pattern",
3251 )
3252 } else {
3253 format!("consider importing {determiner} {kind}{s}{through}{instead}")
3254 };
3255
3256 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3257 err.note(note.clone());
3258 }
3259
3260 let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
3261 msg.push(':');
3262
3263 for candidate in accessible_path_strings {
3264 msg.push('\n');
3265 msg.push_str(&candidate.0);
3266 }
3267 };
3268
3269 if let Some(span) = use_placement_span {
3270 let (add_use, trailing) = match mode {
3271 DiagMode::Pattern => {
3272 err.span_suggestions(
3273 span,
3274 msg,
3275 accessible_path_strings.into_iter().map(|a| a.0),
3276 Applicability::MaybeIncorrect,
3277 );
3278 return true;
3279 }
3280 DiagMode::Import { .. } => ("", ""),
3281 DiagMode::Normal => ("use ", ";\n"),
3282 };
3283 for candidate in &mut accessible_path_strings {
3284 let additional_newline = if let FoundUse::No = found_use
3287 && let DiagMode::Normal = mode
3288 {
3289 "\n"
3290 } else {
3291 ""
3292 };
3293 candidate.0 =
3294 format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
3295 }
3296
3297 match mode {
3298 DiagMode::Import { append: true, .. } => {
3299 append_candidates(&mut msg, accessible_path_strings);
3300 err.span_help(span, msg);
3301 }
3302 _ => {
3303 err.span_suggestions_with_style(
3304 span,
3305 msg,
3306 accessible_path_strings.into_iter().map(|a| a.0),
3307 Applicability::MaybeIncorrect,
3308 SuggestionStyle::ShowAlways,
3309 );
3310 }
3311 }
3312
3313 if let [first, .., last] = &path[..] {
3314 let sp = first.ident.span.until(last.ident.span);
3315 if sp.can_be_used_for_suggestions() && !sp.is_empty() {
3318 err.span_suggestion_verbose(
3319 sp,
3320 format!("if you import `{}`, refer to it directly", last.ident),
3321 "",
3322 Applicability::Unspecified,
3323 );
3324 }
3325 }
3326 } else {
3327 append_candidates(&mut msg, accessible_path_strings);
3328 err.help(msg);
3329 }
3330 showed = true;
3331 }
3332 if !inaccessible_path_strings.is_empty()
3333 && (!matches!(mode, DiagMode::Import { unresolved_import: false, .. }))
3334 {
3335 let prefix =
3336 if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
3337 if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
3338 let msg = format!(
3339 "{prefix}{descr} `{name}`{} exists but is inaccessible",
3340 if let DiagMode::Pattern = mode { ", which" } else { "" }
3341 );
3342
3343 if let Some(source_span) = source_span {
3344 let span = tcx.sess.source_map().guess_head_span(*source_span);
3345 let mut multi_span = MultiSpan::from_span(span);
3346 multi_span.push_span_label(span, "not accessible");
3347 err.span_note(multi_span, msg);
3348 } else {
3349 err.note(msg);
3350 }
3351 if let Some(note) = (*note).as_deref() {
3352 err.note(note.to_string());
3353 }
3354 } else {
3355 let (_, descr_first, _, _, _) = &inaccessible_path_strings[0];
3356 let descr = if inaccessible_path_strings
3357 .iter()
3358 .skip(1)
3359 .all(|(_, descr, _, _, _)| descr == descr_first)
3360 {
3361 descr_first
3362 } else {
3363 "item"
3364 };
3365 let plural_descr =
3366 if descr.ends_with('s') { format!("{descr}es") } else { format!("{descr}s") };
3367
3368 let mut msg = format!("{prefix}these {plural_descr} exist but are inaccessible");
3369 let mut has_colon = false;
3370
3371 let mut spans = Vec::new();
3372 for (name, _, source_span, _, _) in &inaccessible_path_strings {
3373 if let Some(source_span) = source_span {
3374 let span = tcx.sess.source_map().guess_head_span(*source_span);
3375 spans.push((name, span));
3376 } else {
3377 if !has_colon {
3378 msg.push(':');
3379 has_colon = true;
3380 }
3381 msg.push('\n');
3382 msg.push_str(name);
3383 }
3384 }
3385
3386 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3387 for (name, span) in spans {
3388 multi_span.push_span_label(span, format!("`{name}`: not accessible"));
3389 }
3390
3391 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3392 err.note(note.clone());
3393 }
3394
3395 err.span_note(multi_span, msg);
3396 }
3397 showed = true;
3398 }
3399 showed
3400}
3401
3402#[derive(Debug)]
3403struct UsePlacementFinder {
3404 target_module: NodeId,
3405 first_legal_span: Option<Span>,
3406 first_use_span: Option<Span>,
3407}
3408
3409impl UsePlacementFinder {
3410 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3411 let mut finder =
3412 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3413 finder.visit_crate(krate);
3414 if let Some(use_span) = finder.first_use_span {
3415 (Some(use_span), FoundUse::Yes)
3416 } else {
3417 (finder.first_legal_span, FoundUse::No)
3418 }
3419 }
3420}
3421
3422impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
3423 fn visit_crate(&mut self, c: &Crate) {
3424 if self.target_module == CRATE_NODE_ID {
3425 let inject = c.spans.inject_use_span;
3426 if is_span_suitable_for_use_injection(inject) {
3427 self.first_legal_span = Some(inject);
3428 }
3429 self.first_use_span = search_for_any_use_in_items(&c.items);
3430 } else {
3431 visit::walk_crate(self, c);
3432 }
3433 }
3434
3435 fn visit_item(&mut self, item: &'tcx ast::Item) {
3436 if self.target_module == item.id {
3437 if let ItemKind::Mod(_, _, ModKind::Loaded(items, _inline, mod_spans, _)) = &item.kind {
3438 let inject = mod_spans.inject_use_span;
3439 if is_span_suitable_for_use_injection(inject) {
3440 self.first_legal_span = Some(inject);
3441 }
3442 self.first_use_span = search_for_any_use_in_items(items);
3443 }
3444 } else {
3445 visit::walk_item(self, item);
3446 }
3447 }
3448}
3449
3450fn search_for_any_use_in_items(items: &[Box<ast::Item>]) -> Option<Span> {
3451 for item in items {
3452 if let ItemKind::Use(..) = item.kind
3453 && is_span_suitable_for_use_injection(item.span)
3454 {
3455 let mut lo = item.span.lo();
3456 for attr in &item.attrs {
3457 if attr.span.eq_ctxt(item.span) {
3458 lo = std::cmp::min(lo, attr.span.lo());
3459 }
3460 }
3461 return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3462 }
3463 }
3464 None
3465}
3466
3467fn is_span_suitable_for_use_injection(s: Span) -> bool {
3468 !s.from_expansion()
3471}