1use rustc_ast::expand::StrippedCfgItem;
2use rustc_ast::ptr::P;
3use rustc_ast::visit::{self, Visitor};
4use rustc_ast::{
5 self as ast, CRATE_NODE_ID, Crate, ItemKind, MetaItemInner, MetaItemKind, ModKind, NodeId, Path,
6};
7use rustc_ast_pretty::pprust;
8use rustc_data_structures::fx::FxHashSet;
9use rustc_data_structures::unord::UnordSet;
10use rustc_errors::codes::*;
11use rustc_errors::{
12 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, MultiSpan, SuggestionStyle,
13 report_ambiguity_error, struct_span_code_err,
14};
15use rustc_feature::BUILTIN_ATTRIBUTES;
16use rustc_hir::PrimTy;
17use rustc_hir::def::Namespace::{self, *};
18use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS};
19use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
20use rustc_middle::bug;
21use rustc_middle::ty::TyCtxt;
22use rustc_session::Session;
23use rustc_session::lint::builtin::{
24 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS,
25 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
26};
27use rustc_session::lint::{AmbiguityErrorDiag, BuiltinLintDiag};
28use rustc_session::utils::was_invoked_from_cargo;
29use rustc_span::edit_distance::find_best_match_for_name;
30use rustc_span::edition::Edition;
31use rustc_span::hygiene::MacroKind;
32use rustc_span::source_map::SourceMap;
33use rustc_span::{BytePos, Ident, Span, Symbol, SyntaxContext, kw, sym};
34use thin_vec::{ThinVec, thin_vec};
35use tracing::{debug, instrument};
36
37use crate::errors::{
38 self, AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion, ConsiderAddingADerive,
39 ExplicitUnsafeTraits, MacroDefinedLater, MacroRulesNot, MacroSuggMovePosition,
40 MaybeMissingMacroRulesName,
41};
42use crate::imports::{Import, ImportKind};
43use crate::late::{PatternSource, Rib};
44use crate::{
45 AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, BindingKey, Finalize,
46 ForwardGenericParamBanReason, HasGenericParams, LexicalScopeBinding, MacroRulesScope, Module,
47 ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult,
48 PrivacyError, ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used,
49 VisResolutionError, errors as errs, path_names_to_string,
50};
51
52type Res = def::Res<ast::NodeId>;
53
54pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
56
57pub(crate) type LabelSuggestion = (Ident, bool);
60
61#[derive(Debug)]
62pub(crate) enum SuggestionTarget {
63 SimilarlyNamed,
65 SingleItem,
67}
68
69#[derive(Debug)]
70pub(crate) struct TypoSuggestion {
71 pub candidate: Symbol,
72 pub span: Option<Span>,
75 pub res: Res,
76 pub target: SuggestionTarget,
77}
78
79impl TypoSuggestion {
80 pub(crate) fn typo_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
81 Self {
82 candidate: ident.name,
83 span: Some(ident.span),
84 res,
85 target: SuggestionTarget::SimilarlyNamed,
86 }
87 }
88 pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
89 Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
90 }
91 pub(crate) fn single_item_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
92 Self {
93 candidate: ident.name,
94 span: Some(ident.span),
95 res,
96 target: SuggestionTarget::SingleItem,
97 }
98 }
99}
100
101#[derive(Debug, Clone)]
103pub(crate) struct ImportSuggestion {
104 pub did: Option<DefId>,
105 pub descr: &'static str,
106 pub path: Path,
107 pub accessible: bool,
108 pub doc_visible: bool,
110 pub via_import: bool,
111 pub note: Option<String>,
113}
114
115fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
123 let impl_span = sm.span_until_char(impl_span, '<');
124 sm.span_until_whitespace(impl_span)
125}
126
127impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
128 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
129 self.tcx.dcx()
130 }
131
132 pub(crate) fn report_errors(&mut self, krate: &Crate) {
133 self.report_with_use_injections(krate);
134
135 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
136 self.lint_buffer.buffer_lint(
137 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
138 CRATE_NODE_ID,
139 span_use,
140 BuiltinLintDiag::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
141 );
142 }
143
144 for ambiguity_error in &self.ambiguity_errors {
145 let diag = self.ambiguity_diagnostics(ambiguity_error);
146 if ambiguity_error.warning {
147 let NameBindingKind::Import { import, .. } = ambiguity_error.b1.0.kind else {
148 unreachable!()
149 };
150 self.lint_buffer.buffer_lint(
151 AMBIGUOUS_GLOB_IMPORTS,
152 import.root_id,
153 ambiguity_error.ident.span,
154 BuiltinLintDiag::AmbiguousGlobImports { diag },
155 );
156 } else {
157 let mut err = struct_span_code_err!(self.dcx(), diag.span, E0659, "{}", diag.msg);
158 report_ambiguity_error(&mut err, diag);
159 err.emit();
160 }
161 }
162
163 let mut reported_spans = FxHashSet::default();
164 for error in std::mem::take(&mut self.privacy_errors) {
165 if reported_spans.insert(error.dedup_span) {
166 self.report_privacy_error(&error);
167 }
168 }
169 }
170
171 fn report_with_use_injections(&mut self, krate: &Crate) {
172 for UseError { mut err, candidates, def_id, instead, suggestion, path, is_call } in
173 self.use_injections.drain(..)
174 {
175 let (span, found_use) = if let Some(def_id) = def_id.as_local() {
176 UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id])
177 } else {
178 (None, FoundUse::No)
179 };
180
181 if !candidates.is_empty() {
182 show_candidates(
183 self.tcx,
184 &mut err,
185 span,
186 &candidates,
187 if instead { Instead::Yes } else { Instead::No },
188 found_use,
189 DiagMode::Normal,
190 path,
191 "",
192 );
193 err.emit();
194 } else if let Some((span, msg, sugg, appl)) = suggestion {
195 err.span_suggestion_verbose(span, msg, sugg, appl);
196 err.emit();
197 } else if let [segment] = path.as_slice()
198 && is_call
199 {
200 err.stash(segment.ident.span, rustc_errors::StashKey::CallIntoMethod);
201 } else {
202 err.emit();
203 }
204 }
205 }
206
207 pub(crate) fn report_conflict(
208 &mut self,
209 parent: Module<'_>,
210 ident: Ident,
211 ns: Namespace,
212 new_binding: NameBinding<'ra>,
213 old_binding: NameBinding<'ra>,
214 ) {
215 if old_binding.span.lo() > new_binding.span.lo() {
217 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
218 }
219
220 let container = match parent.kind {
221 ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
224 ModuleKind::Block => "block",
225 };
226
227 let (name, span) =
228 (ident.name, self.tcx.sess.source_map().guess_head_span(new_binding.span));
229
230 if self.name_already_seen.get(&name) == Some(&span) {
231 return;
232 }
233
234 let old_kind = match (ns, old_binding.module()) {
235 (ValueNS, _) => "value",
236 (MacroNS, _) => "macro",
237 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
238 (TypeNS, Some(module)) if module.is_normal() => "module",
239 (TypeNS, Some(module)) if module.is_trait() => "trait",
240 (TypeNS, _) => "type",
241 };
242
243 let code = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
244 (true, true) => E0259,
245 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
246 true => E0254,
247 false => E0260,
248 },
249 _ => match (old_binding.is_import_user_facing(), new_binding.is_import_user_facing()) {
250 (false, false) => E0428,
251 (true, true) => E0252,
252 _ => E0255,
253 },
254 };
255
256 let label = match new_binding.is_import_user_facing() {
257 true => errors::NameDefinedMultipleTimeLabel::Reimported { span, name },
258 false => errors::NameDefinedMultipleTimeLabel::Redefined { span, name },
259 };
260
261 let old_binding_label =
262 (!old_binding.span.is_dummy() && old_binding.span != span).then(|| {
263 let span = self.tcx.sess.source_map().guess_head_span(old_binding.span);
264 match old_binding.is_import_user_facing() {
265 true => errors::NameDefinedMultipleTimeOldBindingLabel::Import {
266 span,
267 name,
268 old_kind,
269 },
270 false => errors::NameDefinedMultipleTimeOldBindingLabel::Definition {
271 span,
272 name,
273 old_kind,
274 },
275 }
276 });
277
278 let mut err = self
279 .dcx()
280 .create_err(errors::NameDefinedMultipleTime {
281 span,
282 descr: ns.descr(),
283 container,
284 label,
285 old_binding_label,
286 })
287 .with_code(code);
288
289 use NameBindingKind::Import;
291 let can_suggest = |binding: NameBinding<'_>, import: self::Import<'_>| {
292 !binding.span.is_dummy()
293 && !matches!(import.kind, ImportKind::MacroUse { .. } | ImportKind::MacroExport)
294 };
295 let import = match (&new_binding.kind, &old_binding.kind) {
296 (Import { import: new, .. }, Import { import: old, .. })
299 if {
300 (new.has_attributes || old.has_attributes)
301 && can_suggest(old_binding, *old)
302 && can_suggest(new_binding, *new)
303 } =>
304 {
305 if old.has_attributes {
306 Some((*new, new_binding.span, true))
307 } else {
308 Some((*old, old_binding.span, true))
309 }
310 }
311 (Import { import, .. }, other) if can_suggest(new_binding, *import) => {
313 Some((*import, new_binding.span, other.is_import()))
314 }
315 (other, Import { import, .. }) if can_suggest(old_binding, *import) => {
316 Some((*import, old_binding.span, other.is_import()))
317 }
318 _ => None,
319 };
320
321 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
323 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
324 let from_item =
325 self.extern_prelude.get(&ident).is_none_or(|entry| entry.introduced_by_item);
326 let should_remove_import = duplicate
330 && !has_dummy_span
331 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
332
333 match import {
334 Some((import, span, true)) if should_remove_import && import.is_nested() => {
335 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span);
336 }
337 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
338 err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport {
341 span: import.use_span_with_attributes,
342 });
343 }
344 Some((import, span, _)) => {
345 self.add_suggestion_for_rename_of_use(&mut err, name, import, span);
346 }
347 _ => {}
348 }
349
350 err.emit();
351 self.name_already_seen.insert(name, span);
352 }
353
354 fn add_suggestion_for_rename_of_use(
364 &self,
365 err: &mut Diag<'_>,
366 name: Symbol,
367 import: Import<'_>,
368 binding_span: Span,
369 ) {
370 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
371 format!("Other{name}")
372 } else {
373 format!("other_{name}")
374 };
375
376 let mut suggestion = None;
377 let mut span = binding_span;
378 match import.kind {
379 ImportKind::Single { type_ns_only: true, .. } => {
380 suggestion = Some(format!("self as {suggested_name}"))
381 }
382 ImportKind::Single { source, .. } => {
383 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
384 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(binding_span)
385 && pos as usize <= snippet.len()
386 {
387 span = binding_span.with_lo(binding_span.lo() + BytePos(pos)).with_hi(
388 binding_span.hi() - BytePos(if snippet.ends_with(';') { 1 } else { 0 }),
389 );
390 suggestion = Some(format!(" as {suggested_name}"));
391 }
392 }
393 ImportKind::ExternCrate { source, target, .. } => {
394 suggestion = Some(format!(
395 "extern crate {} as {};",
396 source.unwrap_or(target.name),
397 suggested_name,
398 ))
399 }
400 _ => unreachable!(),
401 }
402
403 if let Some(suggestion) = suggestion {
404 err.subdiagnostic(ChangeImportBindingSuggestion { span, suggestion });
405 } else {
406 err.subdiagnostic(ChangeImportBinding { span });
407 }
408 }
409
410 fn add_suggestion_for_duplicate_nested_use(
433 &self,
434 err: &mut Diag<'_>,
435 import: Import<'_>,
436 binding_span: Span,
437 ) {
438 assert!(import.is_nested());
439
440 let (found_closing_brace, span) =
448 find_span_of_binding_until_next_binding(self.tcx.sess, binding_span, import.use_span);
449
450 if found_closing_brace {
453 if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) {
454 err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport { span });
455 } else {
456 err.subdiagnostic(errors::RemoveUnnecessaryImport {
459 span: import.use_span_with_attributes,
460 });
461 }
462
463 return;
464 }
465
466 err.subdiagnostic(errors::RemoveUnnecessaryImport { span });
467 }
468
469 pub(crate) fn lint_if_path_starts_with_module(
470 &mut self,
471 finalize: Option<Finalize>,
472 path: &[Segment],
473 second_binding: Option<NameBinding<'_>>,
474 ) {
475 let Some(Finalize { node_id, root_span, .. }) = finalize else {
476 return;
477 };
478
479 let first_name = match path.get(0) {
480 Some(seg) if seg.ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015() => {
482 seg.ident.name
483 }
484 _ => return,
485 };
486
487 if first_name != kw::PathRoot {
490 return;
491 }
492
493 match path.get(1) {
494 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
496 Some(_) => {}
498 None => return,
502 }
503
504 if let Some(binding) = second_binding
508 && let NameBindingKind::Import { import, .. } = binding.kind
509 && let ImportKind::ExternCrate { source: None, .. } = import.kind
511 {
512 return;
513 }
514
515 let diag = BuiltinLintDiag::AbsPathWithModule(root_span);
516 self.lint_buffer.buffer_lint(
517 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
518 node_id,
519 root_span,
520 diag,
521 );
522 }
523
524 pub(crate) fn add_module_candidates(
525 &mut self,
526 module: Module<'ra>,
527 names: &mut Vec<TypoSuggestion>,
528 filter_fn: &impl Fn(Res) -> bool,
529 ctxt: Option<SyntaxContext>,
530 ) {
531 module.for_each_child(self, |_this, ident, _ns, binding| {
532 let res = binding.res();
533 if filter_fn(res) && ctxt.is_none_or(|ctxt| ctxt == ident.span.ctxt()) {
534 names.push(TypoSuggestion::typo_from_ident(ident, res));
535 }
536 });
537 }
538
539 pub(crate) fn report_error(
544 &mut self,
545 span: Span,
546 resolution_error: ResolutionError<'ra>,
547 ) -> ErrorGuaranteed {
548 self.into_struct_error(span, resolution_error).emit()
549 }
550
551 pub(crate) fn into_struct_error(
552 &mut self,
553 span: Span,
554 resolution_error: ResolutionError<'ra>,
555 ) -> Diag<'_> {
556 match resolution_error {
557 ResolutionError::GenericParamsFromOuterItem(
558 outer_res,
559 has_generic_params,
560 def_kind,
561 ) => {
562 use errs::GenericParamsFromOuterItemLabel as Label;
563 let static_or_const = match def_kind {
564 DefKind::Static { .. } => {
565 Some(errs::GenericParamsFromOuterItemStaticOrConst::Static)
566 }
567 DefKind::Const => Some(errs::GenericParamsFromOuterItemStaticOrConst::Const),
568 _ => None,
569 };
570 let is_self =
571 matches!(outer_res, Res::SelfTyParam { .. } | Res::SelfTyAlias { .. });
572 let mut err = errs::GenericParamsFromOuterItem {
573 span,
574 label: None,
575 refer_to_type_directly: None,
576 sugg: None,
577 static_or_const,
578 is_self,
579 };
580
581 let sm = self.tcx.sess.source_map();
582 let def_id = match outer_res {
583 Res::SelfTyParam { .. } => {
584 err.label = Some(Label::SelfTyParam(span));
585 return self.dcx().create_err(err);
586 }
587 Res::SelfTyAlias { alias_to: def_id, .. } => {
588 err.label = Some(Label::SelfTyAlias(reduce_impl_span_to_impl_keyword(
589 sm,
590 self.def_span(def_id),
591 )));
592 err.refer_to_type_directly = Some(span);
593 return self.dcx().create_err(err);
594 }
595 Res::Def(DefKind::TyParam, def_id) => {
596 err.label = Some(Label::TyParam(self.def_span(def_id)));
597 def_id
598 }
599 Res::Def(DefKind::ConstParam, def_id) => {
600 err.label = Some(Label::ConstParam(self.def_span(def_id)));
601 def_id
602 }
603 _ => {
604 bug!(
605 "GenericParamsFromOuterItem should only be used with \
606 Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
607 DefKind::ConstParam"
608 );
609 }
610 };
611
612 if let HasGenericParams::Yes(span) = has_generic_params {
613 let name = self.tcx.item_name(def_id);
614 let (span, snippet) = if span.is_empty() {
615 let snippet = format!("<{name}>");
616 (span, snippet)
617 } else {
618 let span = sm.span_through_char(span, '<').shrink_to_hi();
619 let snippet = format!("{name}, ");
620 (span, snippet)
621 };
622 err.sugg = Some(errs::GenericParamsFromOuterItemSugg { span, snippet });
623 }
624
625 self.dcx().create_err(err)
626 }
627 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
628 .dcx()
629 .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
630 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
631 self.dcx().create_err(errs::MethodNotMemberOfTrait {
632 span,
633 method,
634 trait_,
635 sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
636 span: method.span,
637 candidate: c,
638 }),
639 })
640 }
641 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
642 self.dcx().create_err(errs::TypeNotMemberOfTrait {
643 span,
644 type_,
645 trait_,
646 sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
647 span: type_.span,
648 candidate: c,
649 }),
650 })
651 }
652 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
653 self.dcx().create_err(errs::ConstNotMemberOfTrait {
654 span,
655 const_,
656 trait_,
657 sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
658 span: const_.span,
659 candidate: c,
660 }),
661 })
662 }
663 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
664 let BindingError { name, target, origin, could_be_path } = binding_error;
665
666 let target_sp = target.iter().copied().collect::<Vec<_>>();
667 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
668
669 let msp = MultiSpan::from_spans(target_sp.clone());
670 let mut err = self
671 .dcx()
672 .create_err(errors::VariableIsNotBoundInAllPatterns { multispan: msp, name });
673 for sp in target_sp {
674 err.subdiagnostic(errors::PatternDoesntBindName { span: sp, name });
675 }
676 for sp in origin_sp {
677 err.subdiagnostic(errors::VariableNotInAllPatterns { span: sp });
678 }
679 if could_be_path {
680 let import_suggestions = self.lookup_import_candidates(
681 name,
682 Namespace::ValueNS,
683 &parent_scope,
684 &|res: Res| {
685 matches!(
686 res,
687 Res::Def(
688 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
689 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
690 | DefKind::Const
691 | DefKind::AssocConst,
692 _,
693 )
694 )
695 },
696 );
697
698 if import_suggestions.is_empty() {
699 let help_msg = format!(
700 "if you meant to match on a variant or a `const` item, consider \
701 making the path in the pattern qualified: `path::to::ModOrType::{name}`",
702 );
703 err.span_help(span, help_msg);
704 }
705 show_candidates(
706 self.tcx,
707 &mut err,
708 Some(span),
709 &import_suggestions,
710 Instead::No,
711 FoundUse::Yes,
712 DiagMode::Pattern,
713 vec![],
714 "",
715 );
716 }
717 err
718 }
719 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
720 self.dcx().create_err(errs::VariableBoundWithDifferentMode {
721 span,
722 first_binding_span,
723 variable_name,
724 })
725 }
726 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
727 .dcx()
728 .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
729 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
730 .dcx()
731 .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
732 ResolutionError::UndeclaredLabel { name, suggestion } => {
733 let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
734 {
735 Some((ident, true)) => (
737 (
738 Some(errs::LabelWithSimilarNameReachable(ident.span)),
739 Some(errs::TryUsingSimilarlyNamedLabel {
740 span,
741 ident_name: ident.name,
742 }),
743 ),
744 None,
745 ),
746 Some((ident, false)) => (
748 (None, None),
749 Some(errs::UnreachableLabelWithSimilarNameExists {
750 ident_span: ident.span,
751 }),
752 ),
753 None => ((None, None), None),
755 };
756 self.dcx().create_err(errs::UndeclaredLabel {
757 span,
758 name,
759 sub_reachable,
760 sub_reachable_suggestion,
761 sub_unreachable,
762 })
763 }
764 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
765 let (suggestion, mpart_suggestion) = if root {
767 (None, None)
768 } else {
769 let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
772
773 let mpart_suggestion = errs::SelfImportsOnlyAllowedWithinMultipartSuggestion {
776 multipart_start: span_with_rename.shrink_to_lo(),
777 multipart_end: span_with_rename.shrink_to_hi(),
778 };
779 (Some(suggestion), Some(mpart_suggestion))
780 };
781 self.dcx().create_err(errs::SelfImportsOnlyAllowedWithin {
782 span,
783 suggestion,
784 mpart_suggestion,
785 })
786 }
787 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
788 self.dcx().create_err(errs::SelfImportCanOnlyAppearOnceInTheList { span })
789 }
790 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
791 self.dcx().create_err(errs::SelfImportOnlyInImportListWithNonEmptyPrefix { span })
792 }
793 ResolutionError::FailedToResolve { segment, label, suggestion, module } => {
794 let mut err =
795 struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {label}");
796 err.span_label(span, label);
797
798 if let Some((suggestions, msg, applicability)) = suggestion {
799 if suggestions.is_empty() {
800 err.help(msg);
801 return err;
802 }
803 err.multipart_suggestion(msg, suggestions, applicability);
804 }
805 if let Some(ModuleOrUniformRoot::Module(module)) = module
806 && let Some(module) = module.opt_def_id()
807 && let Some(segment) = segment
808 {
809 self.find_cfg_stripped(&mut err, &segment, module);
810 }
811
812 err
813 }
814 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
815 self.dcx().create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
816 }
817 ResolutionError::AttemptToUseNonConstantValueInConstant {
818 ident,
819 suggestion,
820 current,
821 type_span,
822 } => {
823 let sp = self
832 .tcx
833 .sess
834 .source_map()
835 .span_extend_to_prev_str(ident.span, current, true, false);
836
837 let ((with, with_label), without) = match sp {
838 Some(sp) if !self.tcx.sess.source_map().is_multiline(sp) => {
839 let sp = sp
840 .with_lo(BytePos(sp.lo().0 - (current.len() as u32)))
841 .until(ident.span);
842 (
843 (Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
844 span: sp,
845 suggestion,
846 current,
847 type_span,
848 }), Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion {span})),
849 None,
850 )
851 }
852 _ => (
853 (None, None),
854 Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
855 ident_span: ident.span,
856 suggestion,
857 }),
858 ),
859 };
860
861 self.dcx().create_err(errs::AttemptToUseNonConstantValueInConstant {
862 span,
863 with,
864 with_label,
865 without,
866 })
867 }
868 ResolutionError::BindingShadowsSomethingUnacceptable {
869 shadowing_binding,
870 name,
871 participle,
872 article,
873 shadowed_binding,
874 shadowed_binding_span,
875 } => self.dcx().create_err(errs::BindingShadowsSomethingUnacceptable {
876 span,
877 shadowing_binding,
878 shadowed_binding,
879 article,
880 sub_suggestion: match (shadowing_binding, shadowed_binding) {
881 (
882 PatternSource::Match,
883 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
884 ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
885 _ => None,
886 },
887 shadowed_binding_span,
888 participle,
889 name,
890 }),
891 ResolutionError::ForwardDeclaredGenericParam(param, reason) => match reason {
892 ForwardGenericParamBanReason::Default => {
893 self.dcx().create_err(errs::ForwardDeclaredGenericParam { param, span })
894 }
895 ForwardGenericParamBanReason::ConstParamTy => self
896 .dcx()
897 .create_err(errs::ForwardDeclaredGenericInConstParamTy { param, span }),
898 },
899 ResolutionError::ParamInTyOfConstParam { name } => {
900 self.dcx().create_err(errs::ParamInTyOfConstParam { span, name })
901 }
902 ResolutionError::ParamInNonTrivialAnonConst { name, param_kind: is_type } => {
903 self.dcx().create_err(errs::ParamInNonTrivialAnonConst {
904 span,
905 name,
906 param_kind: is_type,
907 help: self
908 .tcx
909 .sess
910 .is_nightly_build()
911 .then_some(errs::ParamInNonTrivialAnonConstHelp),
912 })
913 }
914 ResolutionError::ParamInEnumDiscriminant { name, param_kind: is_type } => self
915 .dcx()
916 .create_err(errs::ParamInEnumDiscriminant { span, name, param_kind: is_type }),
917 ResolutionError::ForwardDeclaredSelf(reason) => match reason {
918 ForwardGenericParamBanReason::Default => {
919 self.dcx().create_err(errs::SelfInGenericParamDefault { span })
920 }
921 ForwardGenericParamBanReason::ConstParamTy => {
922 self.dcx().create_err(errs::SelfInConstGenericTy { span })
923 }
924 },
925 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
926 let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
927 match suggestion {
928 Some((ident, true)) => (
930 (
931 Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
932 Some(errs::UnreachableLabelSubSuggestion {
933 span,
934 ident_name: ident.name,
937 }),
938 ),
939 None,
940 ),
941 Some((ident, false)) => (
943 (None, None),
944 Some(errs::UnreachableLabelSubLabelUnreachable {
945 ident_span: ident.span,
946 }),
947 ),
948 None => ((None, None), None),
950 };
951 self.dcx().create_err(errs::UnreachableLabel {
952 span,
953 name,
954 definition_span,
955 sub_suggestion,
956 sub_suggestion_label,
957 sub_unreachable_label,
958 })
959 }
960 ResolutionError::TraitImplMismatch {
961 name,
962 kind,
963 code,
964 trait_item_span,
965 trait_path,
966 } => self
967 .dcx()
968 .create_err(errors::TraitImplMismatch {
969 span,
970 name,
971 kind,
972 trait_path,
973 trait_item_span,
974 })
975 .with_code(code),
976 ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
977 .dcx()
978 .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
979 ResolutionError::InvalidAsmSym => self.dcx().create_err(errs::InvalidAsmSym { span }),
980 ResolutionError::LowercaseSelf => self.dcx().create_err(errs::LowercaseSelf { span }),
981 ResolutionError::BindingInNeverPattern => {
982 self.dcx().create_err(errs::BindingInNeverPattern { span })
983 }
984 }
985 }
986
987 pub(crate) fn report_vis_error(
988 &mut self,
989 vis_resolution_error: VisResolutionError<'_>,
990 ) -> ErrorGuaranteed {
991 match vis_resolution_error {
992 VisResolutionError::Relative2018(span, path) => {
993 self.dcx().create_err(errs::Relative2018 {
994 span,
995 path_span: path.span,
996 path_str: pprust::path_to_string(path),
999 })
1000 }
1001 VisResolutionError::AncestorOnly(span) => {
1002 self.dcx().create_err(errs::AncestorOnly(span))
1003 }
1004 VisResolutionError::FailedToResolve(span, label, suggestion) => self.into_struct_error(
1005 span,
1006 ResolutionError::FailedToResolve { segment: None, label, suggestion, module: None },
1007 ),
1008 VisResolutionError::ExpectedFound(span, path_str, res) => {
1009 self.dcx().create_err(errs::ExpectedModuleFound { span, res, path_str })
1010 }
1011 VisResolutionError::Indeterminate(span) => {
1012 self.dcx().create_err(errs::Indeterminate(span))
1013 }
1014 VisResolutionError::ModuleOnly(span) => self.dcx().create_err(errs::ModuleOnly(span)),
1015 }
1016 .emit()
1017 }
1018
1019 fn early_lookup_typo_candidate(
1021 &mut self,
1022 scope_set: ScopeSet<'ra>,
1023 parent_scope: &ParentScope<'ra>,
1024 ident: Ident,
1025 filter_fn: &impl Fn(Res) -> bool,
1026 ) -> Option<TypoSuggestion> {
1027 let mut suggestions = Vec::new();
1028 let ctxt = ident.span.ctxt();
1029 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
1030 match scope {
1031 Scope::DeriveHelpers(expn_id) => {
1032 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1033 if filter_fn(res) {
1034 suggestions.extend(
1035 this.helper_attrs
1036 .get(&expn_id)
1037 .into_iter()
1038 .flatten()
1039 .map(|(ident, _)| TypoSuggestion::typo_from_ident(*ident, res)),
1040 );
1041 }
1042 }
1043 Scope::DeriveHelpersCompat => {
1044 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1045 if filter_fn(res) {
1046 for derive in parent_scope.derives {
1047 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1048 let Ok((Some(ext), _)) = this.resolve_macro_path(
1049 derive,
1050 Some(MacroKind::Derive),
1051 parent_scope,
1052 false,
1053 false,
1054 None,
1055 ) else {
1056 continue;
1057 };
1058 suggestions.extend(
1059 ext.helper_attrs
1060 .iter()
1061 .map(|name| TypoSuggestion::typo_from_name(*name, res)),
1062 );
1063 }
1064 }
1065 }
1066 Scope::MacroRules(macro_rules_scope) => {
1067 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1068 let res = macro_rules_binding.binding.res();
1069 if filter_fn(res) {
1070 suggestions.push(TypoSuggestion::typo_from_ident(
1071 macro_rules_binding.ident,
1072 res,
1073 ))
1074 }
1075 }
1076 }
1077 Scope::CrateRoot => {
1078 let root_ident = Ident::new(kw::PathRoot, ident.span);
1079 let root_module = this.resolve_crate_root(root_ident);
1080 this.add_module_candidates(root_module, &mut suggestions, filter_fn, None);
1081 }
1082 Scope::Module(module, _) => {
1083 this.add_module_candidates(module, &mut suggestions, filter_fn, None);
1084 }
1085 Scope::MacroUsePrelude => {
1086 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1087 |(name, binding)| {
1088 let res = binding.res();
1089 filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1090 },
1091 ));
1092 }
1093 Scope::BuiltinAttrs => {
1094 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1095 if filter_fn(res) {
1096 suggestions.extend(
1097 BUILTIN_ATTRIBUTES
1098 .iter()
1099 .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1100 );
1101 }
1102 }
1103 Scope::ExternPrelude => {
1104 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1105 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1106 filter_fn(res).then_some(TypoSuggestion::typo_from_ident(*ident, res))
1107 }));
1108 }
1109 Scope::ToolPrelude => {
1110 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1111 suggestions.extend(
1112 this.registered_tools
1113 .iter()
1114 .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
1115 );
1116 }
1117 Scope::StdLibPrelude => {
1118 if let Some(prelude) = this.prelude {
1119 let mut tmp_suggestions = Vec::new();
1120 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1121 suggestions.extend(
1122 tmp_suggestions
1123 .into_iter()
1124 .filter(|s| use_prelude.into() || this.is_builtin_macro(s.res)),
1125 );
1126 }
1127 }
1128 Scope::BuiltinTypes => {
1129 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1130 let res = Res::PrimTy(*prim_ty);
1131 filter_fn(res)
1132 .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1133 }))
1134 }
1135 }
1136
1137 None::<()>
1138 });
1139
1140 suggestions.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
1142
1143 match find_best_match_for_name(
1144 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1145 ident.name,
1146 None,
1147 ) {
1148 Some(found) if found != ident.name => {
1149 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1150 }
1151 _ => None,
1152 }
1153 }
1154
1155 fn lookup_import_candidates_from_module<FilterFn>(
1156 &mut self,
1157 lookup_ident: Ident,
1158 namespace: Namespace,
1159 parent_scope: &ParentScope<'ra>,
1160 start_module: Module<'ra>,
1161 crate_path: ThinVec<ast::PathSegment>,
1162 filter_fn: FilterFn,
1163 ) -> Vec<ImportSuggestion>
1164 where
1165 FilterFn: Fn(Res) -> bool,
1166 {
1167 let mut candidates = Vec::new();
1168 let mut seen_modules = FxHashSet::default();
1169 let start_did = start_module.def_id();
1170 let mut worklist = vec![(
1171 start_module,
1172 ThinVec::<ast::PathSegment>::new(),
1173 true,
1174 start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
1175 )];
1176 let mut worklist_via_import = vec![];
1177
1178 while let Some((in_module, path_segments, accessible, doc_visible)) = match worklist.pop() {
1179 None => worklist_via_import.pop(),
1180 Some(x) => Some(x),
1181 } {
1182 let in_module_is_extern = !in_module.def_id().is_local();
1183 in_module.for_each_child(self, |this, ident, ns, name_binding| {
1184 if !name_binding.is_importable()
1186 || name_binding.is_assoc_const_or_fn()
1188 && !this.tcx.features().import_trait_associated_functions()
1189 {
1190 return;
1191 }
1192
1193 if ident.name == kw::Underscore {
1194 return;
1195 }
1196
1197 let child_accessible =
1198 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1199
1200 if in_module_is_extern && !child_accessible {
1202 return;
1203 }
1204
1205 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1206
1207 if via_import && name_binding.is_possibly_imported_variant() {
1213 return;
1214 }
1215
1216 if let NameBindingKind::Import { binding, .. } = name_binding.kind
1218 && this.is_accessible_from(binding.vis, parent_scope.module)
1219 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1220 {
1221 return;
1222 }
1223
1224 let res = name_binding.res();
1225 let did = match res {
1226 Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1227 _ => res.opt_def_id(),
1228 };
1229 let child_doc_visible = doc_visible
1230 && did.is_none_or(|did| did.is_local() || !this.tcx.is_doc_hidden(did));
1231
1232 if ident.name == lookup_ident.name
1236 && ns == namespace
1237 && in_module != parent_scope.module
1238 && !ident.span.normalize_to_macros_2_0().from_expansion()
1239 && filter_fn(res)
1240 {
1241 let mut segms = if lookup_ident.span.at_least_rust_2018() {
1243 crate_path.clone()
1246 } else {
1247 ThinVec::new()
1248 };
1249 segms.append(&mut path_segments.clone());
1250
1251 segms.push(ast::PathSegment::from_ident(ident));
1252 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1253
1254 if child_accessible
1255 && let Some(idx) = candidates
1257 .iter()
1258 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1259 {
1260 candidates.remove(idx);
1261 }
1262
1263 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1264 let note = if let Some(did) = did {
1267 let requires_note = !did.is_local()
1268 && this.tcx.get_attrs(did, sym::rustc_diagnostic_item).any(
1269 |attr| {
1270 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1271 .map(|x| Some(x))
1272 .contains(&attr.value_str())
1273 },
1274 );
1275
1276 requires_note.then(|| {
1277 format!(
1278 "'{}' is included in the prelude starting in Edition 2021",
1279 path_names_to_string(&path)
1280 )
1281 })
1282 } else {
1283 None
1284 };
1285
1286 candidates.push(ImportSuggestion {
1287 did,
1288 descr: res.descr(),
1289 path,
1290 accessible: child_accessible,
1291 doc_visible: child_doc_visible,
1292 note,
1293 via_import,
1294 });
1295 }
1296 }
1297
1298 if let Some(module) = name_binding.module() {
1300 let mut path_segments = path_segments.clone();
1302 path_segments.push(ast::PathSegment::from_ident(ident));
1303
1304 let alias_import = if let NameBindingKind::Import { import, .. } =
1305 name_binding.kind
1306 && let ImportKind::ExternCrate { source: Some(_), .. } = import.kind
1307 && import.parent_scope.expansion == parent_scope.expansion
1308 {
1309 true
1310 } else {
1311 false
1312 };
1313
1314 let is_extern_crate_that_also_appears_in_prelude =
1315 name_binding.is_extern_crate() && lookup_ident.span.at_least_rust_2018();
1316
1317 if !is_extern_crate_that_also_appears_in_prelude || alias_import {
1318 if seen_modules.insert(module.def_id()) {
1320 if via_import { &mut worklist_via_import } else { &mut worklist }
1321 .push((module, path_segments, child_accessible, child_doc_visible));
1322 }
1323 }
1324 }
1325 })
1326 }
1327
1328 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1330 candidates.retain(|x| x.accessible)
1331 }
1332
1333 candidates
1334 }
1335
1336 pub(crate) fn lookup_import_candidates<FilterFn>(
1344 &mut self,
1345 lookup_ident: Ident,
1346 namespace: Namespace,
1347 parent_scope: &ParentScope<'ra>,
1348 filter_fn: FilterFn,
1349 ) -> Vec<ImportSuggestion>
1350 where
1351 FilterFn: Fn(Res) -> bool,
1352 {
1353 let crate_path = thin_vec![ast::PathSegment::from_ident(Ident::with_dummy_span(kw::Crate))];
1354 let mut suggestions = self.lookup_import_candidates_from_module(
1355 lookup_ident,
1356 namespace,
1357 parent_scope,
1358 self.graph_root,
1359 crate_path,
1360 &filter_fn,
1361 );
1362
1363 if lookup_ident.span.at_least_rust_2018() {
1364 for ident in self.extern_prelude.clone().into_keys() {
1365 if ident.span.from_expansion() {
1366 continue;
1372 }
1373 let Some(crate_id) = self.crate_loader(|c| c.maybe_process_path_extern(ident.name))
1374 else {
1375 continue;
1376 };
1377
1378 let crate_def_id = crate_id.as_def_id();
1379 let crate_root = self.expect_module(crate_def_id);
1380
1381 let needs_disambiguation =
1385 self.resolutions(parent_scope.module).borrow().iter().any(
1386 |(key, name_resolution)| {
1387 if key.ns == TypeNS
1388 && key.ident == ident
1389 && let Some(binding) = name_resolution.borrow().binding
1390 {
1391 match binding.res() {
1392 Res::Def(_, def_id) => def_id != crate_def_id,
1395 Res::PrimTy(_) => true,
1396 _ => false,
1397 }
1398 } else {
1399 false
1400 }
1401 },
1402 );
1403 let mut crate_path = ThinVec::new();
1404 if needs_disambiguation {
1405 crate_path.push(ast::PathSegment::path_root(rustc_span::DUMMY_SP));
1406 }
1407 crate_path.push(ast::PathSegment::from_ident(ident));
1408
1409 suggestions.extend(self.lookup_import_candidates_from_module(
1410 lookup_ident,
1411 namespace,
1412 parent_scope,
1413 crate_root,
1414 crate_path,
1415 &filter_fn,
1416 ));
1417 }
1418 }
1419
1420 suggestions
1421 }
1422
1423 pub(crate) fn unresolved_macro_suggestions(
1424 &mut self,
1425 err: &mut Diag<'_>,
1426 macro_kind: MacroKind,
1427 parent_scope: &ParentScope<'ra>,
1428 ident: Ident,
1429 krate: &Crate,
1430 ) {
1431 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1432 let suggestion = self.early_lookup_typo_candidate(
1433 ScopeSet::Macro(macro_kind),
1434 parent_scope,
1435 ident,
1436 is_expected,
1437 );
1438 self.add_typo_suggestion(err, suggestion, ident.span);
1439
1440 let import_suggestions =
1441 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1442 let (span, found_use) = match parent_scope.module.nearest_parent_mod().as_local() {
1443 Some(def_id) => UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id]),
1444 None => (None, FoundUse::No),
1445 };
1446 show_candidates(
1447 self.tcx,
1448 err,
1449 span,
1450 &import_suggestions,
1451 Instead::No,
1452 found_use,
1453 DiagMode::Normal,
1454 vec![],
1455 "",
1456 );
1457
1458 if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1459 let label_span = ident.span.shrink_to_hi();
1460 let mut spans = MultiSpan::from_span(label_span);
1461 spans.push_span_label(label_span, "put a macro name here");
1462 err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1463 return;
1464 }
1465
1466 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1467 err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1468 return;
1469 }
1470
1471 let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1472 if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1473 });
1474
1475 if let Some((def_id, unused_ident)) = unused_macro {
1476 let scope = self.local_macro_def_scopes[&def_id];
1477 let parent_nearest = parent_scope.module.nearest_parent_mod();
1478 if Some(parent_nearest) == scope.opt_def_id() {
1479 match macro_kind {
1480 MacroKind::Bang => {
1481 err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1482 err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1483 }
1484 MacroKind::Attr => {
1485 err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1486 }
1487 MacroKind::Derive => {
1488 err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1489 }
1490 }
1491
1492 return;
1493 }
1494 }
1495
1496 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1497 err.subdiagnostic(AddedMacroUse);
1498 return;
1499 }
1500
1501 if ident.name == kw::Default
1502 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1503 {
1504 let span = self.def_span(def_id);
1505 let source_map = self.tcx.sess.source_map();
1506 let head_span = source_map.guess_head_span(span);
1507 err.subdiagnostic(ConsiderAddingADerive {
1508 span: head_span.shrink_to_lo(),
1509 suggestion: "#[derive(Default)]\n".to_string(),
1510 });
1511 }
1512 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1513 let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1514 ident,
1515 ScopeSet::All(ns),
1516 parent_scope,
1517 None,
1518 false,
1519 None,
1520 None,
1521 ) else {
1522 continue;
1523 };
1524
1525 let desc = match binding.res() {
1526 Res::Def(DefKind::Macro(MacroKind::Bang), _) => "a function-like macro".to_string(),
1527 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1528 format!("an attribute: `#[{ident}]`")
1529 }
1530 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1531 format!("a derive macro: `#[derive({ident})]`")
1532 }
1533 Res::ToolMod => {
1534 continue;
1536 }
1537 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1538 "only a trait, without a derive macro".to_string()
1539 }
1540 res => format!(
1541 "{} {}, not {} {}",
1542 res.article(),
1543 res.descr(),
1544 macro_kind.article(),
1545 macro_kind.descr_expected(),
1546 ),
1547 };
1548 if let crate::NameBindingKind::Import { import, .. } = binding.kind
1549 && !import.span.is_dummy()
1550 {
1551 let note = errors::IdentImporterHereButItIsDesc {
1552 span: import.span,
1553 imported_ident: ident,
1554 imported_ident_desc: &desc,
1555 };
1556 err.subdiagnostic(note);
1557 self.record_use(ident, binding, Used::Other);
1560 return;
1561 }
1562 let note = errors::IdentInScopeButItIsDesc {
1563 imported_ident: ident,
1564 imported_ident_desc: &desc,
1565 };
1566 err.subdiagnostic(note);
1567 return;
1568 }
1569 }
1570
1571 pub(crate) fn add_typo_suggestion(
1572 &self,
1573 err: &mut Diag<'_>,
1574 suggestion: Option<TypoSuggestion>,
1575 span: Span,
1576 ) -> bool {
1577 let suggestion = match suggestion {
1578 None => return false,
1579 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1581 Some(suggestion) => suggestion,
1582 };
1583
1584 let mut did_label_def_span = false;
1585
1586 if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1587 if span.overlaps(def_span) {
1588 return false;
1607 }
1608 let span = self.tcx.sess.source_map().guess_head_span(def_span);
1609 let candidate_descr = suggestion.res.descr();
1610 let candidate = suggestion.candidate;
1611 let label = match suggestion.target {
1612 SuggestionTarget::SimilarlyNamed => {
1613 errors::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
1614 }
1615 SuggestionTarget::SingleItem => {
1616 errors::DefinedHere::SingleItem { span, candidate_descr, candidate }
1617 }
1618 };
1619 did_label_def_span = true;
1620 err.subdiagnostic(label);
1621 }
1622
1623 let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
1624 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1625 && let Some(span) = suggestion.span
1626 && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
1627 && snippet == candidate
1628 {
1629 let candidate = suggestion.candidate;
1630 let msg = format!(
1633 "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
1634 );
1635 if !did_label_def_span {
1636 err.span_label(span, format!("`{candidate}` defined here"));
1637 }
1638 (span, msg, snippet)
1639 } else {
1640 let msg = match suggestion.target {
1641 SuggestionTarget::SimilarlyNamed => format!(
1642 "{} {} with a similar name exists",
1643 suggestion.res.article(),
1644 suggestion.res.descr()
1645 ),
1646 SuggestionTarget::SingleItem => {
1647 format!("maybe you meant this {}", suggestion.res.descr())
1648 }
1649 };
1650 (span, msg, suggestion.candidate.to_ident_string())
1651 };
1652 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1653 true
1654 }
1655
1656 fn binding_description(&self, b: NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1657 let res = b.res();
1658 if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
1659 let add_built_in =
1661 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1662 let (built_in, from) = if from_prelude {
1663 ("", " from prelude")
1664 } else if b.is_extern_crate()
1665 && !b.is_import()
1666 && self.tcx.sess.opts.externs.get(ident.as_str()).is_some()
1667 {
1668 ("", " passed with `--extern`")
1669 } else if add_built_in {
1670 (" built-in", "")
1671 } else {
1672 ("", "")
1673 };
1674
1675 let a = if built_in.is_empty() { res.article() } else { "a" };
1676 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1677 } else {
1678 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1679 format!("the {thing} {introduced} here", thing = res.descr())
1680 }
1681 }
1682
1683 fn ambiguity_diagnostics(&self, ambiguity_error: &AmbiguityError<'_>) -> AmbiguityErrorDiag {
1684 let AmbiguityError { kind, ident, b1, b2, misc1, misc2, .. } = *ambiguity_error;
1685 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1686 (b2, b1, misc2, misc1, true)
1688 } else {
1689 (b1, b2, misc1, misc2, false)
1690 };
1691 let could_refer_to = |b: NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1692 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1693 let note_msg = format!("`{ident}` could{also} refer to {what}");
1694
1695 let thing = b.res().descr();
1696 let mut help_msgs = Vec::new();
1697 if b.is_glob_import()
1698 && (kind == AmbiguityKind::GlobVsGlob
1699 || kind == AmbiguityKind::GlobVsExpanded
1700 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1701 {
1702 help_msgs.push(format!(
1703 "consider adding an explicit import of `{ident}` to disambiguate"
1704 ))
1705 }
1706 if b.is_extern_crate() && ident.span.at_least_rust_2018() {
1707 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1708 }
1709 match misc {
1710 AmbiguityErrorMisc::SuggestCrate => help_msgs
1711 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously")),
1712 AmbiguityErrorMisc::SuggestSelf => help_msgs
1713 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously")),
1714 AmbiguityErrorMisc::FromPrelude | AmbiguityErrorMisc::None => {}
1715 }
1716
1717 (
1718 b.span,
1719 note_msg,
1720 help_msgs
1721 .iter()
1722 .enumerate()
1723 .map(|(i, help_msg)| {
1724 let or = if i == 0 { "" } else { "or " };
1725 format!("{or}{help_msg}")
1726 })
1727 .collect::<Vec<_>>(),
1728 )
1729 };
1730 let (b1_span, b1_note_msg, b1_help_msgs) = could_refer_to(b1, misc1, "");
1731 let (b2_span, b2_note_msg, b2_help_msgs) = could_refer_to(b2, misc2, " also");
1732
1733 AmbiguityErrorDiag {
1734 msg: format!("`{ident}` is ambiguous"),
1735 span: ident.span,
1736 label_span: ident.span,
1737 label_msg: "ambiguous name".to_string(),
1738 note_msg: format!("ambiguous because of {}", kind.descr()),
1739 b1_span,
1740 b1_note_msg,
1741 b1_help_msgs,
1742 b2_span,
1743 b2_note_msg,
1744 b2_help_msgs,
1745 }
1746 }
1747
1748 fn ctor_fields_span(&self, binding: NameBinding<'_>) -> Option<Span> {
1751 let NameBindingKind::Res(Res::Def(
1752 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
1753 ctor_def_id,
1754 )) = binding.kind
1755 else {
1756 return None;
1757 };
1758
1759 let def_id = self.tcx.parent(ctor_def_id);
1760 self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) }
1762
1763 fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
1764 let PrivacyError { ident, binding, outermost_res, parent_scope, single_nested, dedup_span } =
1765 *privacy_error;
1766
1767 let res = binding.res();
1768 let ctor_fields_span = self.ctor_fields_span(binding);
1769 let plain_descr = res.descr().to_string();
1770 let nonimport_descr =
1771 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1772 let import_descr = nonimport_descr.clone() + " import";
1773 let get_descr =
1774 |b: NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1775
1776 let ident_descr = get_descr(binding);
1778 let mut err =
1779 self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
1780
1781 let mut not_publicly_reexported = false;
1782 if let Some((this_res, outer_ident)) = outermost_res {
1783 let import_suggestions = self.lookup_import_candidates(
1784 outer_ident,
1785 this_res.ns().unwrap_or(Namespace::TypeNS),
1786 &parent_scope,
1787 &|res: Res| res == this_res,
1788 );
1789 let point_to_def = !show_candidates(
1790 self.tcx,
1791 &mut err,
1792 Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
1793 &import_suggestions,
1794 Instead::Yes,
1795 FoundUse::Yes,
1796 DiagMode::Import { append: single_nested },
1797 vec![],
1798 "",
1799 );
1800 if point_to_def && ident.span != outer_ident.span {
1802 not_publicly_reexported = true;
1803 let label = errors::OuterIdentIsNotPubliclyReexported {
1804 span: outer_ident.span,
1805 outer_ident_descr: this_res.descr(),
1806 outer_ident,
1807 };
1808 err.subdiagnostic(label);
1809 }
1810 }
1811
1812 let mut non_exhaustive = None;
1813 if let Some(def_id) = res.opt_def_id()
1817 && !def_id.is_local()
1818 && let Some(attr) = self.tcx.get_attr(def_id, sym::non_exhaustive)
1819 {
1820 non_exhaustive = Some(attr.span());
1821 } else if let Some(span) = ctor_fields_span {
1822 let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
1823 err.subdiagnostic(label);
1824 if let Res::Def(_, d) = res
1825 && let Some(fields) = self.field_visibility_spans.get(&d)
1826 {
1827 let spans = fields.iter().map(|span| *span).collect();
1828 let sugg =
1829 errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
1830 err.subdiagnostic(sugg);
1831 }
1832 }
1833
1834 let mut sugg_paths = vec![];
1835 if let Some(mut def_id) = res.opt_def_id() {
1836 let mut path = vec![def_id];
1838 while let Some(parent) = self.tcx.opt_parent(def_id) {
1839 def_id = parent;
1840 if !def_id.is_top_level_module() {
1841 path.push(def_id);
1842 } else {
1843 break;
1844 }
1845 }
1846 let path_names: Option<Vec<String>> = path
1848 .iter()
1849 .rev()
1850 .map(|def_id| {
1851 self.tcx.opt_item_name(*def_id).map(|n| {
1852 if def_id.is_top_level_module() {
1853 "crate".to_string()
1854 } else {
1855 n.to_string()
1856 }
1857 })
1858 })
1859 .collect();
1860 if let Some(def_id) = path.get(0)
1861 && let Some(path) = path_names
1862 {
1863 if let Some(def_id) = def_id.as_local() {
1864 if self.effective_visibilities.is_directly_public(def_id) {
1865 sugg_paths.push((path, false));
1866 }
1867 } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
1868 {
1869 sugg_paths.push((path, false));
1870 }
1871 }
1872 }
1873
1874 let first_binding = binding;
1876 let mut next_binding = Some(binding);
1877 let mut next_ident = ident;
1878 let mut path = vec![];
1879 while let Some(binding) = next_binding {
1880 let name = next_ident;
1881 next_binding = match binding.kind {
1882 _ if res == Res::Err => None,
1883 NameBindingKind::Import { binding, import, .. } => match import.kind {
1884 _ if binding.span.is_dummy() => None,
1885 ImportKind::Single { source, .. } => {
1886 next_ident = source;
1887 Some(binding)
1888 }
1889 ImportKind::Glob { .. }
1890 | ImportKind::MacroUse { .. }
1891 | ImportKind::MacroExport => Some(binding),
1892 ImportKind::ExternCrate { .. } => None,
1893 },
1894 _ => None,
1895 };
1896
1897 match binding.kind {
1898 NameBindingKind::Import { import, .. } => {
1899 for segment in import.module_path.iter().skip(1) {
1900 path.push(segment.ident.to_string());
1901 }
1902 sugg_paths.push((
1903 path.iter()
1904 .cloned()
1905 .chain(vec![ident.to_string()].into_iter())
1906 .collect::<Vec<_>>(),
1907 true, ));
1909 }
1910 NameBindingKind::Res(_) | NameBindingKind::Module(_) => {}
1911 }
1912 let first = binding == first_binding;
1913 let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
1914 let mut note_span = MultiSpan::from_span(def_span);
1915 if !first && binding.vis.is_public() {
1916 let desc = match binding.kind {
1917 NameBindingKind::Import { .. } => "re-export",
1918 _ => "directly",
1919 };
1920 note_span.push_span_label(def_span, format!("you could import this {desc}"));
1921 }
1922 if next_binding.is_none()
1925 && let Some(span) = non_exhaustive
1926 {
1927 note_span.push_span_label(
1928 span,
1929 "cannot be constructed because it is `#[non_exhaustive]`",
1930 );
1931 }
1932 let note = errors::NoteAndRefersToTheItemDefinedHere {
1933 span: note_span,
1934 binding_descr: get_descr(binding),
1935 binding_name: name,
1936 first,
1937 dots: next_binding.is_some(),
1938 };
1939 err.subdiagnostic(note);
1940 }
1941 sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0] == "core", *reexport));
1943 for (sugg, reexport) in sugg_paths {
1944 if not_publicly_reexported {
1945 break;
1946 }
1947 if sugg.len() <= 1 {
1948 continue;
1951 }
1952 let path = sugg.join("::");
1953 let sugg = if reexport {
1954 errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
1955 } else {
1956 errors::ImportIdent::Directly { span: dedup_span, ident, path }
1957 };
1958 err.subdiagnostic(sugg);
1959 break;
1960 }
1961
1962 err.emit();
1963 }
1964
1965 pub(crate) fn find_similarly_named_module_or_crate(
1966 &mut self,
1967 ident: Symbol,
1968 current_module: Module<'ra>,
1969 ) -> Option<Symbol> {
1970 let mut candidates = self
1971 .extern_prelude
1972 .keys()
1973 .map(|ident| ident.name)
1974 .chain(
1975 self.module_map
1976 .iter()
1977 .filter(|(_, module)| {
1978 current_module.is_ancestor_of(**module) && current_module != **module
1979 })
1980 .flat_map(|(_, module)| module.kind.name()),
1981 )
1982 .filter(|c| !c.to_string().is_empty())
1983 .collect::<Vec<_>>();
1984 candidates.sort();
1985 candidates.dedup();
1986 find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
1987 }
1988
1989 pub(crate) fn report_path_resolution_error(
1990 &mut self,
1991 path: &[Segment],
1992 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1994 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1995 ignore_binding: Option<NameBinding<'ra>>,
1996 ignore_import: Option<Import<'ra>>,
1997 module: Option<ModuleOrUniformRoot<'ra>>,
1998 failed_segment_idx: usize,
1999 ident: Ident,
2000 ) -> (String, Option<Suggestion>) {
2001 let is_last = failed_segment_idx == path.len() - 1;
2002 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2003 let module_res = match module {
2004 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2005 _ => None,
2006 };
2007 if module_res == self.graph_root.res() {
2008 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
2009 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2010 candidates
2011 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2012 if let Some(candidate) = candidates.get(0) {
2013 let path = {
2014 let len = candidate.path.segments.len();
2016 let start_index = (0..=failed_segment_idx.min(len - 1))
2017 .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2018 .unwrap_or_default();
2019 let segments =
2020 (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2021 Path { segments, span: Span::default(), tokens: None }
2022 };
2023 (
2024 String::from("unresolved import"),
2025 Some((
2026 vec![(ident.span, pprust::path_to_string(&path))],
2027 String::from("a similar path exists"),
2028 Applicability::MaybeIncorrect,
2029 )),
2030 )
2031 } else if ident.name == sym::core {
2032 (
2033 format!("you might be missing crate `{ident}`"),
2034 Some((
2035 vec![(ident.span, "std".to_string())],
2036 "try using `std` instead of `core`".to_string(),
2037 Applicability::MaybeIncorrect,
2038 )),
2039 )
2040 } else if ident.name == kw::Underscore {
2041 (format!("`_` is not a valid crate or module name"), None)
2042 } else if self.tcx.sess.is_rust_2015() {
2043 (
2044 format!("use of unresolved module or unlinked crate `{ident}`"),
2045 Some((
2046 vec![(
2047 self.current_crate_outer_attr_insert_span,
2048 format!("extern crate {ident};\n"),
2049 )],
2050 if was_invoked_from_cargo() {
2051 format!(
2052 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2053 to add it to your `Cargo.toml` and import it in your code",
2054 )
2055 } else {
2056 format!(
2057 "you might be missing a crate named `{ident}`, add it to your \
2058 project and import it in your code",
2059 )
2060 },
2061 Applicability::MaybeIncorrect,
2062 )),
2063 )
2064 } else {
2065 (format!("could not find `{ident}` in the crate root"), None)
2066 }
2067 } else if failed_segment_idx > 0 {
2068 let parent = path[failed_segment_idx - 1].ident.name;
2069 let parent = match parent {
2070 kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2073 "the list of imported crates".to_owned()
2074 }
2075 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2076 _ => format!("`{parent}`"),
2077 };
2078
2079 let mut msg = format!("could not find `{ident}` in {parent}");
2080 if ns == TypeNS || ns == ValueNS {
2081 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2082 let binding = if let Some(module) = module {
2083 self.resolve_ident_in_module(
2084 module,
2085 ident,
2086 ns_to_try,
2087 parent_scope,
2088 None,
2089 ignore_binding,
2090 ignore_import,
2091 )
2092 .ok()
2093 } else if let Some(ribs) = ribs
2094 && let Some(TypeNS | ValueNS) = opt_ns
2095 {
2096 assert!(ignore_import.is_none());
2097 match self.resolve_ident_in_lexical_scope(
2098 ident,
2099 ns_to_try,
2100 parent_scope,
2101 None,
2102 &ribs[ns_to_try],
2103 ignore_binding,
2104 ) {
2105 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
2107 _ => None,
2108 }
2109 } else {
2110 self.early_resolve_ident_in_lexical_scope(
2111 ident,
2112 ScopeSet::All(ns_to_try),
2113 parent_scope,
2114 None,
2115 false,
2116 ignore_binding,
2117 ignore_import,
2118 )
2119 .ok()
2120 };
2121 if let Some(binding) = binding {
2122 let mut found = |what| {
2123 msg = format!(
2124 "expected {}, found {} `{}` in {}",
2125 ns.descr(),
2126 what,
2127 ident,
2128 parent
2129 )
2130 };
2131 if binding.module().is_some() {
2132 found("module")
2133 } else {
2134 match binding.res() {
2135 Res::Def(kind, id) => found(kind.descr(id)),
2138 _ => found(ns_to_try.descr()),
2139 }
2140 }
2141 };
2142 }
2143 (msg, None)
2144 } else if ident.name == kw::SelfUpper {
2145 if opt_ns.is_none() {
2149 ("`Self` cannot be used in imports".to_string(), None)
2150 } else {
2151 (
2152 "`Self` is only available in impls, traits, and type definitions".to_string(),
2153 None,
2154 )
2155 }
2156 } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2157 let binding = if let Some(ribs) = ribs {
2159 assert!(ignore_import.is_none());
2160 self.resolve_ident_in_lexical_scope(
2161 ident,
2162 ValueNS,
2163 parent_scope,
2164 None,
2165 &ribs[ValueNS],
2166 ignore_binding,
2167 )
2168 } else {
2169 None
2170 };
2171 let match_span = match binding {
2172 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
2181 Some(*self.pat_span_map.get(&id).unwrap())
2182 }
2183 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
2195 _ => None,
2196 };
2197 let suggestion = match_span.map(|span| {
2198 (
2199 vec![(span, String::from(""))],
2200 format!("`{ident}` is defined here, but is not a type"),
2201 Applicability::MaybeIncorrect,
2202 )
2203 });
2204
2205 (format!("use of undeclared type `{ident}`"), suggestion)
2206 } else {
2207 let mut suggestion = None;
2208 if ident.name == sym::alloc {
2209 suggestion = Some((
2210 vec![],
2211 String::from("add `extern crate alloc` to use the `alloc` crate"),
2212 Applicability::MaybeIncorrect,
2213 ))
2214 }
2215
2216 suggestion = suggestion.or_else(|| {
2217 self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2218 |sugg| {
2219 (
2220 vec![(ident.span, sugg.to_string())],
2221 String::from("there is a crate or module with a similar name"),
2222 Applicability::MaybeIncorrect,
2223 )
2224 },
2225 )
2226 });
2227 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
2228 ident,
2229 ScopeSet::All(ValueNS),
2230 parent_scope,
2231 None,
2232 false,
2233 ignore_binding,
2234 ignore_import,
2235 ) {
2236 let descr = binding.res().descr();
2237 (format!("{descr} `{ident}` is not a crate or module"), suggestion)
2238 } else {
2239 let suggestion = if suggestion.is_some() {
2240 suggestion
2241 } else if was_invoked_from_cargo() {
2242 Some((
2243 vec![],
2244 format!(
2245 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2246 to add it to your `Cargo.toml`",
2247 ),
2248 Applicability::MaybeIncorrect,
2249 ))
2250 } else {
2251 Some((
2252 vec![],
2253 format!("you might be missing a crate named `{ident}`",),
2254 Applicability::MaybeIncorrect,
2255 ))
2256 };
2257 (format!("use of unresolved module or unlinked crate `{ident}`"), suggestion)
2258 }
2259 }
2260 }
2261
2262 #[instrument(level = "debug", skip(self, parent_scope))]
2264 pub(crate) fn make_path_suggestion(
2265 &mut self,
2266 mut path: Vec<Segment>,
2267 parent_scope: &ParentScope<'ra>,
2268 ) -> Option<(Vec<Segment>, Option<String>)> {
2269 match path[..] {
2270 [first, second, ..]
2273 if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2274 [first, ..]
2276 if first.ident.span.at_least_rust_2018()
2277 && !first.ident.is_path_segment_keyword() =>
2278 {
2279 path.insert(0, Segment::from_ident(Ident::dummy()));
2281 }
2282 _ => return None,
2283 }
2284
2285 self.make_missing_self_suggestion(path.clone(), parent_scope)
2286 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2287 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2288 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2289 }
2290
2291 #[instrument(level = "debug", skip(self, parent_scope))]
2299 fn make_missing_self_suggestion(
2300 &mut self,
2301 mut path: Vec<Segment>,
2302 parent_scope: &ParentScope<'ra>,
2303 ) -> Option<(Vec<Segment>, Option<String>)> {
2304 path[0].ident.name = kw::SelfLower;
2306 let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2307 debug!(?path, ?result);
2308 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2309 }
2310
2311 #[instrument(level = "debug", skip(self, parent_scope))]
2319 fn make_missing_crate_suggestion(
2320 &mut self,
2321 mut path: Vec<Segment>,
2322 parent_scope: &ParentScope<'ra>,
2323 ) -> Option<(Vec<Segment>, Option<String>)> {
2324 path[0].ident.name = kw::Crate;
2326 let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2327 debug!(?path, ?result);
2328 if let PathResult::Module(..) = result {
2329 Some((
2330 path,
2331 Some(
2332 "`use` statements changed in Rust 2018; read more at \
2333 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2334 clarity.html>"
2335 .to_string(),
2336 ),
2337 ))
2338 } else {
2339 None
2340 }
2341 }
2342
2343 #[instrument(level = "debug", skip(self, parent_scope))]
2351 fn make_missing_super_suggestion(
2352 &mut self,
2353 mut path: Vec<Segment>,
2354 parent_scope: &ParentScope<'ra>,
2355 ) -> Option<(Vec<Segment>, Option<String>)> {
2356 path[0].ident.name = kw::Super;
2358 let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2359 debug!(?path, ?result);
2360 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2361 }
2362
2363 #[instrument(level = "debug", skip(self, parent_scope))]
2374 fn make_external_crate_suggestion(
2375 &mut self,
2376 mut path: Vec<Segment>,
2377 parent_scope: &ParentScope<'ra>,
2378 ) -> Option<(Vec<Segment>, Option<String>)> {
2379 if path[1].ident.span.is_rust_2015() {
2380 return None;
2381 }
2382
2383 let mut extern_crate_names =
2387 self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2388 extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
2389
2390 for name in extern_crate_names.into_iter() {
2391 path[0].ident.name = name;
2393 let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2394 debug!(?path, ?name, ?result);
2395 if let PathResult::Module(..) = result {
2396 return Some((path, None));
2397 }
2398 }
2399
2400 None
2401 }
2402
2403 pub(crate) fn check_for_module_export_macro(
2416 &mut self,
2417 import: Import<'ra>,
2418 module: ModuleOrUniformRoot<'ra>,
2419 ident: Ident,
2420 ) -> Option<(Option<Suggestion>, Option<String>)> {
2421 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2422 return None;
2423 };
2424
2425 while let Some(parent) = crate_module.parent {
2426 crate_module = parent;
2427 }
2428
2429 if module == ModuleOrUniformRoot::Module(crate_module) {
2430 return None;
2432 }
2433
2434 let resolutions = self.resolutions(crate_module).borrow();
2435 let binding_key = BindingKey::new(ident, MacroNS);
2436 let resolution = resolutions.get(&binding_key)?;
2437 let binding = resolution.borrow().binding()?;
2438 let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() else {
2439 return None;
2440 };
2441 let module_name = crate_module.kind.name().unwrap_or(kw::Empty);
2442 let import_snippet = match import.kind {
2443 ImportKind::Single { source, target, .. } if source != target => {
2444 format!("{source} as {target}")
2445 }
2446 _ => format!("{ident}"),
2447 };
2448
2449 let mut corrections: Vec<(Span, String)> = Vec::new();
2450 if !import.is_nested() {
2451 corrections.push((import.span, format!("{module_name}::{import_snippet}")));
2454 } else {
2455 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2459 self.tcx.sess,
2460 import.span,
2461 import.use_span,
2462 );
2463 debug!(found_closing_brace, ?binding_span);
2464
2465 let mut removal_span = binding_span;
2466
2467 if found_closing_brace
2475 && let Some(previous_span) =
2476 extend_span_to_previous_binding(self.tcx.sess, binding_span)
2477 {
2478 debug!(?previous_span);
2479 removal_span = removal_span.with_lo(previous_span.lo());
2480 }
2481 debug!(?removal_span);
2482
2483 corrections.push((removal_span, "".to_string()));
2485
2486 let (has_nested, after_crate_name) =
2493 find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
2494 debug!(has_nested, ?after_crate_name);
2495
2496 let source_map = self.tcx.sess.source_map();
2497
2498 let is_definitely_crate = import
2500 .module_path
2501 .first()
2502 .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
2503
2504 let start_point = source_map.start_point(after_crate_name);
2506 if is_definitely_crate
2507 && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
2508 {
2509 corrections.push((
2510 start_point,
2511 if has_nested {
2512 format!("{start_snippet}{import_snippet}, ")
2514 } else {
2515 format!("{{{import_snippet}, {start_snippet}")
2518 },
2519 ));
2520
2521 if !has_nested {
2523 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2524 }
2525 } else {
2526 corrections.push((
2528 import.use_span.shrink_to_lo(),
2529 format!("use {module_name}::{import_snippet};\n"),
2530 ));
2531 }
2532 }
2533
2534 let suggestion = Some((
2535 corrections,
2536 String::from("a macro with this name exists at the root of the crate"),
2537 Applicability::MaybeIncorrect,
2538 ));
2539 Some((
2540 suggestion,
2541 Some(
2542 "this could be because a macro annotated with `#[macro_export]` will be exported \
2543 at the root of the crate instead of the module where it is defined"
2544 .to_string(),
2545 ),
2546 ))
2547 }
2548
2549 pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
2551 let local_items;
2552 let symbols = if module.is_local() {
2553 local_items = self
2554 .stripped_cfg_items
2555 .iter()
2556 .filter_map(|item| {
2557 let parent_module = self.opt_local_def_id(item.parent_module)?.to_def_id();
2558 Some(StrippedCfgItem { parent_module, name: item.name, cfg: item.cfg.clone() })
2559 })
2560 .collect::<Vec<_>>();
2561 local_items.as_slice()
2562 } else {
2563 self.tcx.stripped_cfg_items(module.krate)
2564 };
2565
2566 for &StrippedCfgItem { parent_module, name, ref cfg } in symbols {
2567 if parent_module != module || name.name != *segment {
2568 continue;
2569 }
2570
2571 let note = errors::FoundItemConfigureOut { span: name.span };
2572 err.subdiagnostic(note);
2573
2574 if let MetaItemKind::List(nested) = &cfg.kind
2575 && let MetaItemInner::MetaItem(meta_item) = &nested[0]
2576 && let MetaItemKind::NameValue(feature_name) = &meta_item.kind
2577 {
2578 let note = errors::ItemWasBehindFeature {
2579 feature: feature_name.symbol,
2580 span: meta_item.span,
2581 };
2582 err.subdiagnostic(note);
2583 } else {
2584 let note = errors::ItemWasCfgOut { span: cfg.span };
2585 err.subdiagnostic(note);
2586 }
2587 }
2588 }
2589}
2590
2591fn find_span_of_binding_until_next_binding(
2605 sess: &Session,
2606 binding_span: Span,
2607 use_span: Span,
2608) -> (bool, Span) {
2609 let source_map = sess.source_map();
2610
2611 let binding_until_end = binding_span.with_hi(use_span.hi());
2614
2615 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2618
2619 let mut found_closing_brace = false;
2626 let after_binding_until_next_binding =
2627 source_map.span_take_while(after_binding_until_end, |&ch| {
2628 if ch == '}' {
2629 found_closing_brace = true;
2630 }
2631 ch == ' ' || ch == ','
2632 });
2633
2634 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2639
2640 (found_closing_brace, span)
2641}
2642
2643fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2656 let source_map = sess.source_map();
2657
2658 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2662
2663 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2664 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2665 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2666 return None;
2667 }
2668
2669 let prev_comma = prev_comma.first().unwrap();
2670 let prev_starting_brace = prev_starting_brace.first().unwrap();
2671
2672 if prev_comma.len() > prev_starting_brace.len() {
2676 return None;
2677 }
2678
2679 Some(binding_span.with_lo(BytePos(
2680 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2683 )))
2684}
2685
2686#[instrument(level = "debug", skip(sess))]
2700fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
2701 let source_map = sess.source_map();
2702
2703 let mut num_colons = 0;
2705 let until_second_colon = source_map.span_take_while(use_span, |c| {
2707 if *c == ':' {
2708 num_colons += 1;
2709 }
2710 !matches!(c, ':' if num_colons == 2)
2711 });
2712 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2714
2715 let mut found_a_non_whitespace_character = false;
2716 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2718 if found_a_non_whitespace_character {
2719 return false;
2720 }
2721 if !c.is_whitespace() {
2722 found_a_non_whitespace_character = true;
2723 }
2724 true
2725 });
2726
2727 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2729
2730 (next_left_bracket == after_second_colon, from_second_colon)
2731}
2732
2733enum Instead {
2736 Yes,
2737 No,
2738}
2739
2740enum FoundUse {
2742 Yes,
2743 No,
2744}
2745
2746pub(crate) enum DiagMode {
2748 Normal,
2749 Pattern,
2751 Import {
2753 append: bool,
2756 },
2757}
2758
2759pub(crate) fn import_candidates(
2760 tcx: TyCtxt<'_>,
2761 err: &mut Diag<'_>,
2762 use_placement_span: Option<Span>,
2764 candidates: &[ImportSuggestion],
2765 mode: DiagMode,
2766 append: &str,
2767) {
2768 show_candidates(
2769 tcx,
2770 err,
2771 use_placement_span,
2772 candidates,
2773 Instead::Yes,
2774 FoundUse::Yes,
2775 mode,
2776 vec![],
2777 append,
2778 );
2779}
2780
2781type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
2782
2783fn show_candidates(
2788 tcx: TyCtxt<'_>,
2789 err: &mut Diag<'_>,
2790 use_placement_span: Option<Span>,
2792 candidates: &[ImportSuggestion],
2793 instead: Instead,
2794 found_use: FoundUse,
2795 mode: DiagMode,
2796 path: Vec<Segment>,
2797 append: &str,
2798) -> bool {
2799 if candidates.is_empty() {
2800 return false;
2801 }
2802
2803 let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
2804 let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
2805
2806 candidates.iter().for_each(|c| {
2807 if c.accessible {
2808 if c.doc_visible {
2810 accessible_path_strings.push((
2811 pprust::path_to_string(&c.path),
2812 c.descr,
2813 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
2814 &c.note,
2815 c.via_import,
2816 ))
2817 }
2818 } else {
2819 inaccessible_path_strings.push((
2820 pprust::path_to_string(&c.path),
2821 c.descr,
2822 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
2823 &c.note,
2824 c.via_import,
2825 ))
2826 }
2827 });
2828
2829 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2832 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2833 path_strings.dedup_by(|a, b| a.0 == b.0);
2834 let core_path_strings =
2835 path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
2836 let std_path_strings =
2837 path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
2838 let foreign_crate_path_strings =
2839 path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
2840
2841 if std_path_strings.len() == core_path_strings.len() {
2844 path_strings.extend(std_path_strings);
2846 } else {
2847 path_strings.extend(std_path_strings);
2848 path_strings.extend(core_path_strings);
2849 }
2850 path_strings.extend(foreign_crate_path_strings);
2852 }
2853
2854 if !accessible_path_strings.is_empty() {
2855 let (determiner, kind, s, name, through) =
2856 if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
2857 (
2858 "this",
2859 *descr,
2860 "",
2861 format!(" `{name}`"),
2862 if *via_import { " through its public re-export" } else { "" },
2863 )
2864 } else {
2865 let kinds = accessible_path_strings
2868 .iter()
2869 .map(|(_, descr, _, _, _)| *descr)
2870 .collect::<UnordSet<&str>>();
2871 let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
2872 let s = if kind.ends_with('s') { "es" } else { "s" };
2873
2874 ("one of these", kind, s, String::new(), "")
2875 };
2876
2877 let instead = if let Instead::Yes = instead { " instead" } else { "" };
2878 let mut msg = if let DiagMode::Pattern = mode {
2879 format!(
2880 "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
2881 pattern",
2882 )
2883 } else {
2884 format!("consider importing {determiner} {kind}{s}{through}{instead}")
2885 };
2886
2887 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2888 err.note(note.clone());
2889 }
2890
2891 let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
2892 msg.push(':');
2893
2894 for candidate in accessible_path_strings {
2895 msg.push('\n');
2896 msg.push_str(&candidate.0);
2897 }
2898 };
2899
2900 if let Some(span) = use_placement_span {
2901 let (add_use, trailing) = match mode {
2902 DiagMode::Pattern => {
2903 err.span_suggestions(
2904 span,
2905 msg,
2906 accessible_path_strings.into_iter().map(|a| a.0),
2907 Applicability::MaybeIncorrect,
2908 );
2909 return true;
2910 }
2911 DiagMode::Import { .. } => ("", ""),
2912 DiagMode::Normal => ("use ", ";\n"),
2913 };
2914 for candidate in &mut accessible_path_strings {
2915 let additional_newline = if let FoundUse::No = found_use
2918 && let DiagMode::Normal = mode
2919 {
2920 "\n"
2921 } else {
2922 ""
2923 };
2924 candidate.0 =
2925 format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
2926 }
2927
2928 match mode {
2929 DiagMode::Import { append: true, .. } => {
2930 append_candidates(&mut msg, accessible_path_strings);
2931 err.span_help(span, msg);
2932 }
2933 _ => {
2934 err.span_suggestions_with_style(
2935 span,
2936 msg,
2937 accessible_path_strings.into_iter().map(|a| a.0),
2938 Applicability::MaybeIncorrect,
2939 SuggestionStyle::ShowAlways,
2940 );
2941 }
2942 }
2943
2944 if let [first, .., last] = &path[..] {
2945 let sp = first.ident.span.until(last.ident.span);
2946 if sp.can_be_used_for_suggestions() && !sp.is_empty() {
2949 err.span_suggestion_verbose(
2950 sp,
2951 format!("if you import `{}`, refer to it directly", last.ident),
2952 "",
2953 Applicability::Unspecified,
2954 );
2955 }
2956 }
2957 } else {
2958 append_candidates(&mut msg, accessible_path_strings);
2959 err.help(msg);
2960 }
2961 true
2962 } else if !(inaccessible_path_strings.is_empty() || matches!(mode, DiagMode::Import { .. })) {
2963 let prefix =
2964 if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
2965 if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
2966 let msg = format!(
2967 "{prefix}{descr} `{name}`{} exists but is inaccessible",
2968 if let DiagMode::Pattern = mode { ", which" } else { "" }
2969 );
2970
2971 if let Some(source_span) = source_span {
2972 let span = tcx.sess.source_map().guess_head_span(*source_span);
2973 let mut multi_span = MultiSpan::from_span(span);
2974 multi_span.push_span_label(span, "not accessible");
2975 err.span_note(multi_span, msg);
2976 } else {
2977 err.note(msg);
2978 }
2979 if let Some(note) = (*note).as_deref() {
2980 err.note(note.to_string());
2981 }
2982 } else {
2983 let (_, descr_first, _, _, _) = &inaccessible_path_strings[0];
2984 let descr = if inaccessible_path_strings
2985 .iter()
2986 .skip(1)
2987 .all(|(_, descr, _, _, _)| descr == descr_first)
2988 {
2989 descr_first
2990 } else {
2991 "item"
2992 };
2993 let plural_descr =
2994 if descr.ends_with('s') { format!("{descr}es") } else { format!("{descr}s") };
2995
2996 let mut msg = format!("{prefix}these {plural_descr} exist but are inaccessible");
2997 let mut has_colon = false;
2998
2999 let mut spans = Vec::new();
3000 for (name, _, source_span, _, _) in &inaccessible_path_strings {
3001 if let Some(source_span) = source_span {
3002 let span = tcx.sess.source_map().guess_head_span(*source_span);
3003 spans.push((name, span));
3004 } else {
3005 if !has_colon {
3006 msg.push(':');
3007 has_colon = true;
3008 }
3009 msg.push('\n');
3010 msg.push_str(name);
3011 }
3012 }
3013
3014 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3015 for (name, span) in spans {
3016 multi_span.push_span_label(span, format!("`{name}`: not accessible"));
3017 }
3018
3019 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3020 err.note(note.clone());
3021 }
3022
3023 err.span_note(multi_span, msg);
3024 }
3025 true
3026 } else {
3027 false
3028 }
3029}
3030
3031#[derive(Debug)]
3032struct UsePlacementFinder {
3033 target_module: NodeId,
3034 first_legal_span: Option<Span>,
3035 first_use_span: Option<Span>,
3036}
3037
3038impl UsePlacementFinder {
3039 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3040 let mut finder =
3041 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3042 finder.visit_crate(krate);
3043 if let Some(use_span) = finder.first_use_span {
3044 (Some(use_span), FoundUse::Yes)
3045 } else {
3046 (finder.first_legal_span, FoundUse::No)
3047 }
3048 }
3049}
3050
3051impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
3052 fn visit_crate(&mut self, c: &Crate) {
3053 if self.target_module == CRATE_NODE_ID {
3054 let inject = c.spans.inject_use_span;
3055 if is_span_suitable_for_use_injection(inject) {
3056 self.first_legal_span = Some(inject);
3057 }
3058 self.first_use_span = search_for_any_use_in_items(&c.items);
3059 } else {
3060 visit::walk_crate(self, c);
3061 }
3062 }
3063
3064 fn visit_item(&mut self, item: &'tcx ast::Item) {
3065 if self.target_module == item.id {
3066 if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans, _)) = &item.kind {
3067 let inject = mod_spans.inject_use_span;
3068 if is_span_suitable_for_use_injection(inject) {
3069 self.first_legal_span = Some(inject);
3070 }
3071 self.first_use_span = search_for_any_use_in_items(items);
3072 }
3073 } else {
3074 visit::walk_item(self, item);
3075 }
3076 }
3077}
3078
3079fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
3080 for item in items {
3081 if let ItemKind::Use(..) = item.kind
3082 && is_span_suitable_for_use_injection(item.span)
3083 {
3084 let mut lo = item.span.lo();
3085 for attr in &item.attrs {
3086 if attr.span.eq_ctxt(item.span) {
3087 lo = std::cmp::min(lo, attr.span.lo());
3088 }
3089 }
3090 return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3091 }
3092 }
3093 None
3094}
3095
3096fn is_span_suitable_for_use_injection(s: Span) -> bool {
3097 !s.from_expansion()
3100}