1use std::ops::ControlFlow;
2
3use itertools::Itertools as _;
4use rustc_ast::visit::{self, Visitor};
5use rustc_ast::{
6 self as ast, CRATE_NODE_ID, Crate, ItemKind, ModKind, NodeId, Path, join_path_idents,
7};
8use rustc_ast_pretty::pprust;
9use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10use rustc_data_structures::unord::{UnordMap, UnordSet};
11use rustc_errors::codes::*;
12use rustc_errors::{
13 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, MultiSpan, SuggestionStyle,
14 struct_span_code_err,
15};
16use rustc_feature::BUILTIN_ATTRIBUTES;
17use rustc_hir::attrs::{AttributeKind, CfgEntry, StrippedCfgItem};
18use rustc_hir::def::Namespace::{self, *};
19use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, MacroKinds, NonMacroAttrKind, PerNS};
20use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
21use rustc_hir::{PrimTy, Stability, StabilityLevel, find_attr};
22use rustc_middle::bug;
23use rustc_middle::ty::TyCtxt;
24use rustc_session::Session;
25use rustc_session::lint::BuiltinLintDiag;
26use rustc_session::lint::builtin::{
27 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS,
28 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
29};
30use rustc_session::utils::was_invoked_from_cargo;
31use rustc_span::edit_distance::find_best_match_for_name;
32use rustc_span::edition::Edition;
33use rustc_span::hygiene::MacroKind;
34use rustc_span::source_map::{SourceMap, Spanned};
35use rustc_span::{BytePos, Ident, Macros20NormalizedIdent, Span, Symbol, SyntaxContext, kw, sym};
36use thin_vec::{ThinVec, thin_vec};
37use tracing::{debug, instrument};
38
39use crate::errors::{
40 self, AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion, ConsiderAddingADerive,
41 ExplicitUnsafeTraits, MacroDefinedLater, MacroRulesNot, MacroSuggMovePosition,
42 MaybeMissingMacroRulesName,
43};
44use crate::imports::{Import, ImportKind};
45use crate::late::{DiagMetadata, PatternSource, Rib};
46use crate::{
47 AmbiguityError, AmbiguityKind, BindingError, BindingKey, Decl, DeclKind, Finalize,
48 ForwardGenericParamBanReason, HasGenericParams, LateDecl, MacroRulesScope, Module, ModuleKind,
49 ModuleOrUniformRoot, ParentScope, PathResult, PrivacyError, ResolutionError, Resolver, Scope,
50 ScopeSet, Segment, UseError, Used, VisResolutionError, errors as errs, path_names_to_string,
51};
52
53type Res = def::Res<ast::NodeId>;
54
55pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
57
58pub(crate) type LabelSuggestion = (Ident, bool);
61
62#[derive(Debug)]
63pub(crate) enum SuggestionTarget {
64 SimilarlyNamed,
66 SingleItem,
68}
69
70#[derive(Debug)]
71pub(crate) struct TypoSuggestion {
72 pub candidate: Symbol,
73 pub span: Option<Span>,
76 pub res: Res,
77 pub target: SuggestionTarget,
78}
79
80impl TypoSuggestion {
81 pub(crate) fn typo_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
82 Self {
83 candidate: ident.name,
84 span: Some(ident.span),
85 res,
86 target: SuggestionTarget::SimilarlyNamed,
87 }
88 }
89 pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
90 Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
91 }
92 pub(crate) fn single_item_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
93 Self {
94 candidate: ident.name,
95 span: Some(ident.span),
96 res,
97 target: SuggestionTarget::SingleItem,
98 }
99 }
100}
101
102#[derive(Debug, Clone)]
104pub(crate) struct ImportSuggestion {
105 pub did: Option<DefId>,
106 pub descr: &'static str,
107 pub path: Path,
108 pub accessible: bool,
109 pub doc_visible: bool,
111 pub via_import: bool,
112 pub note: Option<String>,
114 pub is_stable: bool,
115}
116
117fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
125 let impl_span = sm.span_until_char(impl_span, '<');
126 sm.span_until_whitespace(impl_span)
127}
128
129impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
130 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
131 self.tcx.dcx()
132 }
133
134 pub(crate) fn report_errors(&mut self, krate: &Crate) {
135 self.report_with_use_injections(krate);
136
137 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
138 self.lint_buffer.buffer_lint(
139 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
140 CRATE_NODE_ID,
141 span_use,
142 errors::MacroExpandedMacroExportsAccessedByAbsolutePaths { definition: span_def },
143 );
144 }
145
146 for ambiguity_error in &self.ambiguity_errors {
147 let diag = self.ambiguity_diagnostic(ambiguity_error);
148
149 if ambiguity_error.warning {
150 let node_id = match ambiguity_error.b1.0.kind {
151 DeclKind::Import { import, .. } => import.root_id,
152 DeclKind::Def(_) => CRATE_NODE_ID,
153 };
154 self.lint_buffer.buffer_lint(
155 AMBIGUOUS_GLOB_IMPORTS,
156 node_id,
157 diag.ident.span,
158 diag,
159 );
160 } else {
161 self.dcx().emit_err(diag);
162 }
163 }
164
165 let mut reported_spans = FxHashSet::default();
166 for error in std::mem::take(&mut self.privacy_errors) {
167 if reported_spans.insert(error.dedup_span) {
168 self.report_privacy_error(&error);
169 }
170 }
171 }
172
173 fn report_with_use_injections(&mut self, krate: &Crate) {
174 for UseError { mut err, candidates, def_id, instead, suggestion, path, is_call } in
175 std::mem::take(&mut self.use_injections)
176 {
177 let (span, found_use) = if let Some(def_id) = def_id.as_local() {
178 UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id))
179 } else {
180 (None, FoundUse::No)
181 };
182
183 if !candidates.is_empty() {
184 show_candidates(
185 self.tcx,
186 &mut err,
187 span,
188 &candidates,
189 if instead { Instead::Yes } else { Instead::No },
190 found_use,
191 DiagMode::Normal,
192 path,
193 "",
194 );
195 err.emit();
196 } else if let Some((span, msg, sugg, appl)) = suggestion {
197 err.span_suggestion_verbose(span, msg, sugg, appl);
198 err.emit();
199 } else if let [segment] = path.as_slice()
200 && is_call
201 {
202 err.stash(segment.ident.span, rustc_errors::StashKey::CallIntoMethod);
203 } else {
204 err.emit();
205 }
206 }
207 }
208
209 pub(crate) fn report_conflict(
210 &mut self,
211 parent: Module<'_>,
212 ident: Ident,
213 ns: Namespace,
214 new_binding: Decl<'ra>,
215 old_binding: Decl<'ra>,
216 ) {
217 if old_binding.span.lo() > new_binding.span.lo() {
219 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
220 }
221
222 let container = match parent.kind {
223 ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
226 ModuleKind::Block => "block",
227 };
228
229 let (name, span) =
230 (ident.name, self.tcx.sess.source_map().guess_head_span(new_binding.span));
231
232 if self.name_already_seen.get(&name) == Some(&span) {
233 return;
234 }
235
236 let old_kind = match (ns, old_binding.res()) {
237 (ValueNS, _) => "value",
238 (MacroNS, _) => "macro",
239 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
240 (TypeNS, Res::Def(DefKind::Mod, _)) => "module",
241 (TypeNS, Res::Def(DefKind::Trait, _)) => "trait",
242 (TypeNS, _) => "type",
243 };
244
245 let code = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
246 (true, true) => E0259,
247 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
248 true => E0254,
249 false => E0260,
250 },
251 _ => match (old_binding.is_import_user_facing(), new_binding.is_import_user_facing()) {
252 (false, false) => E0428,
253 (true, true) => E0252,
254 _ => E0255,
255 },
256 };
257
258 let label = match new_binding.is_import_user_facing() {
259 true => errors::NameDefinedMultipleTimeLabel::Reimported { span },
260 false => errors::NameDefinedMultipleTimeLabel::Redefined { span },
261 };
262
263 let old_binding_label =
264 (!old_binding.span.is_dummy() && old_binding.span != span).then(|| {
265 let span = self.tcx.sess.source_map().guess_head_span(old_binding.span);
266 match old_binding.is_import_user_facing() {
267 true => {
268 errors::NameDefinedMultipleTimeOldBindingLabel::Import { span, old_kind }
269 }
270 false => errors::NameDefinedMultipleTimeOldBindingLabel::Definition {
271 span,
272 old_kind,
273 },
274 }
275 });
276
277 let mut err = self
278 .dcx()
279 .create_err(errors::NameDefinedMultipleTime {
280 span,
281 name,
282 descr: ns.descr(),
283 container,
284 label,
285 old_binding_label,
286 })
287 .with_code(code);
288
289 use DeclKind::Import;
291 let can_suggest = |binding: Decl<'_>, import: self::Import<'_>| {
292 !binding.span.is_dummy()
293 && !matches!(import.kind, ImportKind::MacroUse { .. } | ImportKind::MacroExport)
294 };
295 let import = match (&new_binding.kind, &old_binding.kind) {
296 (Import { import: new, .. }, Import { import: old, .. })
299 if {
300 (new.has_attributes || old.has_attributes)
301 && can_suggest(old_binding, *old)
302 && can_suggest(new_binding, *new)
303 } =>
304 {
305 if old.has_attributes {
306 Some((*new, new_binding.span, true))
307 } else {
308 Some((*old, old_binding.span, true))
309 }
310 }
311 (Import { import, .. }, other) if can_suggest(new_binding, *import) => {
313 Some((*import, new_binding.span, other.is_import()))
314 }
315 (other, Import { import, .. }) if can_suggest(old_binding, *import) => {
316 Some((*import, old_binding.span, other.is_import()))
317 }
318 _ => None,
319 };
320
321 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
323 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
324 let from_item = self
325 .extern_prelude
326 .get(&Macros20NormalizedIdent::new(ident))
327 .is_none_or(|entry| entry.introduced_by_item());
328 let should_remove_import = duplicate
332 && !has_dummy_span
333 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
334
335 match import {
336 Some((import, span, true)) if should_remove_import && import.is_nested() => {
337 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span);
338 }
339 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
340 err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport {
343 span: import.use_span_with_attributes,
344 });
345 }
346 Some((import, span, _)) => {
347 self.add_suggestion_for_rename_of_use(&mut err, name, import, span);
348 }
349 _ => {}
350 }
351
352 err.emit();
353 self.name_already_seen.insert(name, span);
354 }
355
356 fn add_suggestion_for_rename_of_use(
366 &self,
367 err: &mut Diag<'_>,
368 name: Symbol,
369 import: Import<'_>,
370 binding_span: Span,
371 ) {
372 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
373 format!("Other{name}")
374 } else {
375 format!("other_{name}")
376 };
377
378 let mut suggestion = None;
379 let mut span = binding_span;
380 match import.kind {
381 ImportKind::Single { type_ns_only: true, .. } => {
382 suggestion = Some(format!("self as {suggested_name}"))
383 }
384 ImportKind::Single { source, .. } => {
385 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
386 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(binding_span)
387 && pos as usize <= snippet.len()
388 {
389 span = binding_span.with_lo(binding_span.lo() + BytePos(pos)).with_hi(
390 binding_span.hi() - BytePos(if snippet.ends_with(';') { 1 } else { 0 }),
391 );
392 suggestion = Some(format!(" as {suggested_name}"));
393 }
394 }
395 ImportKind::ExternCrate { source, target, .. } => {
396 suggestion = Some(format!(
397 "extern crate {} as {};",
398 source.unwrap_or(target.name),
399 suggested_name,
400 ))
401 }
402 _ => unreachable!(),
403 }
404
405 if let Some(suggestion) = suggestion {
406 err.subdiagnostic(ChangeImportBindingSuggestion { span, suggestion });
407 } else {
408 err.subdiagnostic(ChangeImportBinding { span });
409 }
410 }
411
412 fn add_suggestion_for_duplicate_nested_use(
435 &self,
436 err: &mut Diag<'_>,
437 import: Import<'_>,
438 binding_span: Span,
439 ) {
440 assert!(import.is_nested());
441
442 let (found_closing_brace, span) =
450 find_span_of_binding_until_next_binding(self.tcx.sess, binding_span, import.use_span);
451
452 if found_closing_brace {
455 if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) {
456 err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport { span });
457 } else {
458 err.subdiagnostic(errors::RemoveUnnecessaryImport {
461 span: import.use_span_with_attributes,
462 });
463 }
464
465 return;
466 }
467
468 err.subdiagnostic(errors::RemoveUnnecessaryImport { span });
469 }
470
471 pub(crate) fn lint_if_path_starts_with_module(
472 &mut self,
473 finalize: Finalize,
474 path: &[Segment],
475 second_binding: Option<Decl<'_>>,
476 ) {
477 let Finalize { node_id, root_span, .. } = finalize;
478
479 let first_name = match path.get(0) {
480 Some(seg) if seg.ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015() => {
482 seg.ident.name
483 }
484 _ => return,
485 };
486
487 if first_name != kw::PathRoot {
490 return;
491 }
492
493 match path.get(1) {
494 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
496 Some(_) => {}
498 None => return,
502 }
503
504 if let Some(binding) = second_binding
508 && let DeclKind::Import { import, .. } = binding.kind
509 && let ImportKind::ExternCrate { source: None, .. } = import.kind
511 {
512 return;
513 }
514
515 let diag = BuiltinLintDiag::AbsPathWithModule(root_span);
516 self.lint_buffer.buffer_lint(
517 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
518 node_id,
519 root_span,
520 diag,
521 );
522 }
523
524 pub(crate) fn add_module_candidates(
525 &self,
526 module: Module<'ra>,
527 names: &mut Vec<TypoSuggestion>,
528 filter_fn: &impl Fn(Res) -> bool,
529 ctxt: Option<SyntaxContext>,
530 ) {
531 module.for_each_child(self, |_this, ident, _ns, binding| {
532 let res = binding.res();
533 if filter_fn(res) && ctxt.is_none_or(|ctxt| ctxt == ident.span.ctxt()) {
534 names.push(TypoSuggestion::typo_from_ident(ident.0, res));
535 }
536 });
537 }
538
539 pub(crate) fn report_error(
544 &mut self,
545 span: Span,
546 resolution_error: ResolutionError<'ra>,
547 ) -> ErrorGuaranteed {
548 self.into_struct_error(span, resolution_error).emit()
549 }
550
551 pub(crate) fn into_struct_error(
552 &mut self,
553 span: Span,
554 resolution_error: ResolutionError<'ra>,
555 ) -> Diag<'_> {
556 match resolution_error {
557 ResolutionError::GenericParamsFromOuterItem {
558 outer_res,
559 has_generic_params,
560 def_kind,
561 inner_item,
562 current_self_ty,
563 } => {
564 use errs::GenericParamsFromOuterItemLabel as Label;
565 let static_or_const = match def_kind {
566 DefKind::Static { .. } => {
567 Some(errs::GenericParamsFromOuterItemStaticOrConst::Static)
568 }
569 DefKind::Const => Some(errs::GenericParamsFromOuterItemStaticOrConst::Const),
570 _ => None,
571 };
572 let is_self =
573 matches!(outer_res, Res::SelfTyParam { .. } | Res::SelfTyAlias { .. });
574 let mut err = errs::GenericParamsFromOuterItem {
575 span,
576 label: None,
577 refer_to_type_directly: None,
578 sugg: None,
579 static_or_const,
580 is_self,
581 item: inner_item.as_ref().map(|(span, kind)| {
582 errs::GenericParamsFromOuterItemInnerItem {
583 span: *span,
584 descr: kind.descr().to_string(),
585 }
586 }),
587 };
588
589 let sm = self.tcx.sess.source_map();
590 let def_id = match outer_res {
591 Res::SelfTyParam { .. } => {
592 err.label = Some(Label::SelfTyParam(span));
593 return self.dcx().create_err(err);
594 }
595 Res::SelfTyAlias { alias_to: def_id, .. } => {
596 err.label = Some(Label::SelfTyAlias(reduce_impl_span_to_impl_keyword(
597 sm,
598 self.def_span(def_id),
599 )));
600 err.refer_to_type_directly =
601 current_self_ty.map(|snippet| errs::UseTypeDirectly { span, snippet });
602 return self.dcx().create_err(err);
603 }
604 Res::Def(DefKind::TyParam, def_id) => {
605 err.label = Some(Label::TyParam(self.def_span(def_id)));
606 def_id
607 }
608 Res::Def(DefKind::ConstParam, def_id) => {
609 err.label = Some(Label::ConstParam(self.def_span(def_id)));
610 def_id
611 }
612 _ => {
613 bug!(
614 "GenericParamsFromOuterItem should only be used with \
615 Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
616 DefKind::ConstParam"
617 );
618 }
619 };
620
621 if let HasGenericParams::Yes(span) = has_generic_params
622 && !matches!(inner_item, Some((_, ItemKind::Delegation(..))))
623 {
624 let name = self.tcx.item_name(def_id);
625 let (span, snippet) = if span.is_empty() {
626 let snippet = format!("<{name}>");
627 (span, snippet)
628 } else {
629 let span = sm.span_through_char(span, '<').shrink_to_hi();
630 let snippet = format!("{name}, ");
631 (span, snippet)
632 };
633 err.sugg = Some(errs::GenericParamsFromOuterItemSugg { span, snippet });
634 }
635
636 self.dcx().create_err(err)
637 }
638 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
639 .dcx()
640 .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
641 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
642 self.dcx().create_err(errs::MethodNotMemberOfTrait {
643 span,
644 method,
645 trait_,
646 sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
647 span: method.span,
648 candidate: c,
649 }),
650 })
651 }
652 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
653 self.dcx().create_err(errs::TypeNotMemberOfTrait {
654 span,
655 type_,
656 trait_,
657 sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
658 span: type_.span,
659 candidate: c,
660 }),
661 })
662 }
663 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
664 self.dcx().create_err(errs::ConstNotMemberOfTrait {
665 span,
666 const_,
667 trait_,
668 sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
669 span: const_.span,
670 candidate: c,
671 }),
672 })
673 }
674 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
675 let BindingError { name, target, origin, could_be_path } = binding_error;
676
677 let mut target_sp = target.iter().map(|pat| pat.span).collect::<Vec<_>>();
678 target_sp.sort();
679 target_sp.dedup();
680 let mut origin_sp = origin.iter().map(|(span, _)| *span).collect::<Vec<_>>();
681 origin_sp.sort();
682 origin_sp.dedup();
683
684 let msp = MultiSpan::from_spans(target_sp.clone());
685 let mut err = self
686 .dcx()
687 .create_err(errors::VariableIsNotBoundInAllPatterns { multispan: msp, name });
688 for sp in target_sp {
689 err.subdiagnostic(errors::PatternDoesntBindName { span: sp, name });
690 }
691 for sp in &origin_sp {
692 err.subdiagnostic(errors::VariableNotInAllPatterns { span: *sp });
693 }
694 let mut suggested_typo = false;
695 if !target.iter().all(|pat| matches!(pat.kind, ast::PatKind::Ident(..)))
696 && !origin.iter().all(|(_, pat)| matches!(pat.kind, ast::PatKind::Ident(..)))
697 {
698 let mut target_visitor = BindingVisitor::default();
701 for pat in &target {
702 target_visitor.visit_pat(pat);
703 }
704 target_visitor.identifiers.sort();
705 target_visitor.identifiers.dedup();
706 let mut origin_visitor = BindingVisitor::default();
707 for (_, pat) in &origin {
708 origin_visitor.visit_pat(pat);
709 }
710 origin_visitor.identifiers.sort();
711 origin_visitor.identifiers.dedup();
712 if let Some(typo) =
714 find_best_match_for_name(&target_visitor.identifiers, name.name, None)
715 && !origin_visitor.identifiers.contains(&typo)
716 {
717 err.subdiagnostic(errors::PatternBindingTypo { spans: origin_sp, typo });
718 suggested_typo = true;
719 }
720 }
721 if could_be_path {
722 let import_suggestions = self.lookup_import_candidates(
723 name,
724 Namespace::ValueNS,
725 &parent_scope,
726 &|res: Res| {
727 matches!(
728 res,
729 Res::Def(
730 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
731 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
732 | DefKind::Const
733 | DefKind::AssocConst,
734 _,
735 )
736 )
737 },
738 );
739
740 if import_suggestions.is_empty() && !suggested_typo {
741 let kinds = [
742 DefKind::Ctor(CtorOf::Variant, CtorKind::Const),
743 DefKind::Ctor(CtorOf::Struct, CtorKind::Const),
744 DefKind::Const,
745 DefKind::AssocConst,
746 ];
747 let mut local_names = vec![];
748 self.add_module_candidates(
749 parent_scope.module,
750 &mut local_names,
751 &|res| matches!(res, Res::Def(_, _)),
752 None,
753 );
754 let local_names: FxHashSet<_> = local_names
755 .into_iter()
756 .filter_map(|s| match s.res {
757 Res::Def(_, def_id) => Some(def_id),
758 _ => None,
759 })
760 .collect();
761
762 let mut local_suggestions = vec![];
763 let mut suggestions = vec![];
764 for kind in kinds {
765 if let Some(suggestion) = self.early_lookup_typo_candidate(
766 ScopeSet::All(Namespace::ValueNS),
767 &parent_scope,
768 name,
769 &|res: Res| match res {
770 Res::Def(k, _) => k == kind,
771 _ => false,
772 },
773 ) && let Res::Def(kind, mut def_id) = suggestion.res
774 {
775 if let DefKind::Ctor(_, _) = kind {
776 def_id = self.tcx.parent(def_id);
777 }
778 let kind = kind.descr(def_id);
779 if local_names.contains(&def_id) {
780 local_suggestions.push((
783 suggestion.candidate,
784 suggestion.candidate.to_string(),
785 kind,
786 ));
787 } else {
788 suggestions.push((
789 suggestion.candidate,
790 self.def_path_str(def_id),
791 kind,
792 ));
793 }
794 }
795 }
796 let suggestions = if !local_suggestions.is_empty() {
797 local_suggestions
800 } else {
801 suggestions
802 };
803 for (name, sugg, kind) in suggestions {
804 err.span_suggestion_verbose(
805 span,
806 format!(
807 "you might have meant to use the similarly named {kind} `{name}`",
808 ),
809 sugg,
810 Applicability::MaybeIncorrect,
811 );
812 suggested_typo = true;
813 }
814 }
815 if import_suggestions.is_empty() && !suggested_typo {
816 let help_msg = format!(
817 "if you meant to match on a unit struct, unit variant or a `const` \
818 item, consider making the path in the pattern qualified: \
819 `path::to::ModOrType::{name}`",
820 );
821 err.span_help(span, help_msg);
822 }
823 show_candidates(
824 self.tcx,
825 &mut err,
826 Some(span),
827 &import_suggestions,
828 Instead::No,
829 FoundUse::Yes,
830 DiagMode::Pattern,
831 vec![],
832 "",
833 );
834 }
835 err
836 }
837 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
838 self.dcx().create_err(errs::VariableBoundWithDifferentMode {
839 span,
840 first_binding_span,
841 variable_name,
842 })
843 }
844 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
845 .dcx()
846 .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
847 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
848 .dcx()
849 .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
850 ResolutionError::UndeclaredLabel { name, suggestion } => {
851 let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
852 {
853 Some((ident, true)) => (
855 (
856 Some(errs::LabelWithSimilarNameReachable(ident.span)),
857 Some(errs::TryUsingSimilarlyNamedLabel {
858 span,
859 ident_name: ident.name,
860 }),
861 ),
862 None,
863 ),
864 Some((ident, false)) => (
866 (None, None),
867 Some(errs::UnreachableLabelWithSimilarNameExists {
868 ident_span: ident.span,
869 }),
870 ),
871 None => ((None, None), None),
873 };
874 self.dcx().create_err(errs::UndeclaredLabel {
875 span,
876 name,
877 sub_reachable,
878 sub_reachable_suggestion,
879 sub_unreachable,
880 })
881 }
882 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
883 let (suggestion, mpart_suggestion) = if root {
885 (None, None)
886 } else {
887 let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
890
891 let mpart_suggestion = errs::SelfImportsOnlyAllowedWithinMultipartSuggestion {
894 multipart_start: span_with_rename.shrink_to_lo(),
895 multipart_end: span_with_rename.shrink_to_hi(),
896 };
897 (Some(suggestion), Some(mpart_suggestion))
898 };
899 self.dcx().create_err(errs::SelfImportsOnlyAllowedWithin {
900 span,
901 suggestion,
902 mpart_suggestion,
903 })
904 }
905 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
906 self.dcx().create_err(errs::SelfImportCanOnlyAppearOnceInTheList { span })
907 }
908 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
909 self.dcx().create_err(errs::SelfImportOnlyInImportListWithNonEmptyPrefix { span })
910 }
911 ResolutionError::FailedToResolve { segment, label, suggestion, module } => {
912 let mut err =
913 struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {label}");
914 err.span_label(span, label);
915
916 if let Some((suggestions, msg, applicability)) = suggestion {
917 if suggestions.is_empty() {
918 err.help(msg);
919 return err;
920 }
921 err.multipart_suggestion(msg, suggestions, applicability);
922 }
923
924 if let Some(segment) = segment {
925 let module = match module {
926 Some(ModuleOrUniformRoot::Module(m)) if let Some(id) = m.opt_def_id() => id,
927 _ => CRATE_DEF_ID.to_def_id(),
928 };
929 self.find_cfg_stripped(&mut err, &segment, module);
930 }
931
932 err
933 }
934 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
935 self.dcx().create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
936 }
937 ResolutionError::AttemptToUseNonConstantValueInConstant {
938 ident,
939 suggestion,
940 current,
941 type_span,
942 } => {
943 let sp = self
952 .tcx
953 .sess
954 .source_map()
955 .span_extend_to_prev_str(ident.span, current, true, false);
956
957 let ((with, with_label), without) = match sp {
958 Some(sp) if !self.tcx.sess.source_map().is_multiline(sp) => {
959 let sp = sp
960 .with_lo(BytePos(sp.lo().0 - (current.len() as u32)))
961 .until(ident.span);
962 (
963 (Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
964 span: sp,
965 suggestion,
966 current,
967 type_span,
968 }), Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion {span})),
969 None,
970 )
971 }
972 _ => (
973 (None, None),
974 Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
975 ident_span: ident.span,
976 suggestion,
977 }),
978 ),
979 };
980
981 self.dcx().create_err(errs::AttemptToUseNonConstantValueInConstant {
982 span,
983 with,
984 with_label,
985 without,
986 })
987 }
988 ResolutionError::BindingShadowsSomethingUnacceptable {
989 shadowing_binding,
990 name,
991 participle,
992 article,
993 shadowed_binding,
994 shadowed_binding_span,
995 } => self.dcx().create_err(errs::BindingShadowsSomethingUnacceptable {
996 span,
997 shadowing_binding,
998 shadowed_binding,
999 article,
1000 sub_suggestion: match (shadowing_binding, shadowed_binding) {
1001 (
1002 PatternSource::Match,
1003 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
1004 ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
1005 _ => None,
1006 },
1007 shadowed_binding_span,
1008 participle,
1009 name,
1010 }),
1011 ResolutionError::ForwardDeclaredGenericParam(param, reason) => match reason {
1012 ForwardGenericParamBanReason::Default => {
1013 self.dcx().create_err(errs::ForwardDeclaredGenericParam { param, span })
1014 }
1015 ForwardGenericParamBanReason::ConstParamTy => self
1016 .dcx()
1017 .create_err(errs::ForwardDeclaredGenericInConstParamTy { param, span }),
1018 },
1019 ResolutionError::ParamInTyOfConstParam { name } => {
1020 self.dcx().create_err(errs::ParamInTyOfConstParam { span, name })
1021 }
1022 ResolutionError::ParamInNonTrivialAnonConst { name, param_kind: is_type } => {
1023 self.dcx().create_err(errs::ParamInNonTrivialAnonConst {
1024 span,
1025 name,
1026 param_kind: is_type,
1027 help: self
1028 .tcx
1029 .sess
1030 .is_nightly_build()
1031 .then_some(errs::ParamInNonTrivialAnonConstHelp),
1032 })
1033 }
1034 ResolutionError::ParamInEnumDiscriminant { name, param_kind: is_type } => self
1035 .dcx()
1036 .create_err(errs::ParamInEnumDiscriminant { span, name, param_kind: is_type }),
1037 ResolutionError::ForwardDeclaredSelf(reason) => match reason {
1038 ForwardGenericParamBanReason::Default => {
1039 self.dcx().create_err(errs::SelfInGenericParamDefault { span })
1040 }
1041 ForwardGenericParamBanReason::ConstParamTy => {
1042 self.dcx().create_err(errs::SelfInConstGenericTy { span })
1043 }
1044 },
1045 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
1046 let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
1047 match suggestion {
1048 Some((ident, true)) => (
1050 (
1051 Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
1052 Some(errs::UnreachableLabelSubSuggestion {
1053 span,
1054 ident_name: ident.name,
1057 }),
1058 ),
1059 None,
1060 ),
1061 Some((ident, false)) => (
1063 (None, None),
1064 Some(errs::UnreachableLabelSubLabelUnreachable {
1065 ident_span: ident.span,
1066 }),
1067 ),
1068 None => ((None, None), None),
1070 };
1071 self.dcx().create_err(errs::UnreachableLabel {
1072 span,
1073 name,
1074 definition_span,
1075 sub_suggestion,
1076 sub_suggestion_label,
1077 sub_unreachable_label,
1078 })
1079 }
1080 ResolutionError::TraitImplMismatch {
1081 name,
1082 kind,
1083 code,
1084 trait_item_span,
1085 trait_path,
1086 } => self
1087 .dcx()
1088 .create_err(errors::TraitImplMismatch {
1089 span,
1090 name,
1091 kind,
1092 trait_path,
1093 trait_item_span,
1094 })
1095 .with_code(code),
1096 ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
1097 .dcx()
1098 .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
1099 ResolutionError::InvalidAsmSym => self.dcx().create_err(errs::InvalidAsmSym { span }),
1100 ResolutionError::LowercaseSelf => self.dcx().create_err(errs::LowercaseSelf { span }),
1101 ResolutionError::BindingInNeverPattern => {
1102 self.dcx().create_err(errs::BindingInNeverPattern { span })
1103 }
1104 }
1105 }
1106
1107 pub(crate) fn report_vis_error(
1108 &mut self,
1109 vis_resolution_error: VisResolutionError<'_>,
1110 ) -> ErrorGuaranteed {
1111 match vis_resolution_error {
1112 VisResolutionError::Relative2018(span, path) => {
1113 self.dcx().create_err(errs::Relative2018 {
1114 span,
1115 path_span: path.span,
1116 path_str: pprust::path_to_string(path),
1119 })
1120 }
1121 VisResolutionError::AncestorOnly(span) => {
1122 self.dcx().create_err(errs::AncestorOnly(span))
1123 }
1124 VisResolutionError::FailedToResolve(span, label, suggestion) => self.into_struct_error(
1125 span,
1126 ResolutionError::FailedToResolve { segment: None, label, suggestion, module: None },
1127 ),
1128 VisResolutionError::ExpectedFound(span, path_str, res) => {
1129 self.dcx().create_err(errs::ExpectedModuleFound { span, res, path_str })
1130 }
1131 VisResolutionError::Indeterminate(span) => {
1132 self.dcx().create_err(errs::Indeterminate(span))
1133 }
1134 VisResolutionError::ModuleOnly(span) => self.dcx().create_err(errs::ModuleOnly(span)),
1135 }
1136 .emit()
1137 }
1138
1139 fn def_path_str(&self, mut def_id: DefId) -> String {
1140 let mut path = vec![def_id];
1142 while let Some(parent) = self.tcx.opt_parent(def_id) {
1143 def_id = parent;
1144 path.push(def_id);
1145 if def_id.is_top_level_module() {
1146 break;
1147 }
1148 }
1149 path.into_iter()
1151 .rev()
1152 .map(|def_id| {
1153 self.tcx
1154 .opt_item_name(def_id)
1155 .map(|name| {
1156 match (
1157 def_id.is_top_level_module(),
1158 def_id.is_local(),
1159 self.tcx.sess.edition(),
1160 ) {
1161 (true, true, Edition::Edition2015) => String::new(),
1162 (true, true, _) => kw::Crate.to_string(),
1163 (true, false, _) | (false, _, _) => name.to_string(),
1164 }
1165 })
1166 .unwrap_or_else(|| "_".to_string())
1167 })
1168 .collect::<Vec<String>>()
1169 .join("::")
1170 }
1171
1172 pub(crate) fn add_scope_set_candidates(
1173 &mut self,
1174 suggestions: &mut Vec<TypoSuggestion>,
1175 scope_set: ScopeSet<'ra>,
1176 ps: &ParentScope<'ra>,
1177 ctxt: SyntaxContext,
1178 filter_fn: &impl Fn(Res) -> bool,
1179 ) {
1180 self.cm().visit_scopes(scope_set, ps, ctxt, None, |this, scope, use_prelude, _| {
1181 match scope {
1182 Scope::DeriveHelpers(expn_id) => {
1183 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1184 if filter_fn(res) {
1185 suggestions.extend(
1186 this.helper_attrs
1187 .get(&expn_id)
1188 .into_iter()
1189 .flatten()
1190 .map(|(ident, _)| TypoSuggestion::typo_from_ident(*ident, res)),
1191 );
1192 }
1193 }
1194 Scope::DeriveHelpersCompat => {
1195 }
1197 Scope::MacroRules(macro_rules_scope) => {
1198 if let MacroRulesScope::Def(macro_rules_def) = macro_rules_scope.get() {
1199 let res = macro_rules_def.decl.res();
1200 if filter_fn(res) {
1201 suggestions
1202 .push(TypoSuggestion::typo_from_ident(macro_rules_def.ident, res))
1203 }
1204 }
1205 }
1206 Scope::ModuleNonGlobs(module, _) => {
1207 this.add_module_candidates(module, suggestions, filter_fn, None);
1208 }
1209 Scope::ModuleGlobs(..) => {
1210 }
1212 Scope::MacroUsePrelude => {
1213 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1214 |(name, binding)| {
1215 let res = binding.res();
1216 filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1217 },
1218 ));
1219 }
1220 Scope::BuiltinAttrs => {
1221 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(sym::dummy));
1222 if filter_fn(res) {
1223 suggestions.extend(
1224 BUILTIN_ATTRIBUTES
1225 .iter()
1226 .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1227 );
1228 }
1229 }
1230 Scope::ExternPreludeItems => {
1231 suggestions.extend(this.extern_prelude.keys().filter_map(|ident| {
1233 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1234 filter_fn(res).then_some(TypoSuggestion::typo_from_ident(ident.0, res))
1235 }));
1236 }
1237 Scope::ExternPreludeFlags => {}
1238 Scope::ToolPrelude => {
1239 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1240 suggestions.extend(
1241 this.registered_tools
1242 .iter()
1243 .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
1244 );
1245 }
1246 Scope::StdLibPrelude => {
1247 if let Some(prelude) = this.prelude {
1248 let mut tmp_suggestions = Vec::new();
1249 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1250 suggestions.extend(
1251 tmp_suggestions
1252 .into_iter()
1253 .filter(|s| use_prelude.into() || this.is_builtin_macro(s.res)),
1254 );
1255 }
1256 }
1257 Scope::BuiltinTypes => {
1258 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1259 let res = Res::PrimTy(*prim_ty);
1260 filter_fn(res)
1261 .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1262 }))
1263 }
1264 }
1265
1266 ControlFlow::<()>::Continue(())
1267 });
1268 }
1269
1270 fn early_lookup_typo_candidate(
1272 &mut self,
1273 scope_set: ScopeSet<'ra>,
1274 parent_scope: &ParentScope<'ra>,
1275 ident: Ident,
1276 filter_fn: &impl Fn(Res) -> bool,
1277 ) -> Option<TypoSuggestion> {
1278 let mut suggestions = Vec::new();
1279 let ctxt = ident.span.ctxt();
1280 self.add_scope_set_candidates(&mut suggestions, scope_set, parent_scope, ctxt, filter_fn);
1281
1282 suggestions.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
1284
1285 match find_best_match_for_name(
1286 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1287 ident.name,
1288 None,
1289 ) {
1290 Some(found) if found != ident.name => {
1291 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1292 }
1293 _ => None,
1294 }
1295 }
1296
1297 fn lookup_import_candidates_from_module<FilterFn>(
1298 &self,
1299 lookup_ident: Ident,
1300 namespace: Namespace,
1301 parent_scope: &ParentScope<'ra>,
1302 start_module: Module<'ra>,
1303 crate_path: ThinVec<ast::PathSegment>,
1304 filter_fn: FilterFn,
1305 ) -> Vec<ImportSuggestion>
1306 where
1307 FilterFn: Fn(Res) -> bool,
1308 {
1309 let mut candidates = Vec::new();
1310 let mut seen_modules = FxHashSet::default();
1311 let start_did = start_module.def_id();
1312 let mut worklist = vec![(
1313 start_module,
1314 ThinVec::<ast::PathSegment>::new(),
1315 true,
1316 start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
1317 true,
1318 )];
1319 let mut worklist_via_import = vec![];
1320
1321 while let Some((in_module, path_segments, accessible, doc_visible, is_stable)) =
1322 match worklist.pop() {
1323 None => worklist_via_import.pop(),
1324 Some(x) => Some(x),
1325 }
1326 {
1327 let in_module_is_extern = !in_module.def_id().is_local();
1328 in_module.for_each_child(self, |this, ident, ns, name_binding| {
1329 if name_binding.is_assoc_item()
1331 && !this.tcx.features().import_trait_associated_functions()
1332 {
1333 return;
1334 }
1335
1336 if ident.name == kw::Underscore {
1337 return;
1338 }
1339
1340 let child_accessible =
1341 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1342
1343 if in_module_is_extern && !child_accessible {
1345 return;
1346 }
1347
1348 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1349
1350 if via_import && name_binding.is_possibly_imported_variant() {
1356 return;
1357 }
1358
1359 if let DeclKind::Import { source_decl, .. } = name_binding.kind
1361 && this.is_accessible_from(source_decl.vis, parent_scope.module)
1362 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1363 {
1364 return;
1365 }
1366
1367 let res = name_binding.res();
1368 let did = match res {
1369 Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1370 _ => res.opt_def_id(),
1371 };
1372 let child_doc_visible = doc_visible
1373 && did.is_none_or(|did| did.is_local() || !this.tcx.is_doc_hidden(did));
1374
1375 if ident.name == lookup_ident.name
1379 && ns == namespace
1380 && in_module != parent_scope.module
1381 && !ident.span.normalize_to_macros_2_0().from_expansion()
1382 && filter_fn(res)
1383 {
1384 let mut segms = if lookup_ident.span.at_least_rust_2018() {
1386 crate_path.clone()
1389 } else {
1390 ThinVec::new()
1391 };
1392 segms.append(&mut path_segments.clone());
1393
1394 segms.push(ast::PathSegment::from_ident(ident.0));
1395 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1396
1397 if child_accessible
1398 && let Some(idx) = candidates
1400 .iter()
1401 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1402 {
1403 candidates.remove(idx);
1404 }
1405
1406 let is_stable = if is_stable
1407 && let Some(did) = did
1408 && this.is_stable(did, path.span)
1409 {
1410 true
1411 } else {
1412 false
1413 };
1414
1415 if is_stable
1420 && let Some(idx) = candidates
1421 .iter()
1422 .position(|v: &ImportSuggestion| v.did == did && !v.is_stable)
1423 {
1424 candidates.remove(idx);
1425 }
1426
1427 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1428 let note = if let Some(did) = did {
1431 let requires_note = !did.is_local()
1432 && this.tcx.get_attrs(did, sym::rustc_diagnostic_item).any(
1433 |attr| {
1434 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1435 .map(|x| Some(x))
1436 .contains(&attr.value_str())
1437 },
1438 );
1439
1440 requires_note.then(|| {
1441 format!(
1442 "'{}' is included in the prelude starting in Edition 2021",
1443 path_names_to_string(&path)
1444 )
1445 })
1446 } else {
1447 None
1448 };
1449
1450 candidates.push(ImportSuggestion {
1451 did,
1452 descr: res.descr(),
1453 path,
1454 accessible: child_accessible,
1455 doc_visible: child_doc_visible,
1456 note,
1457 via_import,
1458 is_stable,
1459 });
1460 }
1461 }
1462
1463 if let Some(def_id) = name_binding.res().module_like_def_id() {
1465 let mut path_segments = path_segments.clone();
1467 path_segments.push(ast::PathSegment::from_ident(ident.0));
1468
1469 let alias_import = if let DeclKind::Import { import, .. } = name_binding.kind
1470 && let ImportKind::ExternCrate { source: Some(_), .. } = import.kind
1471 && import.parent_scope.expansion == parent_scope.expansion
1472 {
1473 true
1474 } else {
1475 false
1476 };
1477
1478 let is_extern_crate_that_also_appears_in_prelude =
1479 name_binding.is_extern_crate() && lookup_ident.span.at_least_rust_2018();
1480
1481 if !is_extern_crate_that_also_appears_in_prelude || alias_import {
1482 if seen_modules.insert(def_id) {
1484 if via_import { &mut worklist_via_import } else { &mut worklist }.push(
1485 (
1486 this.expect_module(def_id),
1487 path_segments,
1488 child_accessible,
1489 child_doc_visible,
1490 is_stable && this.is_stable(def_id, name_binding.span),
1491 ),
1492 );
1493 }
1494 }
1495 }
1496 })
1497 }
1498
1499 candidates
1500 }
1501
1502 fn is_stable(&self, did: DefId, span: Span) -> bool {
1503 if did.is_local() {
1504 return true;
1505 }
1506
1507 match self.tcx.lookup_stability(did) {
1508 Some(Stability {
1509 level: StabilityLevel::Unstable { implied_by, .. }, feature, ..
1510 }) => {
1511 if span.allows_unstable(feature) {
1512 true
1513 } else if self.tcx.features().enabled(feature) {
1514 true
1515 } else if let Some(implied_by) = implied_by
1516 && self.tcx.features().enabled(implied_by)
1517 {
1518 true
1519 } else {
1520 false
1521 }
1522 }
1523 Some(_) => true,
1524 None => false,
1525 }
1526 }
1527
1528 pub(crate) fn lookup_import_candidates<FilterFn>(
1536 &mut self,
1537 lookup_ident: Ident,
1538 namespace: Namespace,
1539 parent_scope: &ParentScope<'ra>,
1540 filter_fn: FilterFn,
1541 ) -> Vec<ImportSuggestion>
1542 where
1543 FilterFn: Fn(Res) -> bool,
1544 {
1545 let crate_path = thin_vec![ast::PathSegment::from_ident(Ident::with_dummy_span(kw::Crate))];
1546 let mut suggestions = self.lookup_import_candidates_from_module(
1547 lookup_ident,
1548 namespace,
1549 parent_scope,
1550 self.graph_root,
1551 crate_path,
1552 &filter_fn,
1553 );
1554
1555 if lookup_ident.span.at_least_rust_2018() {
1556 for &ident in self.extern_prelude.keys() {
1557 if ident.span.from_expansion() {
1558 continue;
1564 }
1565 let Some(crate_id) =
1566 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
1567 else {
1568 continue;
1569 };
1570
1571 let crate_def_id = crate_id.as_def_id();
1572 let crate_root = self.expect_module(crate_def_id);
1573
1574 let needs_disambiguation =
1578 self.resolutions(parent_scope.module).borrow().iter().any(
1579 |(key, name_resolution)| {
1580 if key.ns == TypeNS
1581 && key.ident == ident
1582 && let Some(decl) = name_resolution.borrow().best_decl()
1583 {
1584 match decl.res() {
1585 Res::Def(_, def_id) => def_id != crate_def_id,
1588 Res::PrimTy(_) => true,
1589 _ => false,
1590 }
1591 } else {
1592 false
1593 }
1594 },
1595 );
1596 let mut crate_path = ThinVec::new();
1597 if needs_disambiguation {
1598 crate_path.push(ast::PathSegment::path_root(rustc_span::DUMMY_SP));
1599 }
1600 crate_path.push(ast::PathSegment::from_ident(ident.0));
1601
1602 suggestions.extend(self.lookup_import_candidates_from_module(
1603 lookup_ident,
1604 namespace,
1605 parent_scope,
1606 crate_root,
1607 crate_path,
1608 &filter_fn,
1609 ));
1610 }
1611 }
1612
1613 suggestions
1614 }
1615
1616 pub(crate) fn unresolved_macro_suggestions(
1617 &mut self,
1618 err: &mut Diag<'_>,
1619 macro_kind: MacroKind,
1620 parent_scope: &ParentScope<'ra>,
1621 ident: Ident,
1622 krate: &Crate,
1623 sugg_span: Option<Span>,
1624 ) {
1625 self.register_macros_for_all_crates();
1628
1629 let is_expected =
1630 &|res: Res| res.macro_kinds().is_some_and(|k| k.contains(macro_kind.into()));
1631 let suggestion = self.early_lookup_typo_candidate(
1632 ScopeSet::Macro(macro_kind),
1633 parent_scope,
1634 ident,
1635 is_expected,
1636 );
1637 if !self.add_typo_suggestion(err, suggestion, ident.span) {
1638 self.detect_derive_attribute(err, ident, parent_scope, sugg_span);
1639 }
1640
1641 let import_suggestions =
1642 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1643 let (span, found_use) = match parent_scope.module.nearest_parent_mod().as_local() {
1644 Some(def_id) => UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id)),
1645 None => (None, FoundUse::No),
1646 };
1647 show_candidates(
1648 self.tcx,
1649 err,
1650 span,
1651 &import_suggestions,
1652 Instead::No,
1653 found_use,
1654 DiagMode::Normal,
1655 vec![],
1656 "",
1657 );
1658
1659 if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1660 let label_span = ident.span.shrink_to_hi();
1661 let mut spans = MultiSpan::from_span(label_span);
1662 spans.push_span_label(label_span, "put a macro name here");
1663 err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1664 return;
1665 }
1666
1667 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1668 err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1669 return;
1670 }
1671
1672 let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1673 if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1674 });
1675
1676 if let Some((def_id, unused_ident)) = unused_macro {
1677 let scope = self.local_macro_def_scopes[&def_id];
1678 let parent_nearest = parent_scope.module.nearest_parent_mod();
1679 let unused_macro_kinds = self.local_macro_map[def_id].ext.macro_kinds();
1680 if !unused_macro_kinds.contains(macro_kind.into()) {
1681 match macro_kind {
1682 MacroKind::Bang => {
1683 err.subdiagnostic(MacroRulesNot::Func { span: unused_ident.span, ident });
1684 }
1685 MacroKind::Attr => {
1686 err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1687 }
1688 MacroKind::Derive => {
1689 err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1690 }
1691 }
1692 return;
1693 }
1694 if Some(parent_nearest) == scope.opt_def_id() {
1695 err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1696 err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1697 return;
1698 }
1699 }
1700
1701 if ident.name == kw::Default
1702 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1703 {
1704 let span = self.def_span(def_id);
1705 let source_map = self.tcx.sess.source_map();
1706 let head_span = source_map.guess_head_span(span);
1707 err.subdiagnostic(ConsiderAddingADerive {
1708 span: head_span.shrink_to_lo(),
1709 suggestion: "#[derive(Default)]\n".to_string(),
1710 });
1711 }
1712 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1713 let Ok(binding) = self.cm().resolve_ident_in_scope_set(
1714 ident,
1715 ScopeSet::All(ns),
1716 parent_scope,
1717 None,
1718 false,
1719 None,
1720 None,
1721 ) else {
1722 continue;
1723 };
1724
1725 let desc = match binding.res() {
1726 Res::Def(DefKind::Macro(MacroKinds::BANG), _) => {
1727 "a function-like macro".to_string()
1728 }
1729 Res::Def(DefKind::Macro(MacroKinds::ATTR), _) | Res::NonMacroAttr(..) => {
1730 format!("an attribute: `#[{ident}]`")
1731 }
1732 Res::Def(DefKind::Macro(MacroKinds::DERIVE), _) => {
1733 format!("a derive macro: `#[derive({ident})]`")
1734 }
1735 Res::Def(DefKind::Macro(kinds), _) => {
1736 format!("{} {}", kinds.article(), kinds.descr())
1737 }
1738 Res::ToolMod => {
1739 continue;
1741 }
1742 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1743 "only a trait, without a derive macro".to_string()
1744 }
1745 res => format!(
1746 "{} {}, not {} {}",
1747 res.article(),
1748 res.descr(),
1749 macro_kind.article(),
1750 macro_kind.descr_expected(),
1751 ),
1752 };
1753 if let crate::DeclKind::Import { import, .. } = binding.kind
1754 && !import.span.is_dummy()
1755 {
1756 let note = errors::IdentImporterHereButItIsDesc {
1757 span: import.span,
1758 imported_ident: ident,
1759 imported_ident_desc: &desc,
1760 };
1761 err.subdiagnostic(note);
1762 self.record_use(ident, binding, Used::Other);
1765 return;
1766 }
1767 let note = errors::IdentInScopeButItIsDesc {
1768 imported_ident: ident,
1769 imported_ident_desc: &desc,
1770 };
1771 err.subdiagnostic(note);
1772 return;
1773 }
1774
1775 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1776 err.subdiagnostic(AddedMacroUse);
1777 return;
1778 }
1779 }
1780
1781 fn detect_derive_attribute(
1784 &self,
1785 err: &mut Diag<'_>,
1786 ident: Ident,
1787 parent_scope: &ParentScope<'ra>,
1788 sugg_span: Option<Span>,
1789 ) {
1790 let mut derives = vec![];
1795 let mut all_attrs: UnordMap<Symbol, Vec<_>> = UnordMap::default();
1796 #[allow(rustc::potential_query_instability)]
1798 for (def_id, data) in self
1799 .local_macro_map
1800 .iter()
1801 .map(|(local_id, data)| (local_id.to_def_id(), data))
1802 .chain(self.extern_macro_map.borrow().iter().map(|(id, d)| (*id, d)))
1803 {
1804 for helper_attr in &data.ext.helper_attrs {
1805 let item_name = self.tcx.item_name(def_id);
1806 all_attrs.entry(*helper_attr).or_default().push(item_name);
1807 if helper_attr == &ident.name {
1808 derives.push(item_name);
1809 }
1810 }
1811 }
1812 let kind = MacroKind::Derive.descr();
1813 if !derives.is_empty() {
1814 let mut derives: Vec<String> = derives.into_iter().map(|d| d.to_string()).collect();
1816 derives.sort();
1817 derives.dedup();
1818 let msg = match &derives[..] {
1819 [derive] => format!(" `{derive}`"),
1820 [start @ .., last] => format!(
1821 "s {} and `{last}`",
1822 start.iter().map(|d| format!("`{d}`")).collect::<Vec<_>>().join(", ")
1823 ),
1824 [] => unreachable!("we checked for this to be non-empty 10 lines above!?"),
1825 };
1826 let msg = format!(
1827 "`{}` is an attribute that can be used by the {kind}{msg}, you might be \
1828 missing a `derive` attribute",
1829 ident.name,
1830 );
1831 let sugg_span = if let ModuleKind::Def(DefKind::Enum, id, _) = parent_scope.module.kind
1832 {
1833 let span = self.def_span(id);
1834 if span.from_expansion() {
1835 None
1836 } else {
1837 Some(span.shrink_to_lo())
1839 }
1840 } else {
1841 sugg_span
1843 };
1844 match sugg_span {
1845 Some(span) => {
1846 err.span_suggestion_verbose(
1847 span,
1848 msg,
1849 format!("#[derive({})]\n", derives.join(", ")),
1850 Applicability::MaybeIncorrect,
1851 );
1852 }
1853 None => {
1854 err.note(msg);
1855 }
1856 }
1857 } else {
1858 let all_attr_names = all_attrs.keys().map(|s| *s).into_sorted_stable_ord();
1860 if let Some(best_match) = find_best_match_for_name(&all_attr_names, ident.name, None)
1861 && let Some(macros) = all_attrs.get(&best_match)
1862 {
1863 let mut macros: Vec<String> = macros.into_iter().map(|d| d.to_string()).collect();
1864 macros.sort();
1865 macros.dedup();
1866 let msg = match ¯os[..] {
1867 [] => return,
1868 [name] => format!(" `{name}` accepts"),
1869 [start @ .., end] => format!(
1870 "s {} and `{end}` accept",
1871 start.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", "),
1872 ),
1873 };
1874 let msg = format!("the {kind}{msg} the similarly named `{best_match}` attribute");
1875 err.span_suggestion_verbose(
1876 ident.span,
1877 msg,
1878 best_match,
1879 Applicability::MaybeIncorrect,
1880 );
1881 }
1882 }
1883 }
1884
1885 pub(crate) fn add_typo_suggestion(
1886 &self,
1887 err: &mut Diag<'_>,
1888 suggestion: Option<TypoSuggestion>,
1889 span: Span,
1890 ) -> bool {
1891 let suggestion = match suggestion {
1892 None => return false,
1893 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1895 Some(suggestion) => suggestion,
1896 };
1897
1898 let mut did_label_def_span = false;
1899
1900 if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1901 if span.overlaps(def_span) {
1902 return false;
1921 }
1922 let span = self.tcx.sess.source_map().guess_head_span(def_span);
1923 let candidate_descr = suggestion.res.descr();
1924 let candidate = suggestion.candidate;
1925 let label = match suggestion.target {
1926 SuggestionTarget::SimilarlyNamed => {
1927 errors::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
1928 }
1929 SuggestionTarget::SingleItem => {
1930 errors::DefinedHere::SingleItem { span, candidate_descr, candidate }
1931 }
1932 };
1933 did_label_def_span = true;
1934 err.subdiagnostic(label);
1935 }
1936
1937 let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
1938 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1939 && let Some(span) = suggestion.span
1940 && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
1941 && snippet == candidate
1942 {
1943 let candidate = suggestion.candidate;
1944 let msg = format!(
1947 "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
1948 );
1949 if !did_label_def_span {
1950 err.span_label(span, format!("`{candidate}` defined here"));
1951 }
1952 (span, msg, snippet)
1953 } else {
1954 let msg = match suggestion.target {
1955 SuggestionTarget::SimilarlyNamed => format!(
1956 "{} {} with a similar name exists",
1957 suggestion.res.article(),
1958 suggestion.res.descr()
1959 ),
1960 SuggestionTarget::SingleItem => {
1961 format!("maybe you meant this {}", suggestion.res.descr())
1962 }
1963 };
1964 (span, msg, suggestion.candidate.to_ident_string())
1965 };
1966 err.span_suggestion_verbose(span, msg, sugg, Applicability::MaybeIncorrect);
1967 true
1968 }
1969
1970 fn decl_description(&self, b: Decl<'_>, ident: Ident, scope: Scope<'_>) -> String {
1971 let res = b.res();
1972 if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
1973 let (built_in, from) = match scope {
1974 Scope::StdLibPrelude | Scope::MacroUsePrelude => ("", " from prelude"),
1975 Scope::ExternPreludeFlags
1976 if self.tcx.sess.opts.externs.get(ident.as_str()).is_some() =>
1977 {
1978 ("", " passed with `--extern`")
1979 }
1980 _ => {
1981 if matches!(res, Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod) {
1982 ("", "")
1984 } else {
1985 (" built-in", "")
1986 }
1987 }
1988 };
1989
1990 let a = if built_in.is_empty() { res.article() } else { "a" };
1991 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1992 } else {
1993 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1994 format!("the {thing} {introduced} here", thing = res.descr())
1995 }
1996 }
1997
1998 fn ambiguity_diagnostic(&self, ambiguity_error: &AmbiguityError<'ra>) -> errors::Ambiguity {
1999 let AmbiguityError { kind, ident, b1, b2, scope1, scope2, .. } = *ambiguity_error;
2000 let extern_prelude_ambiguity = || {
2001 matches!(scope2, Scope::ExternPreludeFlags)
2003 && self
2004 .extern_prelude
2005 .get(&Macros20NormalizedIdent::new(ident))
2006 .is_some_and(|entry| entry.item_decl.map(|(b, _)| b) == Some(b1))
2007 };
2008 let (b1, b2, scope1, scope2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
2009 (b2, b1, scope2, scope1, true)
2011 } else {
2012 (b1, b2, scope1, scope2, false)
2013 };
2014
2015 let could_refer_to = |b: Decl<'_>, scope: Scope<'ra>, also: &str| {
2016 let what = self.decl_description(b, ident, scope);
2017 let note_msg = format!("`{ident}` could{also} refer to {what}");
2018
2019 let thing = b.res().descr();
2020 let mut help_msgs = Vec::new();
2021 if b.is_glob_import()
2022 && (kind == AmbiguityKind::GlobVsGlob
2023 || kind == AmbiguityKind::GlobVsExpanded
2024 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
2025 {
2026 help_msgs.push(format!(
2027 "consider adding an explicit import of `{ident}` to disambiguate"
2028 ))
2029 }
2030 if b.is_extern_crate() && ident.span.at_least_rust_2018() && !extern_prelude_ambiguity()
2031 {
2032 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
2033 }
2034
2035 if let Scope::ModuleNonGlobs(module, _) | Scope::ModuleGlobs(module, _) = scope {
2036 if module == self.graph_root {
2037 help_msgs.push(format!(
2038 "use `crate::{ident}` to refer to this {thing} unambiguously"
2039 ));
2040 } else if module != self.empty_module && module.is_normal() {
2041 help_msgs.push(format!(
2042 "use `self::{ident}` to refer to this {thing} unambiguously"
2043 ));
2044 }
2045 }
2046
2047 (
2048 Spanned { node: note_msg, span: b.span },
2049 help_msgs
2050 .iter()
2051 .enumerate()
2052 .map(|(i, help_msg)| {
2053 let or = if i == 0 { "" } else { "or " };
2054 format!("{or}{help_msg}")
2055 })
2056 .collect::<Vec<_>>(),
2057 )
2058 };
2059 let (b1_note, b1_help_msgs) = could_refer_to(b1, scope1, "");
2060 let (b2_note, b2_help_msgs) = could_refer_to(b2, scope2, " also");
2061
2062 errors::Ambiguity {
2063 ident,
2064 kind: kind.descr(),
2065 b1_note,
2066 b1_help_msgs,
2067 b2_note,
2068 b2_help_msgs,
2069 }
2070 }
2071
2072 fn ctor_fields_span(&self, decl: Decl<'_>) -> Option<Span> {
2075 let DeclKind::Def(Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id)) =
2076 decl.kind
2077 else {
2078 return None;
2079 };
2080
2081 let def_id = self.tcx.parent(ctor_def_id);
2082 self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) }
2084
2085 fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
2086 let PrivacyError {
2087 ident,
2088 decl,
2089 outermost_res,
2090 parent_scope,
2091 single_nested,
2092 dedup_span,
2093 ref source,
2094 } = *privacy_error;
2095
2096 let res = decl.res();
2097 let ctor_fields_span = self.ctor_fields_span(decl);
2098 let plain_descr = res.descr().to_string();
2099 let nonimport_descr =
2100 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
2101 let import_descr = nonimport_descr.clone() + " import";
2102 let get_descr = |b: Decl<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
2103
2104 let ident_descr = get_descr(decl);
2106 let mut err =
2107 self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
2108
2109 self.mention_default_field_values(source, ident, &mut err);
2110
2111 let mut not_publicly_reexported = false;
2112 if let Some((this_res, outer_ident)) = outermost_res {
2113 let import_suggestions = self.lookup_import_candidates(
2114 outer_ident,
2115 this_res.ns().unwrap_or(Namespace::TypeNS),
2116 &parent_scope,
2117 &|res: Res| res == this_res,
2118 );
2119 let point_to_def = !show_candidates(
2120 self.tcx,
2121 &mut err,
2122 Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
2123 &import_suggestions,
2124 Instead::Yes,
2125 FoundUse::Yes,
2126 DiagMode::Import { append: single_nested, unresolved_import: false },
2127 vec![],
2128 "",
2129 );
2130 if point_to_def && ident.span != outer_ident.span {
2132 not_publicly_reexported = true;
2133 let label = errors::OuterIdentIsNotPubliclyReexported {
2134 span: outer_ident.span,
2135 outer_ident_descr: this_res.descr(),
2136 outer_ident,
2137 };
2138 err.subdiagnostic(label);
2139 }
2140 }
2141
2142 let mut non_exhaustive = None;
2143 if let Some(def_id) = res.opt_def_id()
2147 && !def_id.is_local()
2148 && let Some(attr_span) = find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::NonExhaustive(span) => *span)
2149 {
2150 non_exhaustive = Some(attr_span);
2151 } else if let Some(span) = ctor_fields_span {
2152 let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
2153 err.subdiagnostic(label);
2154 if let Res::Def(_, d) = res
2155 && let Some(fields) = self.field_visibility_spans.get(&d)
2156 {
2157 let spans = fields.iter().map(|span| *span).collect();
2158 let sugg =
2159 errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
2160 err.subdiagnostic(sugg);
2161 }
2162 }
2163
2164 let mut sugg_paths: Vec<(Vec<Ident>, bool)> = vec![];
2165 if let Some(mut def_id) = res.opt_def_id() {
2166 let mut path = vec![def_id];
2168 while let Some(parent) = self.tcx.opt_parent(def_id) {
2169 def_id = parent;
2170 if !def_id.is_top_level_module() {
2171 path.push(def_id);
2172 } else {
2173 break;
2174 }
2175 }
2176 let path_names: Option<Vec<Ident>> = path
2178 .iter()
2179 .rev()
2180 .map(|def_id| {
2181 self.tcx.opt_item_name(*def_id).map(|name| {
2182 Ident::with_dummy_span(if def_id.is_top_level_module() {
2183 kw::Crate
2184 } else {
2185 name
2186 })
2187 })
2188 })
2189 .collect();
2190 if let Some(def_id) = path.get(0)
2191 && let Some(path) = path_names
2192 {
2193 if let Some(def_id) = def_id.as_local() {
2194 if self.effective_visibilities.is_directly_public(def_id) {
2195 sugg_paths.push((path, false));
2196 }
2197 } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
2198 {
2199 sugg_paths.push((path, false));
2200 }
2201 }
2202 }
2203
2204 let first_binding = decl;
2206 let mut next_binding = Some(decl);
2207 let mut next_ident = ident;
2208 let mut path = vec![];
2209 while let Some(binding) = next_binding {
2210 let name = next_ident;
2211 next_binding = match binding.kind {
2212 _ if res == Res::Err => None,
2213 DeclKind::Import { source_decl, import, .. } => match import.kind {
2214 _ if source_decl.span.is_dummy() => None,
2215 ImportKind::Single { source, .. } => {
2216 next_ident = source;
2217 Some(source_decl)
2218 }
2219 ImportKind::Glob { .. }
2220 | ImportKind::MacroUse { .. }
2221 | ImportKind::MacroExport => Some(source_decl),
2222 ImportKind::ExternCrate { .. } => None,
2223 },
2224 _ => None,
2225 };
2226
2227 match binding.kind {
2228 DeclKind::Import { import, .. } => {
2229 for segment in import.module_path.iter().skip(1) {
2230 if segment.ident.name != kw::PathRoot {
2233 path.push(segment.ident);
2234 }
2235 }
2236 sugg_paths.push((
2237 path.iter().cloned().chain(std::iter::once(ident)).collect::<Vec<_>>(),
2238 true, ));
2240 }
2241 DeclKind::Def(_) => {}
2242 }
2243 let first = binding == first_binding;
2244 let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
2245 let mut note_span = MultiSpan::from_span(def_span);
2246 if !first && binding.vis.is_public() {
2247 let desc = match binding.kind {
2248 DeclKind::Import { .. } => "re-export",
2249 _ => "directly",
2250 };
2251 note_span.push_span_label(def_span, format!("you could import this {desc}"));
2252 }
2253 if next_binding.is_none()
2256 && let Some(span) = non_exhaustive
2257 {
2258 note_span.push_span_label(
2259 span,
2260 "cannot be constructed because it is `#[non_exhaustive]`",
2261 );
2262 }
2263 let note = errors::NoteAndRefersToTheItemDefinedHere {
2264 span: note_span,
2265 binding_descr: get_descr(binding),
2266 binding_name: name,
2267 first,
2268 dots: next_binding.is_some(),
2269 };
2270 err.subdiagnostic(note);
2271 }
2272 sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0].name == sym::core, *reexport));
2274 for (sugg, reexport) in sugg_paths {
2275 if not_publicly_reexported {
2276 break;
2277 }
2278 if sugg.len() <= 1 {
2279 continue;
2282 }
2283 let path = join_path_idents(sugg);
2284 let sugg = if reexport {
2285 errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
2286 } else {
2287 errors::ImportIdent::Directly { span: dedup_span, ident, path }
2288 };
2289 err.subdiagnostic(sugg);
2290 break;
2291 }
2292
2293 err.emit();
2294 }
2295
2296 fn mention_default_field_values(
2316 &self,
2317 source: &Option<ast::Expr>,
2318 ident: Ident,
2319 err: &mut Diag<'_>,
2320 ) {
2321 let Some(expr) = source else { return };
2322 let ast::ExprKind::Struct(struct_expr) = &expr.kind else { return };
2323 let Some(segment) = struct_expr.path.segments.last() else { return };
2326 let Some(partial_res) = self.partial_res_map.get(&segment.id) else { return };
2327 let Some(Res::Def(_, def_id)) = partial_res.full_res() else {
2328 return;
2329 };
2330 let Some(default_fields) = self.field_defaults(def_id) else { return };
2331 if struct_expr.fields.is_empty() {
2332 return;
2333 }
2334 let last_span = struct_expr.fields.iter().last().unwrap().span;
2335 let mut iter = struct_expr.fields.iter().peekable();
2336 let mut prev: Option<Span> = None;
2337 while let Some(field) = iter.next() {
2338 if field.expr.span.overlaps(ident.span) {
2339 err.span_label(field.ident.span, "while setting this field");
2340 if default_fields.contains(&field.ident.name) {
2341 let sugg = if last_span == field.span {
2342 vec![(field.span, "..".to_string())]
2343 } else {
2344 vec![
2345 (
2346 match (prev, iter.peek()) {
2348 (_, Some(next)) => field.span.with_hi(next.span.lo()),
2349 (Some(prev), _) => field.span.with_lo(prev.hi()),
2350 (None, None) => field.span,
2351 },
2352 String::new(),
2353 ),
2354 (last_span.shrink_to_hi(), ", ..".to_string()),
2355 ]
2356 };
2357 err.multipart_suggestion_verbose(
2358 format!(
2359 "the type `{ident}` of field `{}` is private, but you can construct \
2360 the default value defined for it in `{}` using `..` in the struct \
2361 initializer expression",
2362 field.ident,
2363 self.tcx.item_name(def_id),
2364 ),
2365 sugg,
2366 Applicability::MachineApplicable,
2367 );
2368 break;
2369 }
2370 }
2371 prev = Some(field.span);
2372 }
2373 }
2374
2375 pub(crate) fn find_similarly_named_module_or_crate(
2376 &self,
2377 ident: Symbol,
2378 current_module: Module<'ra>,
2379 ) -> Option<Symbol> {
2380 let mut candidates = self
2381 .extern_prelude
2382 .keys()
2383 .map(|ident| ident.name)
2384 .chain(
2385 self.local_module_map
2386 .iter()
2387 .filter(|(_, module)| {
2388 current_module.is_ancestor_of(**module) && current_module != **module
2389 })
2390 .flat_map(|(_, module)| module.kind.name()),
2391 )
2392 .chain(
2393 self.extern_module_map
2394 .borrow()
2395 .iter()
2396 .filter(|(_, module)| {
2397 current_module.is_ancestor_of(**module) && current_module != **module
2398 })
2399 .flat_map(|(_, module)| module.kind.name()),
2400 )
2401 .filter(|c| !c.to_string().is_empty())
2402 .collect::<Vec<_>>();
2403 candidates.sort();
2404 candidates.dedup();
2405 find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
2406 }
2407
2408 pub(crate) fn report_path_resolution_error(
2409 &mut self,
2410 path: &[Segment],
2411 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
2413 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
2414 ignore_decl: Option<Decl<'ra>>,
2415 ignore_import: Option<Import<'ra>>,
2416 module: Option<ModuleOrUniformRoot<'ra>>,
2417 failed_segment_idx: usize,
2418 ident: Ident,
2419 diag_metadata: Option<&DiagMetadata<'_>>,
2420 ) -> (String, Option<Suggestion>) {
2421 let is_last = failed_segment_idx == path.len() - 1;
2422 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2423 let module_res = match module {
2424 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2425 _ => None,
2426 };
2427 if module_res == self.graph_root.res() {
2428 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
2429 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2430 candidates
2431 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2432 if let Some(candidate) = candidates.get(0) {
2433 let path = {
2434 let len = candidate.path.segments.len();
2436 let start_index = (0..=failed_segment_idx.min(len - 1))
2437 .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2438 .unwrap_or_default();
2439 let segments =
2440 (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2441 Path { segments, span: Span::default(), tokens: None }
2442 };
2443 (
2444 String::from("unresolved import"),
2445 Some((
2446 vec![(ident.span, pprust::path_to_string(&path))],
2447 String::from("a similar path exists"),
2448 Applicability::MaybeIncorrect,
2449 )),
2450 )
2451 } else if ident.name == sym::core {
2452 (
2453 format!("you might be missing crate `{ident}`"),
2454 Some((
2455 vec![(ident.span, "std".to_string())],
2456 "try using `std` instead of `core`".to_string(),
2457 Applicability::MaybeIncorrect,
2458 )),
2459 )
2460 } else if ident.name == kw::Underscore {
2461 (format!("`_` is not a valid crate or module name"), None)
2462 } else if self.tcx.sess.is_rust_2015() {
2463 (
2464 format!("use of unresolved module or unlinked crate `{ident}`"),
2465 Some((
2466 vec![(
2467 self.current_crate_outer_attr_insert_span,
2468 format!("extern crate {ident};\n"),
2469 )],
2470 if was_invoked_from_cargo() {
2471 format!(
2472 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2473 to add it to your `Cargo.toml` and import it in your code",
2474 )
2475 } else {
2476 format!(
2477 "you might be missing a crate named `{ident}`, add it to your \
2478 project and import it in your code",
2479 )
2480 },
2481 Applicability::MaybeIncorrect,
2482 )),
2483 )
2484 } else {
2485 (format!("could not find `{ident}` in the crate root"), None)
2486 }
2487 } else if failed_segment_idx > 0 {
2488 let parent = path[failed_segment_idx - 1].ident.name;
2489 let parent = match parent {
2490 kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2493 "the list of imported crates".to_owned()
2494 }
2495 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2496 _ => format!("`{parent}`"),
2497 };
2498
2499 let mut msg = format!("could not find `{ident}` in {parent}");
2500 if ns == TypeNS || ns == ValueNS {
2501 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2502 let binding = if let Some(module) = module {
2503 self.cm()
2504 .resolve_ident_in_module(
2505 module,
2506 ident,
2507 ns_to_try,
2508 parent_scope,
2509 None,
2510 ignore_decl,
2511 ignore_import,
2512 )
2513 .ok()
2514 } else if let Some(ribs) = ribs
2515 && let Some(TypeNS | ValueNS) = opt_ns
2516 {
2517 assert!(ignore_import.is_none());
2518 match self.resolve_ident_in_lexical_scope(
2519 ident,
2520 ns_to_try,
2521 parent_scope,
2522 None,
2523 &ribs[ns_to_try],
2524 ignore_decl,
2525 diag_metadata,
2526 ) {
2527 Some(LateDecl::Decl(binding)) => Some(binding),
2529 _ => None,
2530 }
2531 } else {
2532 self.cm()
2533 .resolve_ident_in_scope_set(
2534 ident,
2535 ScopeSet::All(ns_to_try),
2536 parent_scope,
2537 None,
2538 false,
2539 ignore_decl,
2540 ignore_import,
2541 )
2542 .ok()
2543 };
2544 if let Some(binding) = binding {
2545 msg = format!(
2546 "expected {}, found {} `{ident}` in {parent}",
2547 ns.descr(),
2548 binding.res().descr(),
2549 );
2550 };
2551 }
2552 (msg, None)
2553 } else if ident.name == kw::SelfUpper {
2554 if opt_ns.is_none() {
2558 ("`Self` cannot be used in imports".to_string(), None)
2559 } else {
2560 (
2561 "`Self` is only available in impls, traits, and type definitions".to_string(),
2562 None,
2563 )
2564 }
2565 } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2566 let binding = if let Some(ribs) = ribs {
2568 assert!(ignore_import.is_none());
2569 self.resolve_ident_in_lexical_scope(
2570 ident,
2571 ValueNS,
2572 parent_scope,
2573 None,
2574 &ribs[ValueNS],
2575 ignore_decl,
2576 diag_metadata,
2577 )
2578 } else {
2579 None
2580 };
2581 let match_span = match binding {
2582 Some(LateDecl::RibDef(Res::Local(id))) => {
2591 Some(*self.pat_span_map.get(&id).unwrap())
2592 }
2593 Some(LateDecl::Decl(name_binding)) => Some(name_binding.span),
2605 _ => None,
2606 };
2607 let suggestion = match_span.map(|span| {
2608 (
2609 vec![(span, String::from(""))],
2610 format!("`{ident}` is defined here, but is not a type"),
2611 Applicability::MaybeIncorrect,
2612 )
2613 });
2614
2615 (format!("use of undeclared type `{ident}`"), suggestion)
2616 } else {
2617 let mut suggestion = None;
2618 if ident.name == sym::alloc {
2619 suggestion = Some((
2620 vec![],
2621 String::from("add `extern crate alloc` to use the `alloc` crate"),
2622 Applicability::MaybeIncorrect,
2623 ))
2624 }
2625
2626 suggestion = suggestion.or_else(|| {
2627 self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2628 |sugg| {
2629 (
2630 vec![(ident.span, sugg.to_string())],
2631 String::from("there is a crate or module with a similar name"),
2632 Applicability::MaybeIncorrect,
2633 )
2634 },
2635 )
2636 });
2637 if let Ok(binding) = self.cm().resolve_ident_in_scope_set(
2638 ident,
2639 ScopeSet::All(ValueNS),
2640 parent_scope,
2641 None,
2642 false,
2643 ignore_decl,
2644 ignore_import,
2645 ) {
2646 let descr = binding.res().descr();
2647 (format!("{descr} `{ident}` is not a crate or module"), suggestion)
2648 } else {
2649 let suggestion = if suggestion.is_some() {
2650 suggestion
2651 } else if let Some(m) = self.undeclared_module_exists(ident) {
2652 self.undeclared_module_suggest_declare(ident, m)
2653 } else if was_invoked_from_cargo() {
2654 Some((
2655 vec![],
2656 format!(
2657 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2658 to add it to your `Cargo.toml`",
2659 ),
2660 Applicability::MaybeIncorrect,
2661 ))
2662 } else {
2663 Some((
2664 vec![],
2665 format!("you might be missing a crate named `{ident}`",),
2666 Applicability::MaybeIncorrect,
2667 ))
2668 };
2669 (format!("use of unresolved module or unlinked crate `{ident}`"), suggestion)
2670 }
2671 }
2672 }
2673
2674 fn undeclared_module_suggest_declare(
2675 &self,
2676 ident: Ident,
2677 path: std::path::PathBuf,
2678 ) -> Option<(Vec<(Span, String)>, String, Applicability)> {
2679 Some((
2680 vec![(self.current_crate_outer_attr_insert_span, format!("mod {ident};\n"))],
2681 format!(
2682 "to make use of source file {}, use `mod {ident}` \
2683 in this file to declare the module",
2684 path.display()
2685 ),
2686 Applicability::MaybeIncorrect,
2687 ))
2688 }
2689
2690 fn undeclared_module_exists(&self, ident: Ident) -> Option<std::path::PathBuf> {
2691 let map = self.tcx.sess.source_map();
2692
2693 let src = map.span_to_filename(ident.span).into_local_path()?;
2694 let i = ident.as_str();
2695 let dir = src.parent()?;
2697 let src = src.file_stem()?.to_str()?;
2698 for file in [
2699 dir.join(i).with_extension("rs"),
2701 dir.join(i).join("mod.rs"),
2703 ] {
2704 if file.exists() {
2705 return Some(file);
2706 }
2707 }
2708 if !matches!(src, "main" | "lib" | "mod") {
2709 for file in [
2710 dir.join(src).join(i).with_extension("rs"),
2712 dir.join(src).join(i).join("mod.rs"),
2714 ] {
2715 if file.exists() {
2716 return Some(file);
2717 }
2718 }
2719 }
2720 None
2721 }
2722
2723 #[instrument(level = "debug", skip(self, parent_scope))]
2725 pub(crate) fn make_path_suggestion(
2726 &mut self,
2727 mut path: Vec<Segment>,
2728 parent_scope: &ParentScope<'ra>,
2729 ) -> Option<(Vec<Segment>, Option<String>)> {
2730 match path[..] {
2731 [first, second, ..]
2734 if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2735 [first, ..]
2737 if first.ident.span.at_least_rust_2018()
2738 && !first.ident.is_path_segment_keyword() =>
2739 {
2740 path.insert(0, Segment::from_ident(Ident::dummy()));
2742 }
2743 _ => return None,
2744 }
2745
2746 self.make_missing_self_suggestion(path.clone(), parent_scope)
2747 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2748 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2749 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2750 }
2751
2752 #[instrument(level = "debug", skip(self, parent_scope))]
2760 fn make_missing_self_suggestion(
2761 &mut self,
2762 mut path: Vec<Segment>,
2763 parent_scope: &ParentScope<'ra>,
2764 ) -> Option<(Vec<Segment>, Option<String>)> {
2765 path[0].ident.name = kw::SelfLower;
2767 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2768 debug!(?path, ?result);
2769 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2770 }
2771
2772 #[instrument(level = "debug", skip(self, parent_scope))]
2780 fn make_missing_crate_suggestion(
2781 &mut self,
2782 mut path: Vec<Segment>,
2783 parent_scope: &ParentScope<'ra>,
2784 ) -> Option<(Vec<Segment>, Option<String>)> {
2785 path[0].ident.name = kw::Crate;
2787 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2788 debug!(?path, ?result);
2789 if let PathResult::Module(..) = result {
2790 Some((
2791 path,
2792 Some(
2793 "`use` statements changed in Rust 2018; read more at \
2794 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2795 clarity.html>"
2796 .to_string(),
2797 ),
2798 ))
2799 } else {
2800 None
2801 }
2802 }
2803
2804 #[instrument(level = "debug", skip(self, parent_scope))]
2812 fn make_missing_super_suggestion(
2813 &mut self,
2814 mut path: Vec<Segment>,
2815 parent_scope: &ParentScope<'ra>,
2816 ) -> Option<(Vec<Segment>, Option<String>)> {
2817 path[0].ident.name = kw::Super;
2819 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2820 debug!(?path, ?result);
2821 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2822 }
2823
2824 #[instrument(level = "debug", skip(self, parent_scope))]
2835 fn make_external_crate_suggestion(
2836 &mut self,
2837 mut path: Vec<Segment>,
2838 parent_scope: &ParentScope<'ra>,
2839 ) -> Option<(Vec<Segment>, Option<String>)> {
2840 if path[1].ident.span.is_rust_2015() {
2841 return None;
2842 }
2843
2844 let mut extern_crate_names =
2848 self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2849 extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
2850
2851 for name in extern_crate_names.into_iter() {
2852 path[0].ident.name = name;
2854 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2855 debug!(?path, ?name, ?result);
2856 if let PathResult::Module(..) = result {
2857 return Some((path, None));
2858 }
2859 }
2860
2861 None
2862 }
2863
2864 pub(crate) fn check_for_module_export_macro(
2877 &mut self,
2878 import: Import<'ra>,
2879 module: ModuleOrUniformRoot<'ra>,
2880 ident: Ident,
2881 ) -> Option<(Option<Suggestion>, Option<String>)> {
2882 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2883 return None;
2884 };
2885
2886 while let Some(parent) = crate_module.parent {
2887 crate_module = parent;
2888 }
2889
2890 if module == ModuleOrUniformRoot::Module(crate_module) {
2891 return None;
2893 }
2894
2895 let binding_key = BindingKey::new(ident, MacroNS);
2896 let binding = self.resolution(crate_module, binding_key)?.binding()?;
2897 let Res::Def(DefKind::Macro(kinds), _) = binding.res() else {
2898 return None;
2899 };
2900 if !kinds.contains(MacroKinds::BANG) {
2901 return None;
2902 }
2903 let module_name = crate_module.kind.name().unwrap_or(kw::Crate);
2904 let import_snippet = match import.kind {
2905 ImportKind::Single { source, target, .. } if source != target => {
2906 format!("{source} as {target}")
2907 }
2908 _ => format!("{ident}"),
2909 };
2910
2911 let mut corrections: Vec<(Span, String)> = Vec::new();
2912 if !import.is_nested() {
2913 corrections.push((import.span, format!("{module_name}::{import_snippet}")));
2916 } else {
2917 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2921 self.tcx.sess,
2922 import.span,
2923 import.use_span,
2924 );
2925 debug!(found_closing_brace, ?binding_span);
2926
2927 let mut removal_span = binding_span;
2928
2929 if found_closing_brace
2937 && let Some(previous_span) =
2938 extend_span_to_previous_binding(self.tcx.sess, binding_span)
2939 {
2940 debug!(?previous_span);
2941 removal_span = removal_span.with_lo(previous_span.lo());
2942 }
2943 debug!(?removal_span);
2944
2945 corrections.push((removal_span, "".to_string()));
2947
2948 let (has_nested, after_crate_name) =
2955 find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
2956 debug!(has_nested, ?after_crate_name);
2957
2958 let source_map = self.tcx.sess.source_map();
2959
2960 let is_definitely_crate = import
2962 .module_path
2963 .first()
2964 .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
2965
2966 let start_point = source_map.start_point(after_crate_name);
2968 if is_definitely_crate
2969 && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
2970 {
2971 corrections.push((
2972 start_point,
2973 if has_nested {
2974 format!("{start_snippet}{import_snippet}, ")
2976 } else {
2977 format!("{{{import_snippet}, {start_snippet}")
2980 },
2981 ));
2982
2983 if !has_nested {
2985 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2986 }
2987 } else {
2988 corrections.push((
2990 import.use_span.shrink_to_lo(),
2991 format!("use {module_name}::{import_snippet};\n"),
2992 ));
2993 }
2994 }
2995
2996 let suggestion = Some((
2997 corrections,
2998 String::from("a macro with this name exists at the root of the crate"),
2999 Applicability::MaybeIncorrect,
3000 ));
3001 Some((
3002 suggestion,
3003 Some(
3004 "this could be because a macro annotated with `#[macro_export]` will be exported \
3005 at the root of the crate instead of the module where it is defined"
3006 .to_string(),
3007 ),
3008 ))
3009 }
3010
3011 pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
3013 let local_items;
3014 let symbols = if module.is_local() {
3015 local_items = self
3016 .stripped_cfg_items
3017 .iter()
3018 .filter_map(|item| {
3019 let parent_module = self.opt_local_def_id(item.parent_module)?.to_def_id();
3020 Some(StrippedCfgItem {
3021 parent_module,
3022 ident: item.ident,
3023 cfg: item.cfg.clone(),
3024 })
3025 })
3026 .collect::<Vec<_>>();
3027 local_items.as_slice()
3028 } else {
3029 self.tcx.stripped_cfg_items(module.krate)
3030 };
3031
3032 for &StrippedCfgItem { parent_module, ident, ref cfg } in symbols {
3033 if ident.name != *segment {
3034 continue;
3035 }
3036
3037 fn comes_from_same_module_for_glob(
3038 r: &Resolver<'_, '_>,
3039 parent_module: DefId,
3040 module: DefId,
3041 visited: &mut FxHashMap<DefId, bool>,
3042 ) -> bool {
3043 if let Some(&cached) = visited.get(&parent_module) {
3044 return cached;
3048 }
3049 visited.insert(parent_module, false);
3050 let m = r.expect_module(parent_module);
3051 let mut res = false;
3052 for importer in m.glob_importers.borrow().iter() {
3053 if let Some(next_parent_module) = importer.parent_scope.module.opt_def_id() {
3054 if next_parent_module == module
3055 || comes_from_same_module_for_glob(
3056 r,
3057 next_parent_module,
3058 module,
3059 visited,
3060 )
3061 {
3062 res = true;
3063 break;
3064 }
3065 }
3066 }
3067 visited.insert(parent_module, res);
3068 res
3069 }
3070
3071 let comes_from_same_module = parent_module == module
3072 || comes_from_same_module_for_glob(
3073 self,
3074 parent_module,
3075 module,
3076 &mut Default::default(),
3077 );
3078 if !comes_from_same_module {
3079 continue;
3080 }
3081
3082 let item_was = if let CfgEntry::NameValue { value: Some(feature), .. } = cfg.0 {
3083 errors::ItemWas::BehindFeature { feature, span: cfg.1 }
3084 } else {
3085 errors::ItemWas::CfgOut { span: cfg.1 }
3086 };
3087 let note = errors::FoundItemConfigureOut { span: ident.span, item_was };
3088 err.subdiagnostic(note);
3089 }
3090 }
3091}
3092
3093fn find_span_of_binding_until_next_binding(
3107 sess: &Session,
3108 binding_span: Span,
3109 use_span: Span,
3110) -> (bool, Span) {
3111 let source_map = sess.source_map();
3112
3113 let binding_until_end = binding_span.with_hi(use_span.hi());
3116
3117 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
3120
3121 let mut found_closing_brace = false;
3128 let after_binding_until_next_binding =
3129 source_map.span_take_while(after_binding_until_end, |&ch| {
3130 if ch == '}' {
3131 found_closing_brace = true;
3132 }
3133 ch == ' ' || ch == ','
3134 });
3135
3136 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
3141
3142 (found_closing_brace, span)
3143}
3144
3145fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
3158 let source_map = sess.source_map();
3159
3160 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
3164
3165 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
3166 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
3167 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
3168 return None;
3169 }
3170
3171 let prev_comma = prev_comma.first().unwrap();
3172 let prev_starting_brace = prev_starting_brace.first().unwrap();
3173
3174 if prev_comma.len() > prev_starting_brace.len() {
3178 return None;
3179 }
3180
3181 Some(binding_span.with_lo(BytePos(
3182 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
3185 )))
3186}
3187
3188#[instrument(level = "debug", skip(sess))]
3202fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
3203 let source_map = sess.source_map();
3204
3205 let mut num_colons = 0;
3207 let until_second_colon = source_map.span_take_while(use_span, |c| {
3209 if *c == ':' {
3210 num_colons += 1;
3211 }
3212 !matches!(c, ':' if num_colons == 2)
3213 });
3214 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
3216
3217 let mut found_a_non_whitespace_character = false;
3218 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
3220 if found_a_non_whitespace_character {
3221 return false;
3222 }
3223 if !c.is_whitespace() {
3224 found_a_non_whitespace_character = true;
3225 }
3226 true
3227 });
3228
3229 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
3231
3232 (next_left_bracket == after_second_colon, from_second_colon)
3233}
3234
3235enum Instead {
3238 Yes,
3239 No,
3240}
3241
3242enum FoundUse {
3244 Yes,
3245 No,
3246}
3247
3248pub(crate) enum DiagMode {
3250 Normal,
3251 Pattern,
3253 Import {
3255 unresolved_import: bool,
3257 append: bool,
3260 },
3261}
3262
3263pub(crate) fn import_candidates(
3264 tcx: TyCtxt<'_>,
3265 err: &mut Diag<'_>,
3266 use_placement_span: Option<Span>,
3268 candidates: &[ImportSuggestion],
3269 mode: DiagMode,
3270 append: &str,
3271) {
3272 show_candidates(
3273 tcx,
3274 err,
3275 use_placement_span,
3276 candidates,
3277 Instead::Yes,
3278 FoundUse::Yes,
3279 mode,
3280 vec![],
3281 append,
3282 );
3283}
3284
3285type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
3286
3287fn show_candidates(
3292 tcx: TyCtxt<'_>,
3293 err: &mut Diag<'_>,
3294 use_placement_span: Option<Span>,
3296 candidates: &[ImportSuggestion],
3297 instead: Instead,
3298 found_use: FoundUse,
3299 mode: DiagMode,
3300 path: Vec<Segment>,
3301 append: &str,
3302) -> bool {
3303 if candidates.is_empty() {
3304 return false;
3305 }
3306
3307 let mut showed = false;
3308 let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
3309 let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
3310
3311 candidates.iter().for_each(|c| {
3312 if c.accessible {
3313 if c.doc_visible {
3315 accessible_path_strings.push((
3316 pprust::path_to_string(&c.path),
3317 c.descr,
3318 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3319 &c.note,
3320 c.via_import,
3321 ))
3322 }
3323 } else {
3324 inaccessible_path_strings.push((
3325 pprust::path_to_string(&c.path),
3326 c.descr,
3327 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3328 &c.note,
3329 c.via_import,
3330 ))
3331 }
3332 });
3333
3334 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
3337 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
3338 path_strings.dedup_by(|a, b| a.0 == b.0);
3339 let core_path_strings =
3340 path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
3341 let std_path_strings =
3342 path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
3343 let foreign_crate_path_strings =
3344 path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
3345
3346 if std_path_strings.len() == core_path_strings.len() {
3349 path_strings.extend(std_path_strings);
3351 } else {
3352 path_strings.extend(std_path_strings);
3353 path_strings.extend(core_path_strings);
3354 }
3355 path_strings.extend(foreign_crate_path_strings);
3357 }
3358
3359 if !accessible_path_strings.is_empty() {
3360 let (determiner, kind, s, name, through) =
3361 if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
3362 (
3363 "this",
3364 *descr,
3365 "",
3366 format!(" `{name}`"),
3367 if *via_import { " through its public re-export" } else { "" },
3368 )
3369 } else {
3370 let kinds = accessible_path_strings
3373 .iter()
3374 .map(|(_, descr, _, _, _)| *descr)
3375 .collect::<UnordSet<&str>>();
3376 let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
3377 let s = if kind.ends_with('s') { "es" } else { "s" };
3378
3379 ("one of these", kind, s, String::new(), "")
3380 };
3381
3382 let instead = if let Instead::Yes = instead { " instead" } else { "" };
3383 let mut msg = if let DiagMode::Pattern = mode {
3384 format!(
3385 "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
3386 pattern",
3387 )
3388 } else {
3389 format!("consider importing {determiner} {kind}{s}{through}{instead}")
3390 };
3391
3392 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3393 err.note(note.clone());
3394 }
3395
3396 let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
3397 msg.push(':');
3398
3399 for candidate in accessible_path_strings {
3400 msg.push('\n');
3401 msg.push_str(&candidate.0);
3402 }
3403 };
3404
3405 if let Some(span) = use_placement_span {
3406 let (add_use, trailing) = match mode {
3407 DiagMode::Pattern => {
3408 err.span_suggestions(
3409 span,
3410 msg,
3411 accessible_path_strings.into_iter().map(|a| a.0),
3412 Applicability::MaybeIncorrect,
3413 );
3414 return true;
3415 }
3416 DiagMode::Import { .. } => ("", ""),
3417 DiagMode::Normal => ("use ", ";\n"),
3418 };
3419 for candidate in &mut accessible_path_strings {
3420 let additional_newline = if let FoundUse::No = found_use
3423 && let DiagMode::Normal = mode
3424 {
3425 "\n"
3426 } else {
3427 ""
3428 };
3429 candidate.0 =
3430 format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
3431 }
3432
3433 match mode {
3434 DiagMode::Import { append: true, .. } => {
3435 append_candidates(&mut msg, accessible_path_strings);
3436 err.span_help(span, msg);
3437 }
3438 _ => {
3439 err.span_suggestions_with_style(
3440 span,
3441 msg,
3442 accessible_path_strings.into_iter().map(|a| a.0),
3443 Applicability::MaybeIncorrect,
3444 SuggestionStyle::ShowAlways,
3445 );
3446 }
3447 }
3448
3449 if let [first, .., last] = &path[..] {
3450 let sp = first.ident.span.until(last.ident.span);
3451 if sp.can_be_used_for_suggestions() && !sp.is_empty() {
3454 err.span_suggestion_verbose(
3455 sp,
3456 format!("if you import `{}`, refer to it directly", last.ident),
3457 "",
3458 Applicability::Unspecified,
3459 );
3460 }
3461 }
3462 } else {
3463 append_candidates(&mut msg, accessible_path_strings);
3464 err.help(msg);
3465 }
3466 showed = true;
3467 }
3468 if !inaccessible_path_strings.is_empty()
3469 && (!matches!(mode, DiagMode::Import { unresolved_import: false, .. }))
3470 {
3471 let prefix =
3472 if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
3473 if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
3474 let msg = format!(
3475 "{prefix}{descr} `{name}`{} exists but is inaccessible",
3476 if let DiagMode::Pattern = mode { ", which" } else { "" }
3477 );
3478
3479 if let Some(source_span) = source_span {
3480 let span = tcx.sess.source_map().guess_head_span(*source_span);
3481 let mut multi_span = MultiSpan::from_span(span);
3482 multi_span.push_span_label(span, "not accessible");
3483 err.span_note(multi_span, msg);
3484 } else {
3485 err.note(msg);
3486 }
3487 if let Some(note) = (*note).as_deref() {
3488 err.note(note.to_string());
3489 }
3490 } else {
3491 let descr = inaccessible_path_strings
3492 .iter()
3493 .map(|&(_, descr, _, _, _)| descr)
3494 .all_equal_value()
3495 .unwrap_or("item");
3496 let plural_descr =
3497 if descr.ends_with('s') { format!("{descr}es") } else { format!("{descr}s") };
3498
3499 let mut msg = format!("{prefix}these {plural_descr} exist but are inaccessible");
3500 let mut has_colon = false;
3501
3502 let mut spans = Vec::new();
3503 for (name, _, source_span, _, _) in &inaccessible_path_strings {
3504 if let Some(source_span) = source_span {
3505 let span = tcx.sess.source_map().guess_head_span(*source_span);
3506 spans.push((name, span));
3507 } else {
3508 if !has_colon {
3509 msg.push(':');
3510 has_colon = true;
3511 }
3512 msg.push('\n');
3513 msg.push_str(name);
3514 }
3515 }
3516
3517 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3518 for (name, span) in spans {
3519 multi_span.push_span_label(span, format!("`{name}`: not accessible"));
3520 }
3521
3522 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3523 err.note(note.clone());
3524 }
3525
3526 err.span_note(multi_span, msg);
3527 }
3528 showed = true;
3529 }
3530 showed
3531}
3532
3533#[derive(Debug)]
3534struct UsePlacementFinder {
3535 target_module: NodeId,
3536 first_legal_span: Option<Span>,
3537 first_use_span: Option<Span>,
3538}
3539
3540impl UsePlacementFinder {
3541 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3542 let mut finder =
3543 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3544 finder.visit_crate(krate);
3545 if let Some(use_span) = finder.first_use_span {
3546 (Some(use_span), FoundUse::Yes)
3547 } else {
3548 (finder.first_legal_span, FoundUse::No)
3549 }
3550 }
3551}
3552
3553impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
3554 fn visit_crate(&mut self, c: &Crate) {
3555 if self.target_module == CRATE_NODE_ID {
3556 let inject = c.spans.inject_use_span;
3557 if is_span_suitable_for_use_injection(inject) {
3558 self.first_legal_span = Some(inject);
3559 }
3560 self.first_use_span = search_for_any_use_in_items(&c.items);
3561 } else {
3562 visit::walk_crate(self, c);
3563 }
3564 }
3565
3566 fn visit_item(&mut self, item: &'tcx ast::Item) {
3567 if self.target_module == item.id {
3568 if let ItemKind::Mod(_, _, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
3569 let inject = mod_spans.inject_use_span;
3570 if is_span_suitable_for_use_injection(inject) {
3571 self.first_legal_span = Some(inject);
3572 }
3573 self.first_use_span = search_for_any_use_in_items(items);
3574 }
3575 } else {
3576 visit::walk_item(self, item);
3577 }
3578 }
3579}
3580
3581#[derive(Default)]
3582struct BindingVisitor {
3583 identifiers: Vec<Symbol>,
3584 spans: FxHashMap<Symbol, Vec<Span>>,
3585}
3586
3587impl<'tcx> Visitor<'tcx> for BindingVisitor {
3588 fn visit_pat(&mut self, pat: &ast::Pat) {
3589 if let ast::PatKind::Ident(_, ident, _) = pat.kind {
3590 self.identifiers.push(ident.name);
3591 self.spans.entry(ident.name).or_default().push(ident.span);
3592 }
3593 visit::walk_pat(self, pat);
3594 }
3595}
3596
3597fn search_for_any_use_in_items(items: &[Box<ast::Item>]) -> Option<Span> {
3598 for item in items {
3599 if let ItemKind::Use(..) = item.kind
3600 && is_span_suitable_for_use_injection(item.span)
3601 {
3602 let mut lo = item.span.lo();
3603 for attr in &item.attrs {
3604 if attr.span.eq_ctxt(item.span) {
3605 lo = std::cmp::min(lo, attr.span.lo());
3606 }
3607 }
3608 return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3609 }
3610 }
3611 None
3612}
3613
3614fn is_span_suitable_for_use_injection(s: Span) -> bool {
3615 !s.from_expansion()
3618}