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 std::mem::take(&mut self.use_injections)
174 {
175 let (span, found_use) = if let Some(def_id) = def_id.as_local() {
176 UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id))
177 } else {
178 (None, FoundUse::No)
179 };
180
181 if !candidates.is_empty() {
182 show_candidates(
183 self.tcx,
184 &mut err,
185 span,
186 &candidates,
187 if instead { Instead::Yes } else { Instead::No },
188 found_use,
189 DiagMode::Normal,
190 path,
191 "",
192 );
193 err.emit();
194 } else if let Some((span, msg, sugg, appl)) = suggestion {
195 err.span_suggestion_verbose(span, msg, sugg, appl);
196 err.emit();
197 } else if let [segment] = path.as_slice()
198 && is_call
199 {
200 err.stash(segment.ident.span, rustc_errors::StashKey::CallIntoMethod);
201 } else {
202 err.emit();
203 }
204 }
205 }
206
207 pub(crate) fn report_conflict(
208 &mut self,
209 parent: Module<'_>,
210 ident: Ident,
211 ns: Namespace,
212 new_binding: NameBinding<'ra>,
213 old_binding: NameBinding<'ra>,
214 ) {
215 if old_binding.span.lo() > new_binding.span.lo() {
217 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
218 }
219
220 let container = match parent.kind {
221 ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
224 ModuleKind::Block => "block",
225 };
226
227 let (name, span) =
228 (ident.name, self.tcx.sess.source_map().guess_head_span(new_binding.span));
229
230 if self.name_already_seen.get(&name) == Some(&span) {
231 return;
232 }
233
234 let old_kind = match (ns, old_binding.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(sym::dummy));
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_assoc_item()
1186 && !this.tcx.features().import_trait_associated_functions()
1187 {
1188 return;
1189 }
1190
1191 if ident.name == kw::Underscore {
1192 return;
1193 }
1194
1195 let child_accessible =
1196 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1197
1198 if in_module_is_extern && !child_accessible {
1200 return;
1201 }
1202
1203 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1204
1205 if via_import && name_binding.is_possibly_imported_variant() {
1211 return;
1212 }
1213
1214 if let NameBindingKind::Import { binding, .. } = name_binding.kind
1216 && this.is_accessible_from(binding.vis, parent_scope.module)
1217 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1218 {
1219 return;
1220 }
1221
1222 let res = name_binding.res();
1223 let did = match res {
1224 Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1225 _ => res.opt_def_id(),
1226 };
1227 let child_doc_visible = doc_visible
1228 && did.is_none_or(|did| did.is_local() || !this.tcx.is_doc_hidden(did));
1229
1230 if ident.name == lookup_ident.name
1234 && ns == namespace
1235 && in_module != parent_scope.module
1236 && !ident.span.normalize_to_macros_2_0().from_expansion()
1237 && filter_fn(res)
1238 {
1239 let mut segms = if lookup_ident.span.at_least_rust_2018() {
1241 crate_path.clone()
1244 } else {
1245 ThinVec::new()
1246 };
1247 segms.append(&mut path_segments.clone());
1248
1249 segms.push(ast::PathSegment::from_ident(ident));
1250 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1251
1252 if child_accessible
1253 && let Some(idx) = candidates
1255 .iter()
1256 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1257 {
1258 candidates.remove(idx);
1259 }
1260
1261 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1262 let note = if let Some(did) = did {
1265 let requires_note = !did.is_local()
1266 && this.tcx.get_attrs(did, sym::rustc_diagnostic_item).any(
1267 |attr| {
1268 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1269 .map(|x| Some(x))
1270 .contains(&attr.value_str())
1271 },
1272 );
1273
1274 requires_note.then(|| {
1275 format!(
1276 "'{}' is included in the prelude starting in Edition 2021",
1277 path_names_to_string(&path)
1278 )
1279 })
1280 } else {
1281 None
1282 };
1283
1284 candidates.push(ImportSuggestion {
1285 did,
1286 descr: res.descr(),
1287 path,
1288 accessible: child_accessible,
1289 doc_visible: child_doc_visible,
1290 note,
1291 via_import,
1292 });
1293 }
1294 }
1295
1296 if let Some(module) = name_binding.module() {
1298 let mut path_segments = path_segments.clone();
1300 path_segments.push(ast::PathSegment::from_ident(ident));
1301
1302 let alias_import = if let NameBindingKind::Import { import, .. } =
1303 name_binding.kind
1304 && let ImportKind::ExternCrate { source: Some(_), .. } = import.kind
1305 && import.parent_scope.expansion == parent_scope.expansion
1306 {
1307 true
1308 } else {
1309 false
1310 };
1311
1312 let is_extern_crate_that_also_appears_in_prelude =
1313 name_binding.is_extern_crate() && lookup_ident.span.at_least_rust_2018();
1314
1315 if !is_extern_crate_that_also_appears_in_prelude || alias_import {
1316 if seen_modules.insert(module.def_id()) {
1318 if via_import { &mut worklist_via_import } else { &mut worklist }
1319 .push((module, path_segments, child_accessible, child_doc_visible));
1320 }
1321 }
1322 }
1323 })
1324 }
1325
1326 candidates
1327 }
1328
1329 pub(crate) fn lookup_import_candidates<FilterFn>(
1337 &mut self,
1338 lookup_ident: Ident,
1339 namespace: Namespace,
1340 parent_scope: &ParentScope<'ra>,
1341 filter_fn: FilterFn,
1342 ) -> Vec<ImportSuggestion>
1343 where
1344 FilterFn: Fn(Res) -> bool,
1345 {
1346 let crate_path = thin_vec![ast::PathSegment::from_ident(Ident::with_dummy_span(kw::Crate))];
1347 let mut suggestions = self.lookup_import_candidates_from_module(
1348 lookup_ident,
1349 namespace,
1350 parent_scope,
1351 self.graph_root,
1352 crate_path,
1353 &filter_fn,
1354 );
1355
1356 if lookup_ident.span.at_least_rust_2018() {
1357 for ident in self.extern_prelude.clone().into_keys() {
1358 if ident.span.from_expansion() {
1359 continue;
1365 }
1366 let Some(crate_id) = self.crate_loader(|c| c.maybe_process_path_extern(ident.name))
1367 else {
1368 continue;
1369 };
1370
1371 let crate_def_id = crate_id.as_def_id();
1372 let crate_root = self.expect_module(crate_def_id);
1373
1374 let needs_disambiguation =
1378 self.resolutions(parent_scope.module).borrow().iter().any(
1379 |(key, name_resolution)| {
1380 if key.ns == TypeNS
1381 && key.ident == ident
1382 && let Some(binding) = name_resolution.borrow().binding
1383 {
1384 match binding.res() {
1385 Res::Def(_, def_id) => def_id != crate_def_id,
1388 Res::PrimTy(_) => true,
1389 _ => false,
1390 }
1391 } else {
1392 false
1393 }
1394 },
1395 );
1396 let mut crate_path = ThinVec::new();
1397 if needs_disambiguation {
1398 crate_path.push(ast::PathSegment::path_root(rustc_span::DUMMY_SP));
1399 }
1400 crate_path.push(ast::PathSegment::from_ident(ident));
1401
1402 suggestions.extend(self.lookup_import_candidates_from_module(
1403 lookup_ident,
1404 namespace,
1405 parent_scope,
1406 crate_root,
1407 crate_path,
1408 &filter_fn,
1409 ));
1410 }
1411 }
1412
1413 suggestions
1414 }
1415
1416 pub(crate) fn unresolved_macro_suggestions(
1417 &mut self,
1418 err: &mut Diag<'_>,
1419 macro_kind: MacroKind,
1420 parent_scope: &ParentScope<'ra>,
1421 ident: Ident,
1422 krate: &Crate,
1423 ) {
1424 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1425 let suggestion = self.early_lookup_typo_candidate(
1426 ScopeSet::Macro(macro_kind),
1427 parent_scope,
1428 ident,
1429 is_expected,
1430 );
1431 self.add_typo_suggestion(err, suggestion, ident.span);
1432
1433 let import_suggestions =
1434 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1435 let (span, found_use) = match parent_scope.module.nearest_parent_mod().as_local() {
1436 Some(def_id) => UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id)),
1437 None => (None, FoundUse::No),
1438 };
1439 show_candidates(
1440 self.tcx,
1441 err,
1442 span,
1443 &import_suggestions,
1444 Instead::No,
1445 found_use,
1446 DiagMode::Normal,
1447 vec![],
1448 "",
1449 );
1450
1451 if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1452 let label_span = ident.span.shrink_to_hi();
1453 let mut spans = MultiSpan::from_span(label_span);
1454 spans.push_span_label(label_span, "put a macro name here");
1455 err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1456 return;
1457 }
1458
1459 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1460 err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1461 return;
1462 }
1463
1464 let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1465 if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1466 });
1467
1468 if let Some((def_id, unused_ident)) = unused_macro {
1469 let scope = self.local_macro_def_scopes[&def_id];
1470 let parent_nearest = parent_scope.module.nearest_parent_mod();
1471 if Some(parent_nearest) == scope.opt_def_id() {
1472 match macro_kind {
1473 MacroKind::Bang => {
1474 err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1475 err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1476 }
1477 MacroKind::Attr => {
1478 err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1479 }
1480 MacroKind::Derive => {
1481 err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1482 }
1483 }
1484
1485 return;
1486 }
1487 }
1488
1489 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1490 err.subdiagnostic(AddedMacroUse);
1491 return;
1492 }
1493
1494 if ident.name == kw::Default
1495 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1496 {
1497 let span = self.def_span(def_id);
1498 let source_map = self.tcx.sess.source_map();
1499 let head_span = source_map.guess_head_span(span);
1500 err.subdiagnostic(ConsiderAddingADerive {
1501 span: head_span.shrink_to_lo(),
1502 suggestion: "#[derive(Default)]\n".to_string(),
1503 });
1504 }
1505 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1506 let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1507 ident,
1508 ScopeSet::All(ns),
1509 parent_scope,
1510 None,
1511 false,
1512 None,
1513 None,
1514 ) else {
1515 continue;
1516 };
1517
1518 let desc = match binding.res() {
1519 Res::Def(DefKind::Macro(MacroKind::Bang), _) => "a function-like macro".to_string(),
1520 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1521 format!("an attribute: `#[{ident}]`")
1522 }
1523 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1524 format!("a derive macro: `#[derive({ident})]`")
1525 }
1526 Res::ToolMod => {
1527 continue;
1529 }
1530 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1531 "only a trait, without a derive macro".to_string()
1532 }
1533 res => format!(
1534 "{} {}, not {} {}",
1535 res.article(),
1536 res.descr(),
1537 macro_kind.article(),
1538 macro_kind.descr_expected(),
1539 ),
1540 };
1541 if let crate::NameBindingKind::Import { import, .. } = binding.kind
1542 && !import.span.is_dummy()
1543 {
1544 let note = errors::IdentImporterHereButItIsDesc {
1545 span: import.span,
1546 imported_ident: ident,
1547 imported_ident_desc: &desc,
1548 };
1549 err.subdiagnostic(note);
1550 self.record_use(ident, binding, Used::Other);
1553 return;
1554 }
1555 let note = errors::IdentInScopeButItIsDesc {
1556 imported_ident: ident,
1557 imported_ident_desc: &desc,
1558 };
1559 err.subdiagnostic(note);
1560 return;
1561 }
1562 }
1563
1564 pub(crate) fn add_typo_suggestion(
1565 &self,
1566 err: &mut Diag<'_>,
1567 suggestion: Option<TypoSuggestion>,
1568 span: Span,
1569 ) -> bool {
1570 let suggestion = match suggestion {
1571 None => return false,
1572 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1574 Some(suggestion) => suggestion,
1575 };
1576
1577 let mut did_label_def_span = false;
1578
1579 if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1580 if span.overlaps(def_span) {
1581 return false;
1600 }
1601 let span = self.tcx.sess.source_map().guess_head_span(def_span);
1602 let candidate_descr = suggestion.res.descr();
1603 let candidate = suggestion.candidate;
1604 let label = match suggestion.target {
1605 SuggestionTarget::SimilarlyNamed => {
1606 errors::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
1607 }
1608 SuggestionTarget::SingleItem => {
1609 errors::DefinedHere::SingleItem { span, candidate_descr, candidate }
1610 }
1611 };
1612 did_label_def_span = true;
1613 err.subdiagnostic(label);
1614 }
1615
1616 let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
1617 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1618 && let Some(span) = suggestion.span
1619 && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
1620 && snippet == candidate
1621 {
1622 let candidate = suggestion.candidate;
1623 let msg = format!(
1626 "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
1627 );
1628 if !did_label_def_span {
1629 err.span_label(span, format!("`{candidate}` defined here"));
1630 }
1631 (span, msg, snippet)
1632 } else {
1633 let msg = match suggestion.target {
1634 SuggestionTarget::SimilarlyNamed => format!(
1635 "{} {} with a similar name exists",
1636 suggestion.res.article(),
1637 suggestion.res.descr()
1638 ),
1639 SuggestionTarget::SingleItem => {
1640 format!("maybe you meant this {}", suggestion.res.descr())
1641 }
1642 };
1643 (span, msg, suggestion.candidate.to_ident_string())
1644 };
1645 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1646 true
1647 }
1648
1649 fn binding_description(&self, b: NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1650 let res = b.res();
1651 if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
1652 let add_built_in =
1654 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1655 let (built_in, from) = if from_prelude {
1656 ("", " from prelude")
1657 } else if b.is_extern_crate()
1658 && !b.is_import()
1659 && self.tcx.sess.opts.externs.get(ident.as_str()).is_some()
1660 {
1661 ("", " passed with `--extern`")
1662 } else if add_built_in {
1663 (" built-in", "")
1664 } else {
1665 ("", "")
1666 };
1667
1668 let a = if built_in.is_empty() { res.article() } else { "a" };
1669 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1670 } else {
1671 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1672 format!("the {thing} {introduced} here", thing = res.descr())
1673 }
1674 }
1675
1676 fn ambiguity_diagnostics(&self, ambiguity_error: &AmbiguityError<'_>) -> AmbiguityErrorDiag {
1677 let AmbiguityError { kind, ident, b1, b2, misc1, misc2, .. } = *ambiguity_error;
1678 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1679 (b2, b1, misc2, misc1, true)
1681 } else {
1682 (b1, b2, misc1, misc2, false)
1683 };
1684 let could_refer_to = |b: NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1685 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1686 let note_msg = format!("`{ident}` could{also} refer to {what}");
1687
1688 let thing = b.res().descr();
1689 let mut help_msgs = Vec::new();
1690 if b.is_glob_import()
1691 && (kind == AmbiguityKind::GlobVsGlob
1692 || kind == AmbiguityKind::GlobVsExpanded
1693 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1694 {
1695 help_msgs.push(format!(
1696 "consider adding an explicit import of `{ident}` to disambiguate"
1697 ))
1698 }
1699 if b.is_extern_crate() && ident.span.at_least_rust_2018() {
1700 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1701 }
1702 match misc {
1703 AmbiguityErrorMisc::SuggestCrate => help_msgs
1704 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously")),
1705 AmbiguityErrorMisc::SuggestSelf => help_msgs
1706 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously")),
1707 AmbiguityErrorMisc::FromPrelude | AmbiguityErrorMisc::None => {}
1708 }
1709
1710 (
1711 b.span,
1712 note_msg,
1713 help_msgs
1714 .iter()
1715 .enumerate()
1716 .map(|(i, help_msg)| {
1717 let or = if i == 0 { "" } else { "or " };
1718 format!("{or}{help_msg}")
1719 })
1720 .collect::<Vec<_>>(),
1721 )
1722 };
1723 let (b1_span, b1_note_msg, b1_help_msgs) = could_refer_to(b1, misc1, "");
1724 let (b2_span, b2_note_msg, b2_help_msgs) = could_refer_to(b2, misc2, " also");
1725
1726 AmbiguityErrorDiag {
1727 msg: format!("`{ident}` is ambiguous"),
1728 span: ident.span,
1729 label_span: ident.span,
1730 label_msg: "ambiguous name".to_string(),
1731 note_msg: format!("ambiguous because of {}", kind.descr()),
1732 b1_span,
1733 b1_note_msg,
1734 b1_help_msgs,
1735 b2_span,
1736 b2_note_msg,
1737 b2_help_msgs,
1738 }
1739 }
1740
1741 fn ctor_fields_span(&self, binding: NameBinding<'_>) -> Option<Span> {
1744 let NameBindingKind::Res(Res::Def(
1745 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
1746 ctor_def_id,
1747 )) = binding.kind
1748 else {
1749 return None;
1750 };
1751
1752 let def_id = self.tcx.parent(ctor_def_id);
1753 self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) }
1755
1756 fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
1757 let PrivacyError { ident, binding, outermost_res, parent_scope, single_nested, dedup_span } =
1758 *privacy_error;
1759
1760 let res = binding.res();
1761 let ctor_fields_span = self.ctor_fields_span(binding);
1762 let plain_descr = res.descr().to_string();
1763 let nonimport_descr =
1764 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1765 let import_descr = nonimport_descr.clone() + " import";
1766 let get_descr =
1767 |b: NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1768
1769 let ident_descr = get_descr(binding);
1771 let mut err =
1772 self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
1773
1774 let mut not_publicly_reexported = false;
1775 if let Some((this_res, outer_ident)) = outermost_res {
1776 let import_suggestions = self.lookup_import_candidates(
1777 outer_ident,
1778 this_res.ns().unwrap_or(Namespace::TypeNS),
1779 &parent_scope,
1780 &|res: Res| res == this_res,
1781 );
1782 let point_to_def = !show_candidates(
1783 self.tcx,
1784 &mut err,
1785 Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
1786 &import_suggestions,
1787 Instead::Yes,
1788 FoundUse::Yes,
1789 DiagMode::Import { append: single_nested, unresolved_import: false },
1790 vec![],
1791 "",
1792 );
1793 if point_to_def && ident.span != outer_ident.span {
1795 not_publicly_reexported = true;
1796 let label = errors::OuterIdentIsNotPubliclyReexported {
1797 span: outer_ident.span,
1798 outer_ident_descr: this_res.descr(),
1799 outer_ident,
1800 };
1801 err.subdiagnostic(label);
1802 }
1803 }
1804
1805 let mut non_exhaustive = None;
1806 if let Some(def_id) = res.opt_def_id()
1810 && !def_id.is_local()
1811 && let Some(attr) = self.tcx.get_attr(def_id, sym::non_exhaustive)
1812 {
1813 non_exhaustive = Some(attr.span());
1814 } else if let Some(span) = ctor_fields_span {
1815 let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
1816 err.subdiagnostic(label);
1817 if let Res::Def(_, d) = res
1818 && let Some(fields) = self.field_visibility_spans.get(&d)
1819 {
1820 let spans = fields.iter().map(|span| *span).collect();
1821 let sugg =
1822 errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
1823 err.subdiagnostic(sugg);
1824 }
1825 }
1826
1827 let mut sugg_paths = vec![];
1828 if let Some(mut def_id) = res.opt_def_id() {
1829 let mut path = vec![def_id];
1831 while let Some(parent) = self.tcx.opt_parent(def_id) {
1832 def_id = parent;
1833 if !def_id.is_top_level_module() {
1834 path.push(def_id);
1835 } else {
1836 break;
1837 }
1838 }
1839 let path_names: Option<Vec<String>> = path
1841 .iter()
1842 .rev()
1843 .map(|def_id| {
1844 self.tcx.opt_item_name(*def_id).map(|n| {
1845 if def_id.is_top_level_module() {
1846 "crate".to_string()
1847 } else {
1848 n.to_string()
1849 }
1850 })
1851 })
1852 .collect();
1853 if let Some(def_id) = path.get(0)
1854 && let Some(path) = path_names
1855 {
1856 if let Some(def_id) = def_id.as_local() {
1857 if self.effective_visibilities.is_directly_public(def_id) {
1858 sugg_paths.push((path, false));
1859 }
1860 } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
1861 {
1862 sugg_paths.push((path, false));
1863 }
1864 }
1865 }
1866
1867 let first_binding = binding;
1869 let mut next_binding = Some(binding);
1870 let mut next_ident = ident;
1871 let mut path = vec![];
1872 while let Some(binding) = next_binding {
1873 let name = next_ident;
1874 next_binding = match binding.kind {
1875 _ if res == Res::Err => None,
1876 NameBindingKind::Import { binding, import, .. } => match import.kind {
1877 _ if binding.span.is_dummy() => None,
1878 ImportKind::Single { source, .. } => {
1879 next_ident = source;
1880 Some(binding)
1881 }
1882 ImportKind::Glob { .. }
1883 | ImportKind::MacroUse { .. }
1884 | ImportKind::MacroExport => Some(binding),
1885 ImportKind::ExternCrate { .. } => None,
1886 },
1887 _ => None,
1888 };
1889
1890 match binding.kind {
1891 NameBindingKind::Import { import, .. } => {
1892 for segment in import.module_path.iter().skip(1) {
1893 path.push(segment.ident.to_string());
1894 }
1895 sugg_paths.push((
1896 path.iter()
1897 .cloned()
1898 .chain(vec![ident.to_string()].into_iter())
1899 .collect::<Vec<_>>(),
1900 true, ));
1902 }
1903 NameBindingKind::Res(_) | NameBindingKind::Module(_) => {}
1904 }
1905 let first = binding == first_binding;
1906 let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
1907 let mut note_span = MultiSpan::from_span(def_span);
1908 if !first && binding.vis.is_public() {
1909 let desc = match binding.kind {
1910 NameBindingKind::Import { .. } => "re-export",
1911 _ => "directly",
1912 };
1913 note_span.push_span_label(def_span, format!("you could import this {desc}"));
1914 }
1915 if next_binding.is_none()
1918 && let Some(span) = non_exhaustive
1919 {
1920 note_span.push_span_label(
1921 span,
1922 "cannot be constructed because it is `#[non_exhaustive]`",
1923 );
1924 }
1925 let note = errors::NoteAndRefersToTheItemDefinedHere {
1926 span: note_span,
1927 binding_descr: get_descr(binding),
1928 binding_name: name,
1929 first,
1930 dots: next_binding.is_some(),
1931 };
1932 err.subdiagnostic(note);
1933 }
1934 sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0] == "core", *reexport));
1936 for (sugg, reexport) in sugg_paths {
1937 if not_publicly_reexported {
1938 break;
1939 }
1940 if sugg.len() <= 1 {
1941 continue;
1944 }
1945 let path = sugg.join("::");
1946 let sugg = if reexport {
1947 errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
1948 } else {
1949 errors::ImportIdent::Directly { span: dedup_span, ident, path }
1950 };
1951 err.subdiagnostic(sugg);
1952 break;
1953 }
1954
1955 err.emit();
1956 }
1957
1958 pub(crate) fn find_similarly_named_module_or_crate(
1959 &mut self,
1960 ident: Symbol,
1961 current_module: Module<'ra>,
1962 ) -> Option<Symbol> {
1963 let mut candidates = self
1964 .extern_prelude
1965 .keys()
1966 .map(|ident| ident.name)
1967 .chain(
1968 self.module_map
1969 .iter()
1970 .filter(|(_, module)| {
1971 current_module.is_ancestor_of(**module) && current_module != **module
1972 })
1973 .flat_map(|(_, module)| module.kind.name()),
1974 )
1975 .filter(|c| !c.to_string().is_empty())
1976 .collect::<Vec<_>>();
1977 candidates.sort();
1978 candidates.dedup();
1979 find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
1980 }
1981
1982 pub(crate) fn report_path_resolution_error(
1983 &mut self,
1984 path: &[Segment],
1985 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
1987 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1988 ignore_binding: Option<NameBinding<'ra>>,
1989 ignore_import: Option<Import<'ra>>,
1990 module: Option<ModuleOrUniformRoot<'ra>>,
1991 failed_segment_idx: usize,
1992 ident: Ident,
1993 ) -> (String, Option<Suggestion>) {
1994 let is_last = failed_segment_idx == path.len() - 1;
1995 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1996 let module_res = match module {
1997 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1998 _ => None,
1999 };
2000 if module_res == self.graph_root.res() {
2001 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
2002 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2003 candidates
2004 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2005 if let Some(candidate) = candidates.get(0) {
2006 let path = {
2007 let len = candidate.path.segments.len();
2009 let start_index = (0..=failed_segment_idx.min(len - 1))
2010 .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2011 .unwrap_or_default();
2012 let segments =
2013 (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2014 Path { segments, span: Span::default(), tokens: None }
2015 };
2016 (
2017 String::from("unresolved import"),
2018 Some((
2019 vec![(ident.span, pprust::path_to_string(&path))],
2020 String::from("a similar path exists"),
2021 Applicability::MaybeIncorrect,
2022 )),
2023 )
2024 } else if ident.name == sym::core {
2025 (
2026 format!("you might be missing crate `{ident}`"),
2027 Some((
2028 vec![(ident.span, "std".to_string())],
2029 "try using `std` instead of `core`".to_string(),
2030 Applicability::MaybeIncorrect,
2031 )),
2032 )
2033 } else if ident.name == kw::Underscore {
2034 (format!("`_` is not a valid crate or module name"), None)
2035 } else if self.tcx.sess.is_rust_2015() {
2036 (
2037 format!("use of unresolved module or unlinked crate `{ident}`"),
2038 Some((
2039 vec![(
2040 self.current_crate_outer_attr_insert_span,
2041 format!("extern crate {ident};\n"),
2042 )],
2043 if was_invoked_from_cargo() {
2044 format!(
2045 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2046 to add it to your `Cargo.toml` and import it in your code",
2047 )
2048 } else {
2049 format!(
2050 "you might be missing a crate named `{ident}`, add it to your \
2051 project and import it in your code",
2052 )
2053 },
2054 Applicability::MaybeIncorrect,
2055 )),
2056 )
2057 } else {
2058 (format!("could not find `{ident}` in the crate root"), None)
2059 }
2060 } else if failed_segment_idx > 0 {
2061 let parent = path[failed_segment_idx - 1].ident.name;
2062 let parent = match parent {
2063 kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2066 "the list of imported crates".to_owned()
2067 }
2068 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2069 _ => format!("`{parent}`"),
2070 };
2071
2072 let mut msg = format!("could not find `{ident}` in {parent}");
2073 if ns == TypeNS || ns == ValueNS {
2074 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2075 let binding = if let Some(module) = module {
2076 self.resolve_ident_in_module(
2077 module,
2078 ident,
2079 ns_to_try,
2080 parent_scope,
2081 None,
2082 ignore_binding,
2083 ignore_import,
2084 )
2085 .ok()
2086 } else if let Some(ribs) = ribs
2087 && let Some(TypeNS | ValueNS) = opt_ns
2088 {
2089 assert!(ignore_import.is_none());
2090 match self.resolve_ident_in_lexical_scope(
2091 ident,
2092 ns_to_try,
2093 parent_scope,
2094 None,
2095 &ribs[ns_to_try],
2096 ignore_binding,
2097 ) {
2098 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
2100 _ => None,
2101 }
2102 } else {
2103 self.early_resolve_ident_in_lexical_scope(
2104 ident,
2105 ScopeSet::All(ns_to_try),
2106 parent_scope,
2107 None,
2108 false,
2109 ignore_binding,
2110 ignore_import,
2111 )
2112 .ok()
2113 };
2114 if let Some(binding) = binding {
2115 let mut found = |what| {
2116 msg = format!(
2117 "expected {}, found {} `{}` in {}",
2118 ns.descr(),
2119 what,
2120 ident,
2121 parent
2122 )
2123 };
2124 if binding.module().is_some() {
2125 found("module")
2126 } else {
2127 match binding.res() {
2128 Res::Def(kind, id) => found(kind.descr(id)),
2131 _ => found(ns_to_try.descr()),
2132 }
2133 }
2134 };
2135 }
2136 (msg, None)
2137 } else if ident.name == kw::SelfUpper {
2138 if opt_ns.is_none() {
2142 ("`Self` cannot be used in imports".to_string(), None)
2143 } else {
2144 (
2145 "`Self` is only available in impls, traits, and type definitions".to_string(),
2146 None,
2147 )
2148 }
2149 } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2150 let binding = if let Some(ribs) = ribs {
2152 assert!(ignore_import.is_none());
2153 self.resolve_ident_in_lexical_scope(
2154 ident,
2155 ValueNS,
2156 parent_scope,
2157 None,
2158 &ribs[ValueNS],
2159 ignore_binding,
2160 )
2161 } else {
2162 None
2163 };
2164 let match_span = match binding {
2165 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
2174 Some(*self.pat_span_map.get(&id).unwrap())
2175 }
2176 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
2188 _ => None,
2189 };
2190 let suggestion = match_span.map(|span| {
2191 (
2192 vec![(span, String::from(""))],
2193 format!("`{ident}` is defined here, but is not a type"),
2194 Applicability::MaybeIncorrect,
2195 )
2196 });
2197
2198 (format!("use of undeclared type `{ident}`"), suggestion)
2199 } else {
2200 let mut suggestion = None;
2201 if ident.name == sym::alloc {
2202 suggestion = Some((
2203 vec![],
2204 String::from("add `extern crate alloc` to use the `alloc` crate"),
2205 Applicability::MaybeIncorrect,
2206 ))
2207 }
2208
2209 suggestion = suggestion.or_else(|| {
2210 self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2211 |sugg| {
2212 (
2213 vec![(ident.span, sugg.to_string())],
2214 String::from("there is a crate or module with a similar name"),
2215 Applicability::MaybeIncorrect,
2216 )
2217 },
2218 )
2219 });
2220 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
2221 ident,
2222 ScopeSet::All(ValueNS),
2223 parent_scope,
2224 None,
2225 false,
2226 ignore_binding,
2227 ignore_import,
2228 ) {
2229 let descr = binding.res().descr();
2230 (format!("{descr} `{ident}` is not a crate or module"), suggestion)
2231 } else {
2232 let suggestion = if suggestion.is_some() {
2233 suggestion
2234 } else if was_invoked_from_cargo() {
2235 Some((
2236 vec![],
2237 format!(
2238 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2239 to add it to your `Cargo.toml`",
2240 ),
2241 Applicability::MaybeIncorrect,
2242 ))
2243 } else {
2244 Some((
2245 vec![],
2246 format!("you might be missing a crate named `{ident}`",),
2247 Applicability::MaybeIncorrect,
2248 ))
2249 };
2250 (format!("use of unresolved module or unlinked crate `{ident}`"), suggestion)
2251 }
2252 }
2253 }
2254
2255 #[instrument(level = "debug", skip(self, parent_scope))]
2257 pub(crate) fn make_path_suggestion(
2258 &mut self,
2259 mut path: Vec<Segment>,
2260 parent_scope: &ParentScope<'ra>,
2261 ) -> Option<(Vec<Segment>, Option<String>)> {
2262 match path[..] {
2263 [first, second, ..]
2266 if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2267 [first, ..]
2269 if first.ident.span.at_least_rust_2018()
2270 && !first.ident.is_path_segment_keyword() =>
2271 {
2272 path.insert(0, Segment::from_ident(Ident::dummy()));
2274 }
2275 _ => return None,
2276 }
2277
2278 self.make_missing_self_suggestion(path.clone(), parent_scope)
2279 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2280 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2281 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2282 }
2283
2284 #[instrument(level = "debug", skip(self, parent_scope))]
2292 fn make_missing_self_suggestion(
2293 &mut self,
2294 mut path: Vec<Segment>,
2295 parent_scope: &ParentScope<'ra>,
2296 ) -> Option<(Vec<Segment>, Option<String>)> {
2297 path[0].ident.name = kw::SelfLower;
2299 let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2300 debug!(?path, ?result);
2301 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2302 }
2303
2304 #[instrument(level = "debug", skip(self, parent_scope))]
2312 fn make_missing_crate_suggestion(
2313 &mut self,
2314 mut path: Vec<Segment>,
2315 parent_scope: &ParentScope<'ra>,
2316 ) -> Option<(Vec<Segment>, Option<String>)> {
2317 path[0].ident.name = kw::Crate;
2319 let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2320 debug!(?path, ?result);
2321 if let PathResult::Module(..) = result {
2322 Some((
2323 path,
2324 Some(
2325 "`use` statements changed in Rust 2018; read more at \
2326 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2327 clarity.html>"
2328 .to_string(),
2329 ),
2330 ))
2331 } else {
2332 None
2333 }
2334 }
2335
2336 #[instrument(level = "debug", skip(self, parent_scope))]
2344 fn make_missing_super_suggestion(
2345 &mut self,
2346 mut path: Vec<Segment>,
2347 parent_scope: &ParentScope<'ra>,
2348 ) -> Option<(Vec<Segment>, Option<String>)> {
2349 path[0].ident.name = kw::Super;
2351 let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2352 debug!(?path, ?result);
2353 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2354 }
2355
2356 #[instrument(level = "debug", skip(self, parent_scope))]
2367 fn make_external_crate_suggestion(
2368 &mut self,
2369 mut path: Vec<Segment>,
2370 parent_scope: &ParentScope<'ra>,
2371 ) -> Option<(Vec<Segment>, Option<String>)> {
2372 if path[1].ident.span.is_rust_2015() {
2373 return None;
2374 }
2375
2376 let mut extern_crate_names =
2380 self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2381 extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
2382
2383 for name in extern_crate_names.into_iter() {
2384 path[0].ident.name = name;
2386 let result = self.maybe_resolve_path(&path, None, parent_scope, None);
2387 debug!(?path, ?name, ?result);
2388 if let PathResult::Module(..) = result {
2389 return Some((path, None));
2390 }
2391 }
2392
2393 None
2394 }
2395
2396 pub(crate) fn check_for_module_export_macro(
2409 &mut self,
2410 import: Import<'ra>,
2411 module: ModuleOrUniformRoot<'ra>,
2412 ident: Ident,
2413 ) -> Option<(Option<Suggestion>, Option<String>)> {
2414 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2415 return None;
2416 };
2417
2418 while let Some(parent) = crate_module.parent {
2419 crate_module = parent;
2420 }
2421
2422 if module == ModuleOrUniformRoot::Module(crate_module) {
2423 return None;
2425 }
2426
2427 let resolutions = self.resolutions(crate_module).borrow();
2428 let binding_key = BindingKey::new(ident, MacroNS);
2429 let resolution = resolutions.get(&binding_key)?;
2430 let binding = resolution.borrow().binding()?;
2431 let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() else {
2432 return None;
2433 };
2434 let module_name = crate_module.kind.name().unwrap_or(kw::Empty);
2435 let import_snippet = match import.kind {
2436 ImportKind::Single { source, target, .. } if source != target => {
2437 format!("{source} as {target}")
2438 }
2439 _ => format!("{ident}"),
2440 };
2441
2442 let mut corrections: Vec<(Span, String)> = Vec::new();
2443 if !import.is_nested() {
2444 corrections.push((import.span, format!("{module_name}::{import_snippet}")));
2447 } else {
2448 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2452 self.tcx.sess,
2453 import.span,
2454 import.use_span,
2455 );
2456 debug!(found_closing_brace, ?binding_span);
2457
2458 let mut removal_span = binding_span;
2459
2460 if found_closing_brace
2468 && let Some(previous_span) =
2469 extend_span_to_previous_binding(self.tcx.sess, binding_span)
2470 {
2471 debug!(?previous_span);
2472 removal_span = removal_span.with_lo(previous_span.lo());
2473 }
2474 debug!(?removal_span);
2475
2476 corrections.push((removal_span, "".to_string()));
2478
2479 let (has_nested, after_crate_name) =
2486 find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
2487 debug!(has_nested, ?after_crate_name);
2488
2489 let source_map = self.tcx.sess.source_map();
2490
2491 let is_definitely_crate = import
2493 .module_path
2494 .first()
2495 .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
2496
2497 let start_point = source_map.start_point(after_crate_name);
2499 if is_definitely_crate
2500 && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
2501 {
2502 corrections.push((
2503 start_point,
2504 if has_nested {
2505 format!("{start_snippet}{import_snippet}, ")
2507 } else {
2508 format!("{{{import_snippet}, {start_snippet}")
2511 },
2512 ));
2513
2514 if !has_nested {
2516 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2517 }
2518 } else {
2519 corrections.push((
2521 import.use_span.shrink_to_lo(),
2522 format!("use {module_name}::{import_snippet};\n"),
2523 ));
2524 }
2525 }
2526
2527 let suggestion = Some((
2528 corrections,
2529 String::from("a macro with this name exists at the root of the crate"),
2530 Applicability::MaybeIncorrect,
2531 ));
2532 Some((
2533 suggestion,
2534 Some(
2535 "this could be because a macro annotated with `#[macro_export]` will be exported \
2536 at the root of the crate instead of the module where it is defined"
2537 .to_string(),
2538 ),
2539 ))
2540 }
2541
2542 pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
2544 let local_items;
2545 let symbols = if module.is_local() {
2546 local_items = self
2547 .stripped_cfg_items
2548 .iter()
2549 .filter_map(|item| {
2550 let parent_module = self.opt_local_def_id(item.parent_module)?.to_def_id();
2551 Some(StrippedCfgItem {
2552 parent_module,
2553 ident: item.ident,
2554 cfg: item.cfg.clone(),
2555 })
2556 })
2557 .collect::<Vec<_>>();
2558 local_items.as_slice()
2559 } else {
2560 self.tcx.stripped_cfg_items(module.krate)
2561 };
2562
2563 for &StrippedCfgItem { parent_module, ident, ref cfg } in symbols {
2564 if parent_module != module || ident.name != *segment {
2565 continue;
2566 }
2567
2568 let note = errors::FoundItemConfigureOut { span: ident.span };
2569 err.subdiagnostic(note);
2570
2571 if let MetaItemKind::List(nested) = &cfg.kind
2572 && let MetaItemInner::MetaItem(meta_item) = &nested[0]
2573 && let MetaItemKind::NameValue(feature_name) = &meta_item.kind
2574 {
2575 let note = errors::ItemWasBehindFeature {
2576 feature: feature_name.symbol,
2577 span: meta_item.span,
2578 };
2579 err.subdiagnostic(note);
2580 } else {
2581 let note = errors::ItemWasCfgOut { span: cfg.span };
2582 err.subdiagnostic(note);
2583 }
2584 }
2585 }
2586}
2587
2588fn find_span_of_binding_until_next_binding(
2602 sess: &Session,
2603 binding_span: Span,
2604 use_span: Span,
2605) -> (bool, Span) {
2606 let source_map = sess.source_map();
2607
2608 let binding_until_end = binding_span.with_hi(use_span.hi());
2611
2612 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2615
2616 let mut found_closing_brace = false;
2623 let after_binding_until_next_binding =
2624 source_map.span_take_while(after_binding_until_end, |&ch| {
2625 if ch == '}' {
2626 found_closing_brace = true;
2627 }
2628 ch == ' ' || ch == ','
2629 });
2630
2631 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2636
2637 (found_closing_brace, span)
2638}
2639
2640fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2653 let source_map = sess.source_map();
2654
2655 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2659
2660 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2661 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2662 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2663 return None;
2664 }
2665
2666 let prev_comma = prev_comma.first().unwrap();
2667 let prev_starting_brace = prev_starting_brace.first().unwrap();
2668
2669 if prev_comma.len() > prev_starting_brace.len() {
2673 return None;
2674 }
2675
2676 Some(binding_span.with_lo(BytePos(
2677 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2680 )))
2681}
2682
2683#[instrument(level = "debug", skip(sess))]
2697fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
2698 let source_map = sess.source_map();
2699
2700 let mut num_colons = 0;
2702 let until_second_colon = source_map.span_take_while(use_span, |c| {
2704 if *c == ':' {
2705 num_colons += 1;
2706 }
2707 !matches!(c, ':' if num_colons == 2)
2708 });
2709 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2711
2712 let mut found_a_non_whitespace_character = false;
2713 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2715 if found_a_non_whitespace_character {
2716 return false;
2717 }
2718 if !c.is_whitespace() {
2719 found_a_non_whitespace_character = true;
2720 }
2721 true
2722 });
2723
2724 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2726
2727 (next_left_bracket == after_second_colon, from_second_colon)
2728}
2729
2730enum Instead {
2733 Yes,
2734 No,
2735}
2736
2737enum FoundUse {
2739 Yes,
2740 No,
2741}
2742
2743pub(crate) enum DiagMode {
2745 Normal,
2746 Pattern,
2748 Import {
2750 unresolved_import: bool,
2752 append: bool,
2755 },
2756}
2757
2758pub(crate) fn import_candidates(
2759 tcx: TyCtxt<'_>,
2760 err: &mut Diag<'_>,
2761 use_placement_span: Option<Span>,
2763 candidates: &[ImportSuggestion],
2764 mode: DiagMode,
2765 append: &str,
2766) {
2767 show_candidates(
2768 tcx,
2769 err,
2770 use_placement_span,
2771 candidates,
2772 Instead::Yes,
2773 FoundUse::Yes,
2774 mode,
2775 vec![],
2776 append,
2777 );
2778}
2779
2780type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
2781
2782fn show_candidates(
2787 tcx: TyCtxt<'_>,
2788 err: &mut Diag<'_>,
2789 use_placement_span: Option<Span>,
2791 candidates: &[ImportSuggestion],
2792 instead: Instead,
2793 found_use: FoundUse,
2794 mode: DiagMode,
2795 path: Vec<Segment>,
2796 append: &str,
2797) -> bool {
2798 if candidates.is_empty() {
2799 return false;
2800 }
2801
2802 let mut showed = false;
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 showed = true;
2962 }
2963 if !inaccessible_path_strings.is_empty()
2964 && (!matches!(mode, DiagMode::Import { unresolved_import: false, .. }))
2965 {
2966 let prefix =
2967 if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
2968 if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
2969 let msg = format!(
2970 "{prefix}{descr} `{name}`{} exists but is inaccessible",
2971 if let DiagMode::Pattern = mode { ", which" } else { "" }
2972 );
2973
2974 if let Some(source_span) = source_span {
2975 let span = tcx.sess.source_map().guess_head_span(*source_span);
2976 let mut multi_span = MultiSpan::from_span(span);
2977 multi_span.push_span_label(span, "not accessible");
2978 err.span_note(multi_span, msg);
2979 } else {
2980 err.note(msg);
2981 }
2982 if let Some(note) = (*note).as_deref() {
2983 err.note(note.to_string());
2984 }
2985 } else {
2986 let (_, descr_first, _, _, _) = &inaccessible_path_strings[0];
2987 let descr = if inaccessible_path_strings
2988 .iter()
2989 .skip(1)
2990 .all(|(_, descr, _, _, _)| descr == descr_first)
2991 {
2992 descr_first
2993 } else {
2994 "item"
2995 };
2996 let plural_descr =
2997 if descr.ends_with('s') { format!("{descr}es") } else { format!("{descr}s") };
2998
2999 let mut msg = format!("{prefix}these {plural_descr} exist but are inaccessible");
3000 let mut has_colon = false;
3001
3002 let mut spans = Vec::new();
3003 for (name, _, source_span, _, _) in &inaccessible_path_strings {
3004 if let Some(source_span) = source_span {
3005 let span = tcx.sess.source_map().guess_head_span(*source_span);
3006 spans.push((name, span));
3007 } else {
3008 if !has_colon {
3009 msg.push(':');
3010 has_colon = true;
3011 }
3012 msg.push('\n');
3013 msg.push_str(name);
3014 }
3015 }
3016
3017 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3018 for (name, span) in spans {
3019 multi_span.push_span_label(span, format!("`{name}`: not accessible"));
3020 }
3021
3022 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3023 err.note(note.clone());
3024 }
3025
3026 err.span_note(multi_span, msg);
3027 }
3028 showed = true;
3029 }
3030 showed
3031}
3032
3033#[derive(Debug)]
3034struct UsePlacementFinder {
3035 target_module: NodeId,
3036 first_legal_span: Option<Span>,
3037 first_use_span: Option<Span>,
3038}
3039
3040impl UsePlacementFinder {
3041 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3042 let mut finder =
3043 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3044 finder.visit_crate(krate);
3045 if let Some(use_span) = finder.first_use_span {
3046 (Some(use_span), FoundUse::Yes)
3047 } else {
3048 (finder.first_legal_span, FoundUse::No)
3049 }
3050 }
3051}
3052
3053impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
3054 fn visit_crate(&mut self, c: &Crate) {
3055 if self.target_module == CRATE_NODE_ID {
3056 let inject = c.spans.inject_use_span;
3057 if is_span_suitable_for_use_injection(inject) {
3058 self.first_legal_span = Some(inject);
3059 }
3060 self.first_use_span = search_for_any_use_in_items(&c.items);
3061 } else {
3062 visit::walk_crate(self, c);
3063 }
3064 }
3065
3066 fn visit_item(&mut self, item: &'tcx ast::Item) {
3067 if self.target_module == item.id {
3068 if let ItemKind::Mod(_, _, ModKind::Loaded(items, _inline, mod_spans, _)) = &item.kind {
3069 let inject = mod_spans.inject_use_span;
3070 if is_span_suitable_for_use_injection(inject) {
3071 self.first_legal_span = Some(inject);
3072 }
3073 self.first_use_span = search_for_any_use_in_items(items);
3074 }
3075 } else {
3076 visit::walk_item(self, item);
3077 }
3078 }
3079}
3080
3081fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
3082 for item in items {
3083 if let ItemKind::Use(..) = item.kind
3084 && is_span_suitable_for_use_injection(item.span)
3085 {
3086 let mut lo = item.span.lo();
3087 for attr in &item.attrs {
3088 if attr.span.eq_ctxt(item.span) {
3089 lo = std::cmp::min(lo, attr.span.lo());
3090 }
3091 }
3092 return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3093 }
3094 }
3095 None
3096}
3097
3098fn is_span_suitable_for_use_injection(s: Span) -> bool {
3099 !s.from_expansion()
3102}