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