1use std::ops::ControlFlow;
3
4use itertools::Itertools as _;
5use rustc_ast::visit::{self, Visitor};
6use rustc_ast::{
7 self as ast, CRATE_NODE_ID, Crate, ItemKind, ModKind, NodeId, Path, join_path_idents,
8};
9use rustc_ast_pretty::pprust;
10use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11use rustc_data_structures::unord::{UnordMap, UnordSet};
12use rustc_errors::codes::*;
13use rustc_errors::{
14 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, MultiSpan, SuggestionStyle,
15 struct_span_code_err,
16};
17use rustc_feature::BUILTIN_ATTRIBUTES;
18use rustc_hir::attrs::{CfgEntry, StrippedCfgItem};
19use rustc_hir::def::Namespace::{self, *};
20use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, MacroKinds, NonMacroAttrKind, PerNS};
21use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
22use rustc_hir::{PrimTy, Stability, StabilityLevel, find_attr};
23use rustc_middle::bug;
24use rustc_middle::ty::TyCtxt;
25use rustc_session::Session;
26use rustc_session::lint::BuiltinLintDiag;
27use rustc_session::lint::builtin::{
28 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS, AMBIGUOUS_IMPORT_VISIBILITIES,
29 AMBIGUOUS_PANIC_IMPORTS, MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
30};
31use rustc_session::utils::was_invoked_from_cargo;
32use rustc_span::edit_distance::find_best_match_for_name;
33use rustc_span::edition::Edition;
34use rustc_span::hygiene::MacroKind;
35use rustc_span::source_map::SourceMap;
36use rustc_span::{
37 BytePos, Ident, RemapPathScopeComponents, Span, Spanned, Symbol, SyntaxContext, kw, sym,
38};
39use thin_vec::{ThinVec, thin_vec};
40use tracing::{debug, instrument};
41
42use crate::errors::{
43 self, AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion, ConsiderAddingADerive,
44 ExplicitUnsafeTraits, MacroDefinedLater, MacroRulesNot, MacroSuggMovePosition,
45 MaybeMissingMacroRulesName,
46};
47use crate::hygiene::Macros20NormalizedSyntaxContext;
48use crate::imports::{Import, ImportKind};
49use crate::late::{DiagMetadata, PatternSource, Rib};
50use crate::{
51 AmbiguityError, AmbiguityKind, AmbiguityWarning, BindingError, BindingKey, Decl, DeclKind,
52 Finalize, ForwardGenericParamBanReason, HasGenericParams, IdentKey, LateDecl, MacroRulesScope,
53 Module, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, PrivacyError,
54 ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used, VisResolutionError,
55 errors as errs, path_names_to_string,
56};
57
58type Res = def::Res<ast::NodeId>;
59
60pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
62
63pub(crate) type LabelSuggestion = (Ident, bool);
66
67#[derive(#[automatically_derived]
impl ::core::fmt::Debug for SuggestionTarget {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
SuggestionTarget::SimilarlyNamed => "SimilarlyNamed",
SuggestionTarget::SingleItem => "SingleItem",
})
}
}Debug)]
68pub(crate) enum SuggestionTarget {
69 SimilarlyNamed,
71 SingleItem,
73}
74
75#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TypoSuggestion {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"TypoSuggestion", "candidate", &self.candidate, "span",
&self.span, "res", &self.res, "target", &&self.target)
}
}Debug)]
76pub(crate) struct TypoSuggestion {
77 pub candidate: Symbol,
78 pub span: Option<Span>,
81 pub res: Res,
82 pub target: SuggestionTarget,
83}
84
85impl TypoSuggestion {
86 pub(crate) fn new(candidate: Symbol, span: Span, res: Res) -> TypoSuggestion {
87 Self { candidate, span: Some(span), res, target: SuggestionTarget::SimilarlyNamed }
88 }
89 pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
90 Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
91 }
92 pub(crate) fn single_item(candidate: Symbol, span: Span, res: Res) -> TypoSuggestion {
93 Self { candidate, span: Some(span), res, target: SuggestionTarget::SingleItem }
94 }
95}
96
97#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ImportSuggestion {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["did", "descr", "path", "accessible", "doc_visible",
"via_import", "note", "is_stable"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.did, &self.descr, &self.path, &self.accessible,
&self.doc_visible, &self.via_import, &self.note,
&&self.is_stable];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"ImportSuggestion", names, values)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for ImportSuggestion {
#[inline]
fn clone(&self) -> ImportSuggestion {
ImportSuggestion {
did: ::core::clone::Clone::clone(&self.did),
descr: ::core::clone::Clone::clone(&self.descr),
path: ::core::clone::Clone::clone(&self.path),
accessible: ::core::clone::Clone::clone(&self.accessible),
doc_visible: ::core::clone::Clone::clone(&self.doc_visible),
via_import: ::core::clone::Clone::clone(&self.via_import),
note: ::core::clone::Clone::clone(&self.note),
is_stable: ::core::clone::Clone::clone(&self.is_stable),
}
}
}Clone)]
99pub(crate) struct ImportSuggestion {
100 pub did: Option<DefId>,
101 pub descr: &'static str,
102 pub path: Path,
103 pub accessible: bool,
104 pub doc_visible: bool,
106 pub via_import: bool,
107 pub note: Option<String>,
109 pub is_stable: bool,
110}
111
112fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
120 let impl_span = sm.span_until_char(impl_span, '<');
121 sm.span_until_whitespace(impl_span)
122}
123
124impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
125 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
126 self.tcx.dcx()
127 }
128
129 pub(crate) fn report_errors(&mut self, krate: &Crate) {
130 self.report_with_use_injections(krate);
131
132 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
133 self.lint_buffer.buffer_lint(
134 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
135 CRATE_NODE_ID,
136 span_use,
137 errors::MacroExpandedMacroExportsAccessedByAbsolutePaths { definition: span_def },
138 );
139 }
140
141 for ambiguity_error in &self.ambiguity_errors {
142 let mut diag = self.ambiguity_diagnostic(ambiguity_error);
143
144 if let Some(ambiguity_warning) = ambiguity_error.warning {
145 let node_id = match ambiguity_error.b1.0.kind {
146 DeclKind::Import { import, .. } => import.root_id,
147 DeclKind::Def(_) => CRATE_NODE_ID,
148 };
149
150 let lint = match ambiguity_warning {
151 _ if ambiguity_error.ambig_vis.is_some() => AMBIGUOUS_IMPORT_VISIBILITIES,
152 AmbiguityWarning::GlobImport => AMBIGUOUS_GLOB_IMPORTS,
153 AmbiguityWarning::PanicImport => AMBIGUOUS_PANIC_IMPORTS,
154 };
155
156 self.lint_buffer.buffer_lint(lint, node_id, diag.ident.span, diag);
157 } else {
158 diag.is_error = true;
159 self.dcx().emit_err(diag);
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 ident: IdentKey,
210 ns: Namespace,
211 old_binding: Decl<'ra>,
212 new_binding: Decl<'ra>,
213 ) {
214 if old_binding.span.lo() > new_binding.span.lo() {
216 return self.report_conflict(ident, ns, new_binding, old_binding);
217 }
218
219 let container = match old_binding.parent_module.unwrap().kind {
220 ModuleKind::Def(kind, def_id, _) => kind.descr(def_id),
223 ModuleKind::Block => "block",
224 };
225
226 let (name, span) =
227 (ident.name, self.tcx.sess.source_map().guess_head_span(new_binding.span));
228
229 if self.name_already_seen.get(&name) == Some(&span) {
230 return;
231 }
232
233 let old_kind = match (ns, old_binding.res()) {
234 (ValueNS, _) => "value",
235 (MacroNS, _) => "macro",
236 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
237 (TypeNS, Res::Def(DefKind::Mod, _)) => "module",
238 (TypeNS, Res::Def(DefKind::Trait, _)) => "trait",
239 (TypeNS, _) => "type",
240 };
241
242 let code = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
243 (true, true) => E0259,
244 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
245 true => E0254,
246 false => E0260,
247 },
248 _ => match (old_binding.is_import_user_facing(), new_binding.is_import_user_facing()) {
249 (false, false) => E0428,
250 (true, true) => E0252,
251 _ => E0255,
252 },
253 };
254
255 let label = match new_binding.is_import_user_facing() {
256 true => errors::NameDefinedMultipleTimeLabel::Reimported { span, name },
257 false => errors::NameDefinedMultipleTimeLabel::Redefined { span, name },
258 };
259
260 let old_binding_label =
261 (!old_binding.span.is_dummy() && old_binding.span != span).then(|| {
262 let span = self.tcx.sess.source_map().guess_head_span(old_binding.span);
263 match old_binding.is_import_user_facing() {
264 true => errors::NameDefinedMultipleTimeOldBindingLabel::Import {
265 span,
266 old_kind,
267 name,
268 },
269 false => errors::NameDefinedMultipleTimeOldBindingLabel::Definition {
270 span,
271 old_kind,
272 name,
273 },
274 }
275 });
276
277 let mut err = self
278 .dcx()
279 .create_err(errors::NameDefinedMultipleTime {
280 span,
281 name,
282 descr: ns.descr(),
283 container,
284 label,
285 old_binding_label,
286 })
287 .with_code(code);
288
289 use DeclKind::Import;
291 let can_suggest = |binding: Decl<'_>, import: self::Import<'_>| {
292 !binding.span.is_dummy()
293 && !#[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::MacroUse { .. } | ImportKind::MacroExport => true,
_ => false,
}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 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Other{0}", name))
})format!("Other{name}")
372 } else {
373 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("other_{0}", name))
})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(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self as {0}", suggested_name))
})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(::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", suggested_name))
})format!(" as {suggested_name}"));
391 }
392 }
393 ImportKind::ExternCrate { source, target, .. } => {
394 suggestion = Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern crate {0} as {1};",
source.unwrap_or(target.name), suggested_name))
})format!(
395 "extern crate {} as {};",
396 source.unwrap_or(target.name),
397 suggested_name,
398 ))
399 }
400 _ => ::core::panicking::panic("internal error: entered unreachable code")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 if !import.is_nested() {
::core::panicking::panic("assertion failed: import.is_nested()")
};assert!(import.is_nested());
439
440 let (found_closing_brace, span) =
448 find_span_of_binding_until_next_binding(self.tcx.sess, binding_span, import.use_span);
449
450 if found_closing_brace {
453 if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) {
454 err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport { span });
455 } else {
456 err.subdiagnostic(errors::RemoveUnnecessaryImport {
459 span: import.use_span_with_attributes,
460 });
461 }
462
463 return;
464 }
465
466 err.subdiagnostic(errors::RemoveUnnecessaryImport { span });
467 }
468
469 pub(crate) fn lint_if_path_starts_with_module(
470 &mut self,
471 finalize: Finalize,
472 path: &[Segment],
473 second_binding: Option<Decl<'_>>,
474 ) {
475 let Finalize { node_id, root_span, .. } = finalize;
476
477 let first_name = match path.get(0) {
478 Some(seg) if seg.ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015() => {
480 seg.ident.name
481 }
482 _ => return,
483 };
484
485 if first_name != kw::PathRoot {
488 return;
489 }
490
491 match path.get(1) {
492 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
494 Some(_) => {}
496 None => return,
500 }
501
502 if let Some(binding) = second_binding
506 && let DeclKind::Import { import, .. } = binding.kind
507 && let ImportKind::ExternCrate { source: None, .. } = import.kind
509 {
510 return;
511 }
512
513 let diag = BuiltinLintDiag::AbsPathWithModule(root_span);
514 self.lint_buffer.buffer_lint(
515 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
516 node_id,
517 root_span,
518 diag,
519 );
520 }
521
522 pub(crate) fn add_module_candidates(
523 &self,
524 module: Module<'ra>,
525 names: &mut Vec<TypoSuggestion>,
526 filter_fn: &impl Fn(Res) -> bool,
527 ctxt: Option<SyntaxContext>,
528 ) {
529 module.for_each_child(self, |_this, ident, orig_ident_span, _ns, binding| {
530 let res = binding.res();
531 if filter_fn(res) && ctxt.is_none_or(|ctxt| ctxt == *ident.ctxt) {
532 names.push(TypoSuggestion::new(ident.name, orig_ident_span, res));
533 }
534 });
535 }
536
537 pub(crate) fn report_error(
542 &mut self,
543 span: Span,
544 resolution_error: ResolutionError<'ra>,
545 ) -> ErrorGuaranteed {
546 self.into_struct_error(span, resolution_error).emit()
547 }
548
549 pub(crate) fn into_struct_error(
550 &mut self,
551 span: Span,
552 resolution_error: ResolutionError<'ra>,
553 ) -> Diag<'_> {
554 match resolution_error {
555 ResolutionError::GenericParamsFromOuterItem {
556 outer_res,
557 has_generic_params,
558 def_kind,
559 inner_item,
560 current_self_ty,
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 { .. } => {
568 Some(errs::GenericParamsFromOuterItemStaticOrConst::Const)
569 }
570 _ => None,
571 };
572 let is_self =
573 #[allow(non_exhaustive_omitted_patterns)] match outer_res {
Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => true,
_ => false,
}matches!(outer_res, Res::SelfTyParam { .. } | Res::SelfTyAlias { .. });
574 let mut err = errs::GenericParamsFromOuterItem {
575 span,
576 label: None,
577 refer_to_type_directly: None,
578 sugg: None,
579 static_or_const,
580 is_self,
581 item: inner_item.as_ref().map(|(span, kind)| {
582 errs::GenericParamsFromOuterItemInnerItem {
583 span: *span,
584 descr: kind.descr().to_string(),
585 is_self,
586 }
587 }),
588 };
589
590 let sm = self.tcx.sess.source_map();
591 let def_id = match outer_res {
592 Res::SelfTyParam { .. } => {
593 err.label = Some(Label::SelfTyParam(span));
594 return self.dcx().create_err(err);
595 }
596 Res::SelfTyAlias { alias_to: def_id, .. } => {
597 err.label = Some(Label::SelfTyAlias(reduce_impl_span_to_impl_keyword(
598 sm,
599 self.def_span(def_id),
600 )));
601 err.refer_to_type_directly =
602 current_self_ty.map(|snippet| errs::UseTypeDirectly { span, snippet });
603 return self.dcx().create_err(err);
604 }
605 Res::Def(DefKind::TyParam, def_id) => {
606 err.label = Some(Label::TyParam(self.def_span(def_id)));
607 def_id
608 }
609 Res::Def(DefKind::ConstParam, def_id) => {
610 err.label = Some(Label::ConstParam(self.def_span(def_id)));
611 def_id
612 }
613 _ => {
614 ::rustc_middle::util::bug::bug_fmt(format_args!("GenericParamsFromOuterItem should only be used with Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or DefKind::ConstParam"));bug!(
615 "GenericParamsFromOuterItem should only be used with \
616 Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
617 DefKind::ConstParam"
618 );
619 }
620 };
621
622 if let HasGenericParams::Yes(span) = has_generic_params
623 && !#[allow(non_exhaustive_omitted_patterns)] match inner_item {
Some((_, ItemKind::Delegation(..))) => true,
_ => false,
}matches!(inner_item, Some((_, ItemKind::Delegation(..))))
624 {
625 let name = self.tcx.item_name(def_id);
626 let (span, snippet) = if span.is_empty() {
627 let snippet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", name))
})format!("<{name}>");
628 (span, snippet)
629 } else {
630 let span = sm.span_through_char(span, '<').shrink_to_hi();
631 let snippet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", name))
})format!("{name}, ");
632 (span, snippet)
633 };
634 err.sugg = Some(errs::GenericParamsFromOuterItemSugg { span, snippet });
635 }
636
637 self.dcx().create_err(err)
638 }
639 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
640 .dcx()
641 .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
642 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
643 self.dcx().create_err(errs::MethodNotMemberOfTrait {
644 span,
645 method,
646 trait_,
647 sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
648 span: method.span,
649 candidate: c,
650 }),
651 })
652 }
653 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
654 self.dcx().create_err(errs::TypeNotMemberOfTrait {
655 span,
656 type_,
657 trait_,
658 sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
659 span: type_.span,
660 candidate: c,
661 }),
662 })
663 }
664 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
665 self.dcx().create_err(errs::ConstNotMemberOfTrait {
666 span,
667 const_,
668 trait_,
669 sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
670 span: const_.span,
671 candidate: c,
672 }),
673 })
674 }
675 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
676 let BindingError { name, target, origin, could_be_path } = binding_error;
677
678 let mut target_sp = target.iter().map(|pat| pat.span).collect::<Vec<_>>();
679 target_sp.sort();
680 target_sp.dedup();
681 let mut origin_sp = origin.iter().map(|(span, _)| *span).collect::<Vec<_>>();
682 origin_sp.sort();
683 origin_sp.dedup();
684
685 let msp = MultiSpan::from_spans(target_sp.clone());
686 let mut err = self
687 .dcx()
688 .create_err(errors::VariableIsNotBoundInAllPatterns { multispan: msp, name });
689 for sp in target_sp {
690 err.subdiagnostic(errors::PatternDoesntBindName { span: sp, name });
691 }
692 for sp in &origin_sp {
693 err.subdiagnostic(errors::VariableNotInAllPatterns { span: *sp });
694 }
695 let mut suggested_typo = false;
696 if !target.iter().all(|pat| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
ast::PatKind::Ident(..) => true,
_ => false,
}matches!(pat.kind, ast::PatKind::Ident(..)))
697 && !origin.iter().all(|(_, pat)| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
ast::PatKind::Ident(..) => true,
_ => false,
}matches!(pat.kind, ast::PatKind::Ident(..)))
698 {
699 let mut target_visitor = BindingVisitor::default();
702 for pat in &target {
703 target_visitor.visit_pat(pat);
704 }
705 target_visitor.identifiers.sort();
706 target_visitor.identifiers.dedup();
707 let mut origin_visitor = BindingVisitor::default();
708 for (_, pat) in &origin {
709 origin_visitor.visit_pat(pat);
710 }
711 origin_visitor.identifiers.sort();
712 origin_visitor.identifiers.dedup();
713 if let Some(typo) =
715 find_best_match_for_name(&target_visitor.identifiers, name.name, None)
716 && !origin_visitor.identifiers.contains(&typo)
717 {
718 err.subdiagnostic(errors::PatternBindingTypo { spans: origin_sp, typo });
719 suggested_typo = true;
720 }
721 }
722 if could_be_path {
723 let import_suggestions = self.lookup_import_candidates(
724 name,
725 Namespace::ValueNS,
726 &parent_scope,
727 &|res: Res| {
728 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Const) |
DefKind::Ctor(CtorOf::Struct, CtorKind::Const) | DefKind::Const { .. }
| DefKind::AssocConst { .. }, _) => true,
_ => false,
}matches!(
729 res,
730 Res::Def(
731 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
732 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
733 | DefKind::Const { .. }
734 | DefKind::AssocConst { .. },
735 _,
736 )
737 )
738 },
739 );
740
741 if import_suggestions.is_empty() && !suggested_typo {
742 let kind_matches: [fn(DefKind) -> bool; 4] = [
743 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => true,
_ => false,
}matches!(kind, DefKind::Ctor(CtorOf::Variant, CtorKind::Const)),
744 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => true,
_ => false,
}matches!(kind, DefKind::Ctor(CtorOf::Struct, CtorKind::Const)),
745 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Const { .. } => true,
_ => false,
}matches!(kind, DefKind::Const { .. }),
746 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::AssocConst { .. } => true,
_ => false,
}matches!(kind, DefKind::AssocConst { .. }),
747 ];
748 let mut local_names = ::alloc::vec::Vec::new()vec![];
749 self.add_module_candidates(
750 parent_scope.module,
751 &mut local_names,
752 &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(_, _) => true,
_ => false,
}matches!(res, Res::Def(_, _)),
753 None,
754 );
755 let local_names: FxHashSet<_> = local_names
756 .into_iter()
757 .filter_map(|s| match s.res {
758 Res::Def(_, def_id) => Some(def_id),
759 _ => None,
760 })
761 .collect();
762
763 let mut local_suggestions = ::alloc::vec::Vec::new()vec![];
764 let mut suggestions = ::alloc::vec::Vec::new()vec![];
765 for matches_kind in kind_matches {
766 if let Some(suggestion) = self.early_lookup_typo_candidate(
767 ScopeSet::All(Namespace::ValueNS),
768 &parent_scope,
769 name,
770 &|res: Res| match res {
771 Res::Def(k, _) => matches_kind(k),
772 _ => false,
773 },
774 ) && let Res::Def(kind, mut def_id) = suggestion.res
775 {
776 if let DefKind::Ctor(_, _) = kind {
777 def_id = self.tcx.parent(def_id);
778 }
779 let kind = kind.descr(def_id);
780 if local_names.contains(&def_id) {
781 local_suggestions.push((
784 suggestion.candidate,
785 suggestion.candidate.to_string(),
786 kind,
787 ));
788 } else {
789 suggestions.push((
790 suggestion.candidate,
791 self.def_path_str(def_id),
792 kind,
793 ));
794 }
795 }
796 }
797 let suggestions = if !local_suggestions.is_empty() {
798 local_suggestions
801 } else {
802 suggestions
803 };
804 for (name, sugg, kind) in suggestions {
805 err.span_suggestion_verbose(
806 span,
807 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use the similarly named {0} `{1}`",
kind, name))
})format!(
808 "you might have meant to use the similarly named {kind} `{name}`",
809 ),
810 sugg,
811 Applicability::MaybeIncorrect,
812 );
813 suggested_typo = true;
814 }
815 }
816 if import_suggestions.is_empty() && !suggested_typo {
817 let help_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you meant to match on a unit struct, unit variant or a `const` item, consider making the path in the pattern qualified: `path::to::ModOrType::{0}`",
name))
})format!(
818 "if you meant to match on a unit struct, unit variant or a `const` \
819 item, consider making the path in the pattern qualified: \
820 `path::to::ModOrType::{name}`",
821 );
822 err.span_help(span, help_msg);
823 }
824 show_candidates(
825 self.tcx,
826 &mut err,
827 Some(span),
828 &import_suggestions,
829 Instead::No,
830 FoundUse::Yes,
831 DiagMode::Pattern,
832 ::alloc::vec::Vec::new()vec![],
833 "",
834 );
835 }
836 err
837 }
838 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
839 self.dcx().create_err(errs::VariableBoundWithDifferentMode {
840 span,
841 first_binding_span,
842 variable_name,
843 })
844 }
845 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
846 .dcx()
847 .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
848 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
849 .dcx()
850 .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
851 ResolutionError::UndeclaredLabel { name, suggestion } => {
852 let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
853 {
854 Some((ident, true)) => (
856 (
857 Some(errs::LabelWithSimilarNameReachable(ident.span)),
858 Some(errs::TryUsingSimilarlyNamedLabel {
859 span,
860 ident_name: ident.name,
861 }),
862 ),
863 None,
864 ),
865 Some((ident, false)) => (
867 (None, None),
868 Some(errs::UnreachableLabelWithSimilarNameExists {
869 ident_span: ident.span,
870 }),
871 ),
872 None => ((None, None), None),
874 };
875 self.dcx().create_err(errs::UndeclaredLabel {
876 span,
877 name,
878 sub_reachable,
879 sub_reachable_suggestion,
880 sub_unreachable,
881 })
882 }
883 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
884 let (suggestion, mpart_suggestion) = if root {
886 (None, None)
887 } else {
888 let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
891
892 let mpart_suggestion = errs::SelfImportsOnlyAllowedWithinMultipartSuggestion {
895 multipart_start: span_with_rename.shrink_to_lo(),
896 multipart_end: span_with_rename.shrink_to_hi(),
897 };
898 (Some(suggestion), Some(mpart_suggestion))
899 };
900 self.dcx().create_err(errs::SelfImportsOnlyAllowedWithin {
901 span,
902 suggestion,
903 mpart_suggestion,
904 })
905 }
906 ResolutionError::FailedToResolve { segment, label, suggestion, module, message } => {
907 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", message))
})).with_code(E0433)
}struct_span_code_err!(self.dcx(), span, E0433, "{message}");
908 err.span_label(span, label);
909
910 if let Some((suggestions, msg, applicability)) = suggestion {
911 if suggestions.is_empty() {
912 err.help(msg);
913 return err;
914 }
915 err.multipart_suggestion(msg, suggestions, applicability);
916 }
917
918 let module = match module {
919 Some(ModuleOrUniformRoot::Module(m)) if let Some(id) = m.opt_def_id() => id,
920 _ => CRATE_DEF_ID.to_def_id(),
921 };
922 self.find_cfg_stripped(&mut err, &segment, module);
923
924 err
925 }
926 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
927 self.dcx().create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
928 }
929 ResolutionError::AttemptToUseNonConstantValueInConstant {
930 ident,
931 suggestion,
932 current,
933 type_span,
934 } => {
935 let sp = self
944 .tcx
945 .sess
946 .source_map()
947 .span_extend_to_prev_str(ident.span, current, true, false);
948
949 let ((with, with_label), without) = match sp {
950 Some(sp) if !self.tcx.sess.source_map().is_multiline(sp) => {
951 let sp = sp
952 .with_lo(BytePos(sp.lo().0 - (current.len() as u32)))
953 .until(ident.span);
954 (
955 (Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
956 span: sp,
957 suggestion,
958 current,
959 type_span,
960 }), Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion {span})),
961 None,
962 )
963 }
964 _ => (
965 (None, None),
966 Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
967 ident_span: ident.span,
968 suggestion,
969 }),
970 ),
971 };
972
973 self.dcx().create_err(errs::AttemptToUseNonConstantValueInConstant {
974 span,
975 with,
976 with_label,
977 without,
978 })
979 }
980 ResolutionError::BindingShadowsSomethingUnacceptable {
981 shadowing_binding,
982 name,
983 participle,
984 article,
985 shadowed_binding,
986 shadowed_binding_span,
987 } => self.dcx().create_err(errs::BindingShadowsSomethingUnacceptable {
988 span,
989 shadowing_binding,
990 shadowed_binding,
991 article,
992 sub_suggestion: match (shadowing_binding, shadowed_binding) {
993 (
994 PatternSource::Match,
995 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
996 ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
997 _ => None,
998 },
999 shadowed_binding_span,
1000 participle,
1001 name,
1002 }),
1003 ResolutionError::ForwardDeclaredGenericParam(param, reason) => match reason {
1004 ForwardGenericParamBanReason::Default => {
1005 self.dcx().create_err(errs::ForwardDeclaredGenericParam { param, span })
1006 }
1007 ForwardGenericParamBanReason::ConstParamTy => self
1008 .dcx()
1009 .create_err(errs::ForwardDeclaredGenericInConstParamTy { param, span }),
1010 },
1011 ResolutionError::ParamInTyOfConstParam { name } => {
1012 self.dcx().create_err(errs::ParamInTyOfConstParam { span, name })
1013 }
1014 ResolutionError::ParamInNonTrivialAnonConst { is_ogca, name, param_kind: is_type } => {
1015 self.dcx().create_err(errs::ParamInNonTrivialAnonConst {
1016 span,
1017 name,
1018 param_kind: is_type,
1019 help: self.tcx.sess.is_nightly_build(),
1020 is_ogca,
1021 help_ogca: is_ogca,
1022 })
1023 }
1024 ResolutionError::ParamInEnumDiscriminant { name, param_kind: is_type } => self
1025 .dcx()
1026 .create_err(errs::ParamInEnumDiscriminant { span, name, param_kind: is_type }),
1027 ResolutionError::ForwardDeclaredSelf(reason) => match reason {
1028 ForwardGenericParamBanReason::Default => {
1029 self.dcx().create_err(errs::SelfInGenericParamDefault { span })
1030 }
1031 ForwardGenericParamBanReason::ConstParamTy => {
1032 self.dcx().create_err(errs::SelfInConstGenericTy { span })
1033 }
1034 },
1035 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
1036 let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
1037 match suggestion {
1038 Some((ident, true)) => (
1040 (
1041 Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
1042 Some(errs::UnreachableLabelSubSuggestion {
1043 span,
1044 ident_name: ident.name,
1047 }),
1048 ),
1049 None,
1050 ),
1051 Some((ident, false)) => (
1053 (None, None),
1054 Some(errs::UnreachableLabelSubLabelUnreachable {
1055 ident_span: ident.span,
1056 }),
1057 ),
1058 None => ((None, None), None),
1060 };
1061 self.dcx().create_err(errs::UnreachableLabel {
1062 span,
1063 name,
1064 definition_span,
1065 sub_suggestion,
1066 sub_suggestion_label,
1067 sub_unreachable_label,
1068 })
1069 }
1070 ResolutionError::TraitImplMismatch {
1071 name,
1072 kind,
1073 code,
1074 trait_item_span,
1075 trait_path,
1076 } => self
1077 .dcx()
1078 .create_err(errors::TraitImplMismatch {
1079 span,
1080 name,
1081 kind,
1082 trait_path,
1083 trait_item_span,
1084 })
1085 .with_code(code),
1086 ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
1087 .dcx()
1088 .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
1089 ResolutionError::InvalidAsmSym => self.dcx().create_err(errs::InvalidAsmSym { span }),
1090 ResolutionError::LowercaseSelf => self.dcx().create_err(errs::LowercaseSelf { span }),
1091 ResolutionError::BindingInNeverPattern => {
1092 self.dcx().create_err(errs::BindingInNeverPattern { span })
1093 }
1094 }
1095 }
1096
1097 pub(crate) fn report_vis_error(
1098 &mut self,
1099 vis_resolution_error: VisResolutionError<'_>,
1100 ) -> ErrorGuaranteed {
1101 match vis_resolution_error {
1102 VisResolutionError::Relative2018(span, path) => {
1103 self.dcx().create_err(errs::Relative2018 {
1104 span,
1105 path_span: path.span,
1106 path_str: pprust::path_to_string(path),
1109 })
1110 }
1111 VisResolutionError::AncestorOnly(span) => {
1112 self.dcx().create_err(errs::AncestorOnly(span))
1113 }
1114 VisResolutionError::FailedToResolve(span, segment, label, suggestion, message) => self
1115 .into_struct_error(
1116 span,
1117 ResolutionError::FailedToResolve {
1118 segment,
1119 label,
1120 suggestion,
1121 module: None,
1122 message,
1123 },
1124 ),
1125 VisResolutionError::ExpectedFound(span, path_str, res) => {
1126 self.dcx().create_err(errs::ExpectedModuleFound { span, res, path_str })
1127 }
1128 VisResolutionError::Indeterminate(span) => {
1129 self.dcx().create_err(errs::Indeterminate(span))
1130 }
1131 VisResolutionError::ModuleOnly(span) => self.dcx().create_err(errs::ModuleOnly(span)),
1132 }
1133 .emit()
1134 }
1135
1136 fn def_path_str(&self, mut def_id: DefId) -> String {
1137 let mut path = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[def_id]))vec![def_id];
1139 while let Some(parent) = self.tcx.opt_parent(def_id) {
1140 def_id = parent;
1141 path.push(def_id);
1142 if def_id.is_top_level_module() {
1143 break;
1144 }
1145 }
1146 path.into_iter()
1148 .rev()
1149 .map(|def_id| {
1150 self.tcx
1151 .opt_item_name(def_id)
1152 .map(|name| {
1153 match (
1154 def_id.is_top_level_module(),
1155 def_id.is_local(),
1156 self.tcx.sess.edition(),
1157 ) {
1158 (true, true, Edition::Edition2015) => String::new(),
1159 (true, true, _) => kw::Crate.to_string(),
1160 (true, false, _) | (false, _, _) => name.to_string(),
1161 }
1162 })
1163 .unwrap_or_else(|| "_".to_string())
1164 })
1165 .collect::<Vec<String>>()
1166 .join("::")
1167 }
1168
1169 pub(crate) fn add_scope_set_candidates(
1170 &mut self,
1171 suggestions: &mut Vec<TypoSuggestion>,
1172 scope_set: ScopeSet<'ra>,
1173 ps: &ParentScope<'ra>,
1174 sp: Span,
1175 filter_fn: &impl Fn(Res) -> bool,
1176 ) {
1177 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
1178 self.cm().visit_scopes(scope_set, ps, ctxt, sp, None, |this, scope, use_prelude, _| {
1179 match scope {
1180 Scope::DeriveHelpers(expn_id) => {
1181 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1182 if filter_fn(res) {
1183 suggestions.extend(
1184 this.helper_attrs.get(&expn_id).into_iter().flatten().map(
1185 |&(ident, orig_ident_span, _)| {
1186 TypoSuggestion::new(ident.name, orig_ident_span, res)
1187 },
1188 ),
1189 );
1190 }
1191 }
1192 Scope::DeriveHelpersCompat => {
1193 }
1195 Scope::MacroRules(macro_rules_scope) => {
1196 if let MacroRulesScope::Def(macro_rules_def) = macro_rules_scope.get() {
1197 let res = macro_rules_def.decl.res();
1198 if filter_fn(res) {
1199 suggestions.push(TypoSuggestion::new(
1200 macro_rules_def.ident.name,
1201 macro_rules_def.orig_ident_span,
1202 res,
1203 ))
1204 }
1205 }
1206 }
1207 Scope::ModuleNonGlobs(module, _) => {
1208 this.add_module_candidates(module, suggestions, filter_fn, None);
1209 }
1210 Scope::ModuleGlobs(..) => {
1211 }
1213 Scope::MacroUsePrelude => {
1214 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1215 |(name, binding)| {
1216 let res = binding.res();
1217 filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1218 },
1219 ));
1220 }
1221 Scope::BuiltinAttrs => {
1222 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(sym::dummy));
1223 if filter_fn(res) {
1224 suggestions.extend(
1225 BUILTIN_ATTRIBUTES
1226 .iter()
1227 .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1228 );
1229 }
1230 }
1231 Scope::ExternPreludeItems => {
1232 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, entry)| {
1234 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1235 filter_fn(res).then_some(TypoSuggestion::new(ident.name, entry.span(), res))
1236 }));
1237 }
1238 Scope::ExternPreludeFlags => {}
1239 Scope::ToolPrelude => {
1240 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1241 suggestions.extend(
1242 this.registered_tools
1243 .iter()
1244 .map(|ident| TypoSuggestion::new(ident.name, ident.span, res)),
1245 );
1246 }
1247 Scope::StdLibPrelude => {
1248 if let Some(prelude) = this.prelude {
1249 let mut tmp_suggestions = Vec::new();
1250 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1251 suggestions.extend(
1252 tmp_suggestions
1253 .into_iter()
1254 .filter(|s| use_prelude.into() || this.is_builtin_macro(s.res)),
1255 );
1256 }
1257 }
1258 Scope::BuiltinTypes => {
1259 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1260 let res = Res::PrimTy(*prim_ty);
1261 filter_fn(res)
1262 .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1263 }))
1264 }
1265 }
1266
1267 ControlFlow::<()>::Continue(())
1268 });
1269 }
1270
1271 fn early_lookup_typo_candidate(
1273 &mut self,
1274 scope_set: ScopeSet<'ra>,
1275 parent_scope: &ParentScope<'ra>,
1276 ident: Ident,
1277 filter_fn: &impl Fn(Res) -> bool,
1278 ) -> Option<TypoSuggestion> {
1279 let mut suggestions = Vec::new();
1280 self.add_scope_set_candidates(
1281 &mut suggestions,
1282 scope_set,
1283 parent_scope,
1284 ident.span,
1285 filter_fn,
1286 );
1287
1288 suggestions.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
1290
1291 match find_best_match_for_name(
1292 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1293 ident.name,
1294 None,
1295 ) {
1296 Some(found) if found != ident.name => {
1297 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1298 }
1299 _ => None,
1300 }
1301 }
1302
1303 fn lookup_import_candidates_from_module<FilterFn>(
1304 &self,
1305 lookup_ident: Ident,
1306 namespace: Namespace,
1307 parent_scope: &ParentScope<'ra>,
1308 start_module: Module<'ra>,
1309 crate_path: ThinVec<ast::PathSegment>,
1310 filter_fn: FilterFn,
1311 ) -> Vec<ImportSuggestion>
1312 where
1313 FilterFn: Fn(Res) -> bool,
1314 {
1315 let mut candidates = Vec::new();
1316 let mut seen_modules = FxHashSet::default();
1317 let start_did = start_module.def_id();
1318 let mut worklist = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(start_module, ThinVec::<ast::PathSegment>::new(), true,
start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
true)]))vec![(
1319 start_module,
1320 ThinVec::<ast::PathSegment>::new(),
1321 true,
1322 start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
1323 true,
1324 )];
1325 let mut worklist_via_import = ::alloc::vec::Vec::new()vec![];
1326
1327 while let Some((in_module, path_segments, accessible, doc_visible, is_stable)) =
1328 match worklist.pop() {
1329 None => worklist_via_import.pop(),
1330 Some(x) => Some(x),
1331 }
1332 {
1333 let in_module_is_extern = !in_module.def_id().is_local();
1334 in_module.for_each_child(self, |this, ident, orig_ident_span, ns, name_binding| {
1335 if name_binding.is_assoc_item()
1337 && !this.tcx.features().import_trait_associated_functions()
1338 {
1339 return;
1340 }
1341
1342 if ident.name == kw::Underscore {
1343 return;
1344 }
1345
1346 let child_accessible =
1347 accessible && this.is_accessible_from(name_binding.vis(), parent_scope.module);
1348
1349 if in_module_is_extern && !child_accessible {
1351 return;
1352 }
1353
1354 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1355
1356 if via_import && name_binding.is_possibly_imported_variant() {
1362 return;
1363 }
1364
1365 if let DeclKind::Import { source_decl, .. } = name_binding.kind
1367 && this.is_accessible_from(source_decl.vis(), parent_scope.module)
1368 && !this.is_accessible_from(name_binding.vis(), parent_scope.module)
1369 {
1370 return;
1371 }
1372
1373 let res = name_binding.res();
1374 let did = match res {
1375 Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1376 _ => res.opt_def_id(),
1377 };
1378 let child_doc_visible = doc_visible
1379 && did.is_none_or(|did| did.is_local() || !this.tcx.is_doc_hidden(did));
1380
1381 if ident.name == lookup_ident.name
1385 && ns == namespace
1386 && in_module != parent_scope.module
1387 && ident.ctxt.is_root()
1388 && filter_fn(res)
1389 {
1390 let mut segms = if lookup_ident.span.at_least_rust_2018() {
1392 crate_path.clone()
1395 } else {
1396 ThinVec::new()
1397 };
1398 segms.append(&mut path_segments.clone());
1399
1400 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
1401 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1402
1403 if child_accessible
1404 && let Some(idx) = candidates
1406 .iter()
1407 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1408 {
1409 candidates.remove(idx);
1410 }
1411
1412 let is_stable = if is_stable
1413 && let Some(did) = did
1414 && this.is_stable(did, path.span)
1415 {
1416 true
1417 } else {
1418 false
1419 };
1420
1421 if is_stable
1426 && let Some(idx) = candidates
1427 .iter()
1428 .position(|v: &ImportSuggestion| v.did == did && !v.is_stable)
1429 {
1430 candidates.remove(idx);
1431 }
1432
1433 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1434 let note = if let Some(did) = did {
1437 let requires_note = !did.is_local()
1438 && {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(did, &this.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcDiagnosticItem(sym::TryInto
| sym::TryFrom | sym::FromIterator)) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(
1439 this.tcx,
1440 did,
1441 RustcDiagnosticItem(
1442 sym::TryInto | sym::TryFrom | sym::FromIterator
1443 )
1444 );
1445 requires_note.then(|| {
1446 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}\' is included in the prelude starting in Edition 2021",
path_names_to_string(&path)))
})format!(
1447 "'{}' is included in the prelude starting in Edition 2021",
1448 path_names_to_string(&path)
1449 )
1450 })
1451 } else {
1452 None
1453 };
1454
1455 candidates.push(ImportSuggestion {
1456 did,
1457 descr: res.descr(),
1458 path,
1459 accessible: child_accessible,
1460 doc_visible: child_doc_visible,
1461 note,
1462 via_import,
1463 is_stable,
1464 });
1465 }
1466 }
1467
1468 if let Some(def_id) = name_binding.res().module_like_def_id() {
1470 let mut path_segments = path_segments.clone();
1472 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
1473
1474 let alias_import = if let DeclKind::Import { import, .. } = name_binding.kind
1475 && let ImportKind::ExternCrate { source: Some(_), .. } = import.kind
1476 && import.parent_scope.expansion == parent_scope.expansion
1477 {
1478 true
1479 } else {
1480 false
1481 };
1482
1483 let is_extern_crate_that_also_appears_in_prelude =
1484 name_binding.is_extern_crate() && lookup_ident.span.at_least_rust_2018();
1485
1486 if !is_extern_crate_that_also_appears_in_prelude || alias_import {
1487 if seen_modules.insert(def_id) {
1489 if via_import { &mut worklist_via_import } else { &mut worklist }.push(
1490 (
1491 this.expect_module(def_id),
1492 path_segments,
1493 child_accessible,
1494 child_doc_visible,
1495 is_stable && this.is_stable(def_id, name_binding.span),
1496 ),
1497 );
1498 }
1499 }
1500 }
1501 })
1502 }
1503
1504 candidates
1505 }
1506
1507 fn is_stable(&self, did: DefId, span: Span) -> bool {
1508 if did.is_local() {
1509 return true;
1510 }
1511
1512 match self.tcx.lookup_stability(did) {
1513 Some(Stability {
1514 level: StabilityLevel::Unstable { implied_by, .. }, feature, ..
1515 }) => {
1516 if span.allows_unstable(feature) {
1517 true
1518 } else if self.tcx.features().enabled(feature) {
1519 true
1520 } else if let Some(implied_by) = implied_by
1521 && self.tcx.features().enabled(implied_by)
1522 {
1523 true
1524 } else {
1525 false
1526 }
1527 }
1528 Some(_) => true,
1529 None => false,
1530 }
1531 }
1532
1533 pub(crate) fn lookup_import_candidates<FilterFn>(
1541 &mut self,
1542 lookup_ident: Ident,
1543 namespace: Namespace,
1544 parent_scope: &ParentScope<'ra>,
1545 filter_fn: FilterFn,
1546 ) -> Vec<ImportSuggestion>
1547 where
1548 FilterFn: Fn(Res) -> bool,
1549 {
1550 let crate_path = {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(ast::PathSegment::from_ident(Ident::with_dummy_span(kw::Crate)));
vec
}thin_vec![ast::PathSegment::from_ident(Ident::with_dummy_span(kw::Crate))];
1551 let mut suggestions = self.lookup_import_candidates_from_module(
1552 lookup_ident,
1553 namespace,
1554 parent_scope,
1555 self.graph_root,
1556 crate_path,
1557 &filter_fn,
1558 );
1559
1560 if lookup_ident.span.at_least_rust_2018() {
1561 for (ident, entry) in &self.extern_prelude {
1562 if entry.span().from_expansion() {
1563 continue;
1569 }
1570 let Some(crate_id) =
1571 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
1572 else {
1573 continue;
1574 };
1575
1576 let crate_def_id = crate_id.as_def_id();
1577 let crate_root = self.expect_module(crate_def_id);
1578
1579 let needs_disambiguation =
1583 self.resolutions(parent_scope.module).borrow().iter().any(
1584 |(key, name_resolution)| {
1585 if key.ns == TypeNS
1586 && key.ident == *ident
1587 && let Some(decl) = name_resolution.borrow().best_decl()
1588 {
1589 match decl.res() {
1590 Res::Def(_, def_id) => def_id != crate_def_id,
1593 Res::PrimTy(_) => true,
1594 _ => false,
1595 }
1596 } else {
1597 false
1598 }
1599 },
1600 );
1601 let mut crate_path = ThinVec::new();
1602 if needs_disambiguation {
1603 crate_path.push(ast::PathSegment::path_root(rustc_span::DUMMY_SP));
1604 }
1605 crate_path.push(ast::PathSegment::from_ident(ident.orig(entry.span())));
1606
1607 suggestions.extend(self.lookup_import_candidates_from_module(
1608 lookup_ident,
1609 namespace,
1610 parent_scope,
1611 crate_root,
1612 crate_path,
1613 &filter_fn,
1614 ));
1615 }
1616 }
1617
1618 suggestions.retain(|suggestion| suggestion.is_stable || self.tcx.sess.is_nightly_build());
1619 suggestions
1620 }
1621
1622 pub(crate) fn unresolved_macro_suggestions(
1623 &mut self,
1624 err: &mut Diag<'_>,
1625 macro_kind: MacroKind,
1626 parent_scope: &ParentScope<'ra>,
1627 ident: Ident,
1628 krate: &Crate,
1629 sugg_span: Option<Span>,
1630 ) {
1631 self.register_macros_for_all_crates();
1634
1635 let is_expected =
1636 &|res: Res| res.macro_kinds().is_some_and(|k| k.contains(macro_kind.into()));
1637 let suggestion = self.early_lookup_typo_candidate(
1638 ScopeSet::Macro(macro_kind),
1639 parent_scope,
1640 ident,
1641 is_expected,
1642 );
1643 if !self.add_typo_suggestion(err, suggestion, ident.span) {
1644 self.detect_derive_attribute(err, ident, parent_scope, sugg_span);
1645 }
1646
1647 let import_suggestions =
1648 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1649 let (span, found_use) = match parent_scope.module.nearest_parent_mod().as_local() {
1650 Some(def_id) => UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id)),
1651 None => (None, FoundUse::No),
1652 };
1653 show_candidates(
1654 self.tcx,
1655 err,
1656 span,
1657 &import_suggestions,
1658 Instead::No,
1659 found_use,
1660 DiagMode::Normal,
1661 ::alloc::vec::Vec::new()vec![],
1662 "",
1663 );
1664
1665 if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1666 let label_span = ident.span.shrink_to_hi();
1667 let mut spans = MultiSpan::from_span(label_span);
1668 spans.push_span_label(label_span, "put a macro name here");
1669 err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1670 return;
1671 }
1672
1673 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1674 err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1675 return;
1676 }
1677
1678 let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1679 if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1680 });
1681
1682 if let Some((def_id, unused_ident)) = unused_macro {
1683 let scope = self.local_macro_def_scopes[&def_id];
1684 let parent_nearest = parent_scope.module.nearest_parent_mod();
1685 let unused_macro_kinds = self.local_macro_map[def_id].ext.macro_kinds();
1686 if !unused_macro_kinds.contains(macro_kind.into()) {
1687 match macro_kind {
1688 MacroKind::Bang => {
1689 err.subdiagnostic(MacroRulesNot::Func { span: unused_ident.span, ident });
1690 }
1691 MacroKind::Attr => {
1692 err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1693 }
1694 MacroKind::Derive => {
1695 err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1696 }
1697 }
1698 return;
1699 }
1700 if Some(parent_nearest) == scope.opt_def_id() {
1701 err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1702 err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1703 return;
1704 }
1705 }
1706
1707 if ident.name == kw::Default
1708 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1709 {
1710 let span = self.def_span(def_id);
1711 let source_map = self.tcx.sess.source_map();
1712 let head_span = source_map.guess_head_span(span);
1713 err.subdiagnostic(ConsiderAddingADerive {
1714 span: head_span.shrink_to_lo(),
1715 suggestion: "#[derive(Default)]\n".to_string(),
1716 });
1717 }
1718 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1719 let Ok(binding) = self.cm().resolve_ident_in_scope_set(
1720 ident,
1721 ScopeSet::All(ns),
1722 parent_scope,
1723 None,
1724 None,
1725 None,
1726 ) else {
1727 continue;
1728 };
1729
1730 let desc = match binding.res() {
1731 Res::Def(DefKind::Macro(MacroKinds::BANG), _) => {
1732 "a function-like macro".to_string()
1733 }
1734 Res::Def(DefKind::Macro(MacroKinds::ATTR), _) | Res::NonMacroAttr(..) => {
1735 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("an attribute: `#[{0}]`", ident))
})format!("an attribute: `#[{ident}]`")
1736 }
1737 Res::Def(DefKind::Macro(MacroKinds::DERIVE), _) => {
1738 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a derive macro: `#[derive({0})]`",
ident))
})format!("a derive macro: `#[derive({ident})]`")
1739 }
1740 Res::Def(DefKind::Macro(kinds), _) => {
1741 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", kinds.article(),
kinds.descr()))
})format!("{} {}", kinds.article(), kinds.descr())
1742 }
1743 Res::ToolMod | Res::OpenMod(..) => {
1744 continue;
1746 }
1747 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1748 "only a trait, without a derive macro".to_string()
1749 }
1750 res => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}, not {2} {3}",
res.article(), res.descr(), macro_kind.article(),
macro_kind.descr_expected()))
})format!(
1751 "{} {}, not {} {}",
1752 res.article(),
1753 res.descr(),
1754 macro_kind.article(),
1755 macro_kind.descr_expected(),
1756 ),
1757 };
1758 if let crate::DeclKind::Import { import, .. } = binding.kind
1759 && !import.span.is_dummy()
1760 {
1761 let note = errors::IdentImporterHereButItIsDesc {
1762 span: import.span,
1763 imported_ident: ident,
1764 imported_ident_desc: &desc,
1765 };
1766 err.subdiagnostic(note);
1767 self.record_use(ident, binding, Used::Other);
1770 return;
1771 }
1772 let note = errors::IdentInScopeButItIsDesc {
1773 imported_ident: ident,
1774 imported_ident_desc: &desc,
1775 };
1776 err.subdiagnostic(note);
1777 return;
1778 }
1779
1780 if self.macro_names.contains(&IdentKey::new(ident)) {
1781 err.subdiagnostic(AddedMacroUse);
1782 return;
1783 }
1784 }
1785
1786 fn detect_derive_attribute(
1789 &self,
1790 err: &mut Diag<'_>,
1791 ident: Ident,
1792 parent_scope: &ParentScope<'ra>,
1793 sugg_span: Option<Span>,
1794 ) {
1795 let mut derives = ::alloc::vec::Vec::new()vec![];
1800 let mut all_attrs: UnordMap<Symbol, Vec<_>> = UnordMap::default();
1801 #[allow(rustc::potential_query_instability)]
1803 for (def_id, data) in self
1804 .local_macro_map
1805 .iter()
1806 .map(|(local_id, data)| (local_id.to_def_id(), data))
1807 .chain(self.extern_macro_map.borrow().iter().map(|(id, d)| (*id, d)))
1808 {
1809 for helper_attr in &data.ext.helper_attrs {
1810 let item_name = self.tcx.item_name(def_id);
1811 all_attrs.entry(*helper_attr).or_default().push(item_name);
1812 if helper_attr == &ident.name {
1813 derives.push(item_name);
1814 }
1815 }
1816 }
1817 let kind = MacroKind::Derive.descr();
1818 if !derives.is_empty() {
1819 let mut derives: Vec<String> = derives.into_iter().map(|d| d.to_string()).collect();
1821 derives.sort();
1822 derives.dedup();
1823 let msg = match &derives[..] {
1824 [derive] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}`", derive))
})format!(" `{derive}`"),
1825 [start @ .., last] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("s {0} and `{1}`",
start.iter().map(|d|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", d))
})).collect::<Vec<_>>().join(", "), last))
})format!(
1826 "s {} and `{last}`",
1827 start.iter().map(|d| format!("`{d}`")).collect::<Vec<_>>().join(", ")
1828 ),
1829 [] => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("we checked for this to be non-empty 10 lines above!?")));
}unreachable!("we checked for this to be non-empty 10 lines above!?"),
1830 };
1831 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is an attribute that can be used by the {1}{2}, you might be missing a `derive` attribute",
ident.name, kind, msg))
})format!(
1832 "`{}` is an attribute that can be used by the {kind}{msg}, you might be \
1833 missing a `derive` attribute",
1834 ident.name,
1835 );
1836 let sugg_span = if let ModuleKind::Def(DefKind::Enum, id, _) = parent_scope.module.kind
1837 {
1838 let span = self.def_span(id);
1839 if span.from_expansion() {
1840 None
1841 } else {
1842 Some(span.shrink_to_lo())
1844 }
1845 } else {
1846 sugg_span
1848 };
1849 match sugg_span {
1850 Some(span) => {
1851 err.span_suggestion_verbose(
1852 span,
1853 msg,
1854 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n",
derives.join(", ")))
})format!("#[derive({})]\n", derives.join(", ")),
1855 Applicability::MaybeIncorrect,
1856 );
1857 }
1858 None => {
1859 err.note(msg);
1860 }
1861 }
1862 } else {
1863 let all_attr_names = all_attrs.keys().map(|s| *s).into_sorted_stable_ord();
1865 if let Some(best_match) = find_best_match_for_name(&all_attr_names, ident.name, None)
1866 && let Some(macros) = all_attrs.get(&best_match)
1867 {
1868 let mut macros: Vec<String> = macros.into_iter().map(|d| d.to_string()).collect();
1869 macros.sort();
1870 macros.dedup();
1871 let msg = match ¯os[..] {
1872 [] => return,
1873 [name] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}` accepts", name))
})format!(" `{name}` accepts"),
1874 [start @ .., end] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("s {0} and `{1}` accept",
start.iter().map(|m|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", m))
})).collect::<Vec<_>>().join(", "), end))
})format!(
1875 "s {} and `{end}` accept",
1876 start.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", "),
1877 ),
1878 };
1879 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0}{1} the similarly named `{2}` attribute",
kind, msg, best_match))
})format!("the {kind}{msg} the similarly named `{best_match}` attribute");
1880 err.span_suggestion_verbose(
1881 ident.span,
1882 msg,
1883 best_match,
1884 Applicability::MaybeIncorrect,
1885 );
1886 }
1887 }
1888 }
1889
1890 pub(crate) fn add_typo_suggestion(
1891 &self,
1892 err: &mut Diag<'_>,
1893 suggestion: Option<TypoSuggestion>,
1894 span: Span,
1895 ) -> bool {
1896 let suggestion = match suggestion {
1897 None => return false,
1898 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1900 Some(suggestion) => suggestion,
1901 };
1902
1903 let mut did_label_def_span = false;
1904
1905 if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1906 if span.overlaps(def_span) {
1907 return false;
1926 }
1927 let span = self.tcx.sess.source_map().guess_head_span(def_span);
1928 let candidate_descr = suggestion.res.descr();
1929 let candidate = suggestion.candidate;
1930 let label = match suggestion.target {
1931 SuggestionTarget::SimilarlyNamed => {
1932 errors::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
1933 }
1934 SuggestionTarget::SingleItem => {
1935 errors::DefinedHere::SingleItem { span, candidate_descr, candidate }
1936 }
1937 };
1938 did_label_def_span = true;
1939 err.subdiagnostic(label);
1940 }
1941
1942 let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
1943 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1944 && let Some(span) = suggestion.span
1945 && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
1946 && snippet == candidate
1947 {
1948 let candidate = suggestion.candidate;
1949 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the leading underscore in `{0}` marks it as unused, consider renaming it to `{1}`",
candidate, snippet))
})format!(
1952 "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
1953 );
1954 if !did_label_def_span {
1955 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", candidate))
})format!("`{candidate}` defined here"));
1956 }
1957 (span, msg, snippet)
1958 } else {
1959 let msg = match suggestion.target {
1960 SuggestionTarget::SimilarlyNamed => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1} with a similar name exists",
suggestion.res.article(), suggestion.res.descr()))
})format!(
1961 "{} {} with a similar name exists",
1962 suggestion.res.article(),
1963 suggestion.res.descr()
1964 ),
1965 SuggestionTarget::SingleItem => {
1966 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("maybe you meant this {0}",
suggestion.res.descr()))
})format!("maybe you meant this {}", suggestion.res.descr())
1967 }
1968 };
1969 (span, msg, suggestion.candidate.to_ident_string())
1970 };
1971 err.span_suggestion_verbose(span, msg, sugg, Applicability::MaybeIncorrect);
1972 true
1973 }
1974
1975 fn decl_description(&self, b: Decl<'_>, ident: Ident, scope: Scope<'_>) -> String {
1976 let res = b.res();
1977 if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
1978 let (built_in, from) = match scope {
1979 Scope::StdLibPrelude | Scope::MacroUsePrelude => ("", " from prelude"),
1980 Scope::ExternPreludeFlags
1981 if self.tcx.sess.opts.externs.get(ident.as_str()).is_some()
1982 || #[allow(non_exhaustive_omitted_patterns)] match res {
Res::OpenMod(..) => true,
_ => false,
}matches!(res, Res::OpenMod(..)) =>
1983 {
1984 ("", " passed with `--extern`")
1985 }
1986 _ => {
1987 if #[allow(non_exhaustive_omitted_patterns)] match res {
Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => true,
_ => false,
}matches!(res, Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod) {
1988 ("", "")
1990 } else {
1991 (" built-in", "")
1992 }
1993 }
1994 };
1995
1996 let a = if built_in.is_empty() { res.article() } else { "a" };
1997 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{2} {0}{3}", res.descr(), a,
built_in, from))
})format!("{a}{built_in} {thing}{from}", thing = res.descr())
1998 } else {
1999 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
2000 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} {1} here", res.descr(),
introduced))
})format!("the {thing} {introduced} here", thing = res.descr())
2001 }
2002 }
2003
2004 fn ambiguity_diagnostic(&self, ambiguity_error: &AmbiguityError<'ra>) -> errors::Ambiguity {
2005 let AmbiguityError { kind, ambig_vis, ident, b1, b2, scope1, scope2, .. } =
2006 *ambiguity_error;
2007 let extern_prelude_ambiguity = || {
2008 #[allow(non_exhaustive_omitted_patterns)] match scope2 {
Scope::ExternPreludeFlags => true,
_ => false,
}matches!(scope2, Scope::ExternPreludeFlags)
2010 && self
2011 .extern_prelude
2012 .get(&IdentKey::new(ident))
2013 .is_some_and(|entry| entry.item_decl.map(|(b, ..)| b) == Some(b1))
2014 };
2015 let (b1, b2, scope1, scope2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
2016 (b2, b1, scope2, scope1, true)
2018 } else {
2019 (b1, b2, scope1, scope2, false)
2020 };
2021
2022 let could_refer_to = |b: Decl<'_>, scope: Scope<'ra>, also: &str| {
2023 let what = self.decl_description(b, ident, scope);
2024 let note_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` could{1} refer to {2}",
ident, also, what))
})format!("`{ident}` could{also} refer to {what}");
2025
2026 let thing = b.res().descr();
2027 let mut help_msgs = Vec::new();
2028 if b.is_glob_import()
2029 && (kind == AmbiguityKind::GlobVsGlob
2030 || kind == AmbiguityKind::GlobVsExpanded
2031 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
2032 {
2033 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider adding an explicit import of `{0}` to disambiguate",
ident))
})format!(
2034 "consider adding an explicit import of `{ident}` to disambiguate"
2035 ))
2036 }
2037 if b.is_extern_crate() && ident.span.at_least_rust_2018() && !extern_prelude_ambiguity()
2038 {
2039 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `::{0}` to refer to this {1} unambiguously",
ident, thing))
})format!("use `::{ident}` to refer to this {thing} unambiguously"))
2040 }
2041
2042 if kind != AmbiguityKind::GlobVsGlob {
2043 if let Scope::ModuleNonGlobs(module, _) | Scope::ModuleGlobs(module, _) = scope {
2044 if module == self.graph_root {
2045 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `crate::{0}` to refer to this {1} unambiguously",
ident, thing))
})format!(
2046 "use `crate::{ident}` to refer to this {thing} unambiguously"
2047 ));
2048 } else if module.is_normal() {
2049 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `self::{0}` to refer to this {1} unambiguously",
ident, thing))
})format!(
2050 "use `self::{ident}` to refer to this {thing} unambiguously"
2051 ));
2052 }
2053 }
2054 }
2055
2056 (
2057 Spanned { node: note_msg, span: b.span },
2058 help_msgs
2059 .iter()
2060 .enumerate()
2061 .map(|(i, help_msg)| {
2062 let or = if i == 0 { "" } else { "or " };
2063 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", or, help_msg))
})format!("{or}{help_msg}")
2064 })
2065 .collect::<Vec<_>>(),
2066 )
2067 };
2068 let (b1_note, b1_help_msgs) = could_refer_to(b1, scope1, "");
2069 let (b2_note, b2_help_msgs) = could_refer_to(b2, scope2, " also");
2070 let help = if kind == AmbiguityKind::GlobVsGlob
2071 && b1
2072 .parent_module
2073 .and_then(|m| m.opt_def_id())
2074 .map(|d| !d.is_local())
2075 .unwrap_or_default()
2076 {
2077 Some(&[
2078 "consider updating this dependency to resolve this error",
2079 "if updating the dependency does not resolve the problem report the problem to the author of the relevant crate",
2080 ] as &[_])
2081 } else {
2082 None
2083 };
2084
2085 let ambig_vis = ambig_vis.map(|(vis1, vis2)| {
2086 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} or {1}",
vis1.to_string(CRATE_DEF_ID, self.tcx),
vis2.to_string(CRATE_DEF_ID, self.tcx)))
})format!(
2087 "{} or {}",
2088 vis1.to_string(CRATE_DEF_ID, self.tcx),
2089 vis2.to_string(CRATE_DEF_ID, self.tcx)
2090 )
2091 });
2092
2093 errors::Ambiguity {
2094 ident,
2095 help,
2096 ambig_vis,
2097 kind: kind.descr(),
2098 b1_note,
2099 b1_help_msgs,
2100 b2_note,
2101 b2_help_msgs,
2102 is_error: false,
2103 }
2104 }
2105
2106 fn ctor_fields_span(&self, decl: Decl<'_>) -> Option<Span> {
2109 let DeclKind::Def(Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id)) =
2110 decl.kind
2111 else {
2112 return None;
2113 };
2114
2115 let def_id = self.tcx.parent(ctor_def_id);
2116 self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) }
2118
2119 fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
2120 let PrivacyError {
2121 ident,
2122 decl,
2123 outermost_res,
2124 parent_scope,
2125 single_nested,
2126 dedup_span,
2127 ref source,
2128 } = *privacy_error;
2129
2130 let res = decl.res();
2131 let ctor_fields_span = self.ctor_fields_span(decl);
2132 let plain_descr = res.descr().to_string();
2133 let nonimport_descr =
2134 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
2135 let import_descr = nonimport_descr.clone() + " import";
2136 let get_descr = |b: Decl<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
2137
2138 let ident_descr = get_descr(decl);
2140 let mut err =
2141 self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
2142
2143 self.mention_default_field_values(source, ident, &mut err);
2144
2145 let mut not_publicly_reexported = false;
2146 if let Some((this_res, outer_ident)) = outermost_res {
2147 let import_suggestions = self.lookup_import_candidates(
2148 outer_ident,
2149 this_res.ns().unwrap_or(Namespace::TypeNS),
2150 &parent_scope,
2151 &|res: Res| res == this_res,
2152 );
2153 let point_to_def = !show_candidates(
2154 self.tcx,
2155 &mut err,
2156 Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
2157 &import_suggestions,
2158 Instead::Yes,
2159 FoundUse::Yes,
2160 DiagMode::Import { append: single_nested, unresolved_import: false },
2161 ::alloc::vec::Vec::new()vec![],
2162 "",
2163 );
2164 if point_to_def && ident.span != outer_ident.span {
2166 not_publicly_reexported = true;
2167 let label = errors::OuterIdentIsNotPubliclyReexported {
2168 span: outer_ident.span,
2169 outer_ident_descr: this_res.descr(),
2170 outer_ident,
2171 };
2172 err.subdiagnostic(label);
2173 }
2174 }
2175
2176 let mut non_exhaustive = None;
2177 if let Some(def_id) = res.opt_def_id()
2181 && !def_id.is_local()
2182 && let Some(attr_span) = {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(NonExhaustive(span)) => {
break 'done Some(*span);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, def_id, NonExhaustive(span) => *span)
2183 {
2184 non_exhaustive = Some(attr_span);
2185 } else if let Some(span) = ctor_fields_span {
2186 let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
2187 err.subdiagnostic(label);
2188 if let Res::Def(_, d) = res
2189 && let Some(fields) = self.field_visibility_spans.get(&d)
2190 {
2191 let spans = fields.iter().map(|span| *span).collect();
2192 let sugg =
2193 errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
2194 err.subdiagnostic(sugg);
2195 }
2196 }
2197
2198 let mut sugg_paths: Vec<(Vec<Ident>, bool)> = ::alloc::vec::Vec::new()vec![];
2199 if let Some(mut def_id) = res.opt_def_id() {
2200 let mut path = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[def_id]))vec![def_id];
2202 while let Some(parent) = self.tcx.opt_parent(def_id) {
2203 def_id = parent;
2204 if !def_id.is_top_level_module() {
2205 path.push(def_id);
2206 } else {
2207 break;
2208 }
2209 }
2210 let path_names: Option<Vec<Ident>> = path
2212 .iter()
2213 .rev()
2214 .map(|def_id| {
2215 self.tcx.opt_item_name(*def_id).map(|name| {
2216 Ident::with_dummy_span(if def_id.is_top_level_module() {
2217 kw::Crate
2218 } else {
2219 name
2220 })
2221 })
2222 })
2223 .collect();
2224 if let Some(&def_id) = path.get(0)
2225 && let Some(path) = path_names
2226 {
2227 if let Some(def_id) = def_id.as_local() {
2228 if self.effective_visibilities.is_directly_public(def_id) {
2229 sugg_paths.push((path, false));
2230 }
2231 } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
2232 {
2233 sugg_paths.push((path, false));
2234 }
2235 }
2236 }
2237
2238 let first_binding = decl;
2240 let mut next_binding = Some(decl);
2241 let mut next_ident = ident;
2242 let mut path = ::alloc::vec::Vec::new()vec![];
2243 while let Some(binding) = next_binding {
2244 let name = next_ident;
2245 next_binding = match binding.kind {
2246 _ if res == Res::Err => None,
2247 DeclKind::Import { source_decl, import, .. } => match import.kind {
2248 _ if source_decl.span.is_dummy() => None,
2249 ImportKind::Single { source, .. } => {
2250 next_ident = source;
2251 Some(source_decl)
2252 }
2253 ImportKind::Glob { .. }
2254 | ImportKind::MacroUse { .. }
2255 | ImportKind::MacroExport => Some(source_decl),
2256 ImportKind::ExternCrate { .. } => None,
2257 },
2258 _ => None,
2259 };
2260
2261 match binding.kind {
2262 DeclKind::Import { import, .. } => {
2263 for segment in import.module_path.iter().skip(1) {
2264 if segment.ident.name != kw::PathRoot {
2267 path.push(segment.ident);
2268 }
2269 }
2270 sugg_paths.push((
2271 path.iter().cloned().chain(std::iter::once(ident)).collect::<Vec<_>>(),
2272 true, ));
2274 }
2275 DeclKind::Def(_) => {}
2276 }
2277 let first = binding == first_binding;
2278 let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
2279 let mut note_span = MultiSpan::from_span(def_span);
2280 if !first && binding.vis().is_public() {
2281 let desc = match binding.kind {
2282 DeclKind::Import { .. } => "re-export",
2283 _ => "directly",
2284 };
2285 note_span.push_span_label(def_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you could import this {0}", desc))
})format!("you could import this {desc}"));
2286 }
2287 if next_binding.is_none()
2290 && let Some(span) = non_exhaustive
2291 {
2292 note_span.push_span_label(
2293 span,
2294 "cannot be constructed because it is `#[non_exhaustive]`",
2295 );
2296 }
2297 let note = errors::NoteAndRefersToTheItemDefinedHere {
2298 span: note_span,
2299 binding_descr: get_descr(binding),
2300 binding_name: name,
2301 first,
2302 dots: next_binding.is_some(),
2303 };
2304 err.subdiagnostic(note);
2305 }
2306 sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0].name == sym::core, *reexport));
2308 for (sugg, reexport) in sugg_paths {
2309 if not_publicly_reexported {
2310 break;
2311 }
2312 if sugg.len() <= 1 {
2313 continue;
2316 }
2317 let path = join_path_idents(sugg);
2318 let sugg = if reexport {
2319 errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
2320 } else {
2321 errors::ImportIdent::Directly { span: dedup_span, ident, path }
2322 };
2323 err.subdiagnostic(sugg);
2324 break;
2325 }
2326
2327 err.emit();
2328 }
2329
2330 fn mention_default_field_values(
2350 &self,
2351 source: &Option<ast::Expr>,
2352 ident: Ident,
2353 err: &mut Diag<'_>,
2354 ) {
2355 let Some(expr) = source else { return };
2356 let ast::ExprKind::Struct(struct_expr) = &expr.kind else { return };
2357 let Some(segment) = struct_expr.path.segments.last() else { return };
2360 let Some(partial_res) = self.partial_res_map.get(&segment.id) else { return };
2361 let Some(Res::Def(_, def_id)) = partial_res.full_res() else {
2362 return;
2363 };
2364 let Some(default_fields) = self.field_defaults(def_id) else { return };
2365 if struct_expr.fields.is_empty() {
2366 return;
2367 }
2368 let last_span = struct_expr.fields.iter().last().unwrap().span;
2369 let mut iter = struct_expr.fields.iter().peekable();
2370 let mut prev: Option<Span> = None;
2371 while let Some(field) = iter.next() {
2372 if field.expr.span.overlaps(ident.span) {
2373 err.span_label(field.ident.span, "while setting this field");
2374 if default_fields.contains(&field.ident.name) {
2375 let sugg = if last_span == field.span {
2376 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(field.span, "..".to_string())]))vec![(field.span, "..".to_string())]
2377 } else {
2378 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(match (prev, iter.peek()) {
(_, Some(next)) => field.span.with_hi(next.span.lo()),
(Some(prev), _) => field.span.with_lo(prev.hi()),
(None, None) => field.span,
}, String::new()),
(last_span.shrink_to_hi(), ", ..".to_string())]))vec![
2379 (
2380 match (prev, iter.peek()) {
2382 (_, Some(next)) => field.span.with_hi(next.span.lo()),
2383 (Some(prev), _) => field.span.with_lo(prev.hi()),
2384 (None, None) => field.span,
2385 },
2386 String::new(),
2387 ),
2388 (last_span.shrink_to_hi(), ", ..".to_string()),
2389 ]
2390 };
2391 err.multipart_suggestion(
2392 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the type `{2}` of field `{0}` is private, but you can construct the default value defined for it in `{1}` using `..` in the struct initializer expression",
field.ident, self.tcx.item_name(def_id), ident))
})format!(
2393 "the type `{ident}` of field `{}` is private, but you can construct \
2394 the default value defined for it in `{}` using `..` in the struct \
2395 initializer expression",
2396 field.ident,
2397 self.tcx.item_name(def_id),
2398 ),
2399 sugg,
2400 Applicability::MachineApplicable,
2401 );
2402 break;
2403 }
2404 }
2405 prev = Some(field.span);
2406 }
2407 }
2408
2409 pub(crate) fn find_similarly_named_module_or_crate(
2410 &self,
2411 ident: Symbol,
2412 current_module: Module<'ra>,
2413 ) -> Option<Symbol> {
2414 let mut candidates = self
2415 .extern_prelude
2416 .keys()
2417 .map(|ident| ident.name)
2418 .chain(
2419 self.local_module_map
2420 .iter()
2421 .filter(|(_, module)| {
2422 current_module.is_ancestor_of(**module) && current_module != **module
2423 })
2424 .flat_map(|(_, module)| module.kind.name()),
2425 )
2426 .chain(
2427 self.extern_module_map
2428 .borrow()
2429 .iter()
2430 .filter(|(_, module)| {
2431 current_module.is_ancestor_of(**module) && current_module != **module
2432 })
2433 .flat_map(|(_, module)| module.kind.name()),
2434 )
2435 .filter(|c| !c.to_string().is_empty())
2436 .collect::<Vec<_>>();
2437 candidates.sort();
2438 candidates.dedup();
2439 find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
2440 }
2441
2442 pub(crate) fn report_path_resolution_error(
2443 &mut self,
2444 path: &[Segment],
2445 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
2447 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
2448 ignore_decl: Option<Decl<'ra>>,
2449 ignore_import: Option<Import<'ra>>,
2450 module: Option<ModuleOrUniformRoot<'ra>>,
2451 failed_segment_idx: usize,
2452 ident: Ident,
2453 diag_metadata: Option<&DiagMetadata<'_>>,
2454 ) -> (String, String, Option<Suggestion>) {
2455 let is_last = failed_segment_idx == path.len() - 1;
2456 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2457 let module_res = match module {
2458 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2459 _ => None,
2460 };
2461 let scope = match &path[..failed_segment_idx] {
2462 [.., prev] => {
2463 if prev.ident.name == kw::PathRoot {
2464 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the crate root"))
})format!("the crate root")
2465 } else {
2466 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", prev.ident))
})format!("`{}`", prev.ident)
2467 }
2468 }
2469 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this scope"))
})format!("this scope"),
2470 };
2471 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find `{0}` in {1}", ident,
scope))
})format!("cannot find `{ident}` in {scope}");
2472
2473 if module_res == self.graph_root.res() {
2474 let is_mod = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _));
2475 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2476 candidates
2477 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2478 if let Some(candidate) = candidates.get(0) {
2479 let path = {
2480 let len = candidate.path.segments.len();
2482 let start_index = (0..=failed_segment_idx.min(len - 1))
2483 .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2484 .unwrap_or_default();
2485 let segments =
2486 (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2487 Path { segments, span: Span::default(), tokens: None }
2488 };
2489 (
2490 message,
2491 String::from("unresolved import"),
2492 Some((
2493 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, pprust::path_to_string(&path))]))vec![(ident.span, pprust::path_to_string(&path))],
2494 String::from("a similar path exists"),
2495 Applicability::MaybeIncorrect,
2496 )),
2497 )
2498 } else if ident.name == sym::core {
2499 (
2500 message,
2501 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might be missing crate `{0}`",
ident))
})format!("you might be missing crate `{ident}`"),
2502 Some((
2503 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, "std".to_string())]))vec![(ident.span, "std".to_string())],
2504 "try using `std` instead of `core`".to_string(),
2505 Applicability::MaybeIncorrect,
2506 )),
2507 )
2508 } else if ident.name == kw::Underscore {
2509 (
2510 "invalid crate or module name `_`".to_string(),
2511 "`_` is not a valid crate or module name".to_string(),
2512 None,
2513 )
2514 } else if self.tcx.sess.is_rust_2015() {
2515 (
2516 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
ident, scope))
})format!("cannot find module or crate `{ident}` in {scope}"),
2517 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use of unresolved module or unlinked crate `{0}`",
ident))
})format!("use of unresolved module or unlinked crate `{ident}`"),
2518 Some((
2519 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.current_crate_outer_attr_insert_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern crate {0};\n",
ident))
}))]))vec![(
2520 self.current_crate_outer_attr_insert_span,
2521 format!("extern crate {ident};\n"),
2522 )],
2523 if was_invoked_from_cargo() {
2524 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you wanted to use a crate named `{0}`, use `cargo add {0}` to add it to your `Cargo.toml` and import it in your code",
ident))
})format!(
2525 "if you wanted to use a crate named `{ident}`, use `cargo add \
2526 {ident}` to add it to your `Cargo.toml` and import it in your \
2527 code",
2528 )
2529 } else {
2530 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might be missing a crate named `{0}`, add it to your project and import it in your code",
ident))
})format!(
2531 "you might be missing a crate named `{ident}`, add it to your \
2532 project and import it in your code",
2533 )
2534 },
2535 Applicability::MaybeIncorrect,
2536 )),
2537 )
2538 } else {
2539 (message, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not find `{0}` in the crate root",
ident))
})format!("could not find `{ident}` in the crate root"), None)
2540 }
2541 } else if failed_segment_idx > 0 {
2542 let parent = path[failed_segment_idx - 1].ident.name;
2543 let parent = match parent {
2544 kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2547 "the list of imported crates".to_owned()
2548 }
2549 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2550 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", parent))
})format!("`{parent}`"),
2551 };
2552
2553 let mut msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not find `{0}` in {1}",
ident, parent))
})format!("could not find `{ident}` in {parent}");
2554 if ns == TypeNS || ns == ValueNS {
2555 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2556 let binding = if let Some(module) = module {
2557 self.cm()
2558 .resolve_ident_in_module(
2559 module,
2560 ident,
2561 ns_to_try,
2562 parent_scope,
2563 None,
2564 ignore_decl,
2565 ignore_import,
2566 )
2567 .ok()
2568 } else if let Some(ribs) = ribs
2569 && let Some(TypeNS | ValueNS) = opt_ns
2570 {
2571 if !ignore_import.is_none() {
::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
2572 match self.resolve_ident_in_lexical_scope(
2573 ident,
2574 ns_to_try,
2575 parent_scope,
2576 None,
2577 &ribs[ns_to_try],
2578 ignore_decl,
2579 diag_metadata,
2580 ) {
2581 Some(LateDecl::Decl(binding)) => Some(binding),
2583 _ => None,
2584 }
2585 } else {
2586 self.cm()
2587 .resolve_ident_in_scope_set(
2588 ident,
2589 ScopeSet::All(ns_to_try),
2590 parent_scope,
2591 None,
2592 ignore_decl,
2593 ignore_import,
2594 )
2595 .ok()
2596 };
2597 if let Some(binding) = binding {
2598 msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1} `{2}` in {3}",
ns.descr(), binding.res().descr(), ident, parent))
})format!(
2599 "expected {}, found {} `{ident}` in {parent}",
2600 ns.descr(),
2601 binding.res().descr(),
2602 );
2603 };
2604 }
2605 (message, msg, None)
2606 } else if ident.name == kw::SelfUpper {
2607 if opt_ns.is_none() {
2611 (message, "`Self` cannot be used in imports".to_string(), None)
2612 } else {
2613 (
2614 message,
2615 "`Self` is only available in impls, traits, and type definitions".to_string(),
2616 None,
2617 )
2618 }
2619 } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2620 let binding = if let Some(ribs) = ribs {
2622 if !ignore_import.is_none() {
::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
2623 self.resolve_ident_in_lexical_scope(
2624 ident,
2625 ValueNS,
2626 parent_scope,
2627 None,
2628 &ribs[ValueNS],
2629 ignore_decl,
2630 diag_metadata,
2631 )
2632 } else {
2633 None
2634 };
2635 let match_span = match binding {
2636 Some(LateDecl::RibDef(Res::Local(id))) => {
2645 Some((*self.pat_span_map.get(&id).unwrap(), "a", "local binding"))
2646 }
2647 Some(LateDecl::Decl(name_binding)) => Some((
2659 name_binding.span,
2660 name_binding.res().article(),
2661 name_binding.res().descr(),
2662 )),
2663 _ => None,
2664 };
2665
2666 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find type `{0}` in {1}",
ident, scope))
})format!("cannot find type `{ident}` in {scope}");
2667 let label = if let Some((span, article, descr)) = match_span {
2668 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{1}` is declared as {2} {3} at `{0}`, not a type",
self.tcx.sess.source_map().span_to_short_string(span,
RemapPathScopeComponents::DIAGNOSTICS), ident, article,
descr))
})format!(
2669 "`{ident}` is declared as {article} {descr} at `{}`, not a type",
2670 self.tcx
2671 .sess
2672 .source_map()
2673 .span_to_short_string(span, RemapPathScopeComponents::DIAGNOSTICS)
2674 )
2675 } else {
2676 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use of undeclared type `{0}`",
ident))
})format!("use of undeclared type `{ident}`")
2677 };
2678 (message, label, None)
2679 } else {
2680 let mut suggestion = None;
2681 if ident.name == sym::alloc {
2682 suggestion = Some((
2683 ::alloc::vec::Vec::new()vec![],
2684 String::from("add `extern crate alloc` to use the `alloc` crate"),
2685 Applicability::MaybeIncorrect,
2686 ))
2687 }
2688
2689 suggestion = suggestion.or_else(|| {
2690 self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2691 |sugg| {
2692 (
2693 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, sugg.to_string())]))vec![(ident.span, sugg.to_string())],
2694 String::from("there is a crate or module with a similar name"),
2695 Applicability::MaybeIncorrect,
2696 )
2697 },
2698 )
2699 });
2700 if let Ok(binding) = self.cm().resolve_ident_in_scope_set(
2701 ident,
2702 ScopeSet::All(ValueNS),
2703 parent_scope,
2704 None,
2705 ignore_decl,
2706 ignore_import,
2707 ) {
2708 let descr = binding.res().descr();
2709 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
ident, scope))
})format!("cannot find module or crate `{ident}` in {scope}");
2710 (message, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` is not a crate or module",
descr, ident))
})format!("{descr} `{ident}` is not a crate or module"), suggestion)
2711 } else {
2712 let suggestion = if suggestion.is_some() {
2713 suggestion
2714 } else if let Some(m) = self.undeclared_module_exists(ident) {
2715 self.undeclared_module_suggest_declare(ident, m)
2716 } else if was_invoked_from_cargo() {
2717 Some((
2718 ::alloc::vec::Vec::new()vec![],
2719 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you wanted to use a crate named `{0}`, use `cargo add {0}` to add it to your `Cargo.toml`",
ident))
})format!(
2720 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2721 to add it to your `Cargo.toml`",
2722 ),
2723 Applicability::MaybeIncorrect,
2724 ))
2725 } else {
2726 Some((
2727 ::alloc::vec::Vec::new()vec![],
2728 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might be missing a crate named `{0}`",
ident))
})format!("you might be missing a crate named `{ident}`",),
2729 Applicability::MaybeIncorrect,
2730 ))
2731 };
2732 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
ident, scope))
})format!("cannot find module or crate `{ident}` in {scope}");
2733 (
2734 message,
2735 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use of unresolved module or unlinked crate `{0}`",
ident))
})format!("use of unresolved module or unlinked crate `{ident}`"),
2736 suggestion,
2737 )
2738 }
2739 }
2740 }
2741
2742 fn undeclared_module_suggest_declare(
2743 &self,
2744 ident: Ident,
2745 path: std::path::PathBuf,
2746 ) -> Option<(Vec<(Span, String)>, String, Applicability)> {
2747 Some((
2748 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.current_crate_outer_attr_insert_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("mod {0};\n", ident))
}))]))vec![(self.current_crate_outer_attr_insert_span, format!("mod {ident};\n"))],
2749 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to make use of source file {0}, use `mod {1}` in this file to declare the module",
path.display(), ident))
})format!(
2750 "to make use of source file {}, use `mod {ident}` \
2751 in this file to declare the module",
2752 path.display()
2753 ),
2754 Applicability::MaybeIncorrect,
2755 ))
2756 }
2757
2758 fn undeclared_module_exists(&self, ident: Ident) -> Option<std::path::PathBuf> {
2759 let map = self.tcx.sess.source_map();
2760
2761 let src = map.span_to_filename(ident.span).into_local_path()?;
2762 let i = ident.as_str();
2763 let dir = src.parent()?;
2765 let src = src.file_stem()?.to_str()?;
2766 for file in [
2767 dir.join(i).with_extension("rs"),
2769 dir.join(i).join("mod.rs"),
2771 ] {
2772 if file.exists() {
2773 return Some(file);
2774 }
2775 }
2776 if !#[allow(non_exhaustive_omitted_patterns)] match src {
"main" | "lib" | "mod" => true,
_ => false,
}matches!(src, "main" | "lib" | "mod") {
2777 for file in [
2778 dir.join(src).join(i).with_extension("rs"),
2780 dir.join(src).join(i).join("mod.rs"),
2782 ] {
2783 if file.exists() {
2784 return Some(file);
2785 }
2786 }
2787 }
2788 None
2789 }
2790
2791 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("make_path_suggestion",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2792u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Option<(Vec<Segment>, Option<String>)> = loop {};
return __tracing_attr_fake_return;
}
{
match path[..] {
[first, second, ..] if
first.ident.name == kw::PathRoot &&
!second.ident.is_path_segment_keyword() => {}
[first, ..] if
first.ident.span.at_least_rust_2018() &&
!first.ident.is_path_segment_keyword() => {
path.insert(0, Segment::from_ident(Ident::dummy()));
}
_ => return None,
}
self.make_missing_self_suggestion(path.clone(),
parent_scope).or_else(||
self.make_missing_crate_suggestion(path.clone(),
parent_scope)).or_else(||
self.make_missing_super_suggestion(path.clone(),
parent_scope)).or_else(||
self.make_external_crate_suggestion(path, parent_scope))
}
}
}#[instrument(level = "debug", skip(self, parent_scope))]
2793 pub(crate) fn make_path_suggestion(
2794 &mut self,
2795 mut path: Vec<Segment>,
2796 parent_scope: &ParentScope<'ra>,
2797 ) -> Option<(Vec<Segment>, Option<String>)> {
2798 match path[..] {
2799 [first, second, ..]
2802 if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2803 [first, ..]
2805 if first.ident.span.at_least_rust_2018()
2806 && !first.ident.is_path_segment_keyword() =>
2807 {
2808 path.insert(0, Segment::from_ident(Ident::dummy()));
2810 }
2811 _ => return None,
2812 }
2813
2814 self.make_missing_self_suggestion(path.clone(), parent_scope)
2815 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2816 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2817 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2818 }
2819
2820 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("make_missing_self_suggestion",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2827u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Option<(Vec<Segment>, Option<String>)> = loop {};
return __tracing_attr_fake_return;
}
{
path[0].ident.name = kw::SelfLower;
let result =
self.cm().maybe_resolve_path(&path, None, parent_scope, None);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2836",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2836u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path", "result"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&result) as
&dyn Value))])
});
} else { ; }
};
if let PathResult::Module(..) = result {
Some((path, None))
} else { None }
}
}
}#[instrument(level = "debug", skip(self, parent_scope))]
2828 fn make_missing_self_suggestion(
2829 &mut self,
2830 mut path: Vec<Segment>,
2831 parent_scope: &ParentScope<'ra>,
2832 ) -> Option<(Vec<Segment>, Option<String>)> {
2833 path[0].ident.name = kw::SelfLower;
2835 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2836 debug!(?path, ?result);
2837 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2838 }
2839
2840 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("make_missing_crate_suggestion",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2847u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Option<(Vec<Segment>, Option<String>)> = loop {};
return __tracing_attr_fake_return;
}
{
path[0].ident.name = kw::Crate;
let result =
self.cm().maybe_resolve_path(&path, None, parent_scope, None);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2856",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2856u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path", "result"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&result) as
&dyn Value))])
});
} else { ; }
};
if let PathResult::Module(..) = result {
Some((path,
Some("`use` statements changed in Rust 2018; read more at \
<https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
clarity.html>".to_string())))
} else { None }
}
}
}#[instrument(level = "debug", skip(self, parent_scope))]
2848 fn make_missing_crate_suggestion(
2849 &mut self,
2850 mut path: Vec<Segment>,
2851 parent_scope: &ParentScope<'ra>,
2852 ) -> Option<(Vec<Segment>, Option<String>)> {
2853 path[0].ident.name = kw::Crate;
2855 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2856 debug!(?path, ?result);
2857 if let PathResult::Module(..) = result {
2858 Some((
2859 path,
2860 Some(
2861 "`use` statements changed in Rust 2018; read more at \
2862 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2863 clarity.html>"
2864 .to_string(),
2865 ),
2866 ))
2867 } else {
2868 None
2869 }
2870 }
2871
2872 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("make_missing_super_suggestion",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2879u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Option<(Vec<Segment>, Option<String>)> = loop {};
return __tracing_attr_fake_return;
}
{
path[0].ident.name = kw::Super;
let result =
self.cm().maybe_resolve_path(&path, None, parent_scope, None);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2888",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2888u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path", "result"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&result) as
&dyn Value))])
});
} else { ; }
};
if let PathResult::Module(..) = result {
Some((path, None))
} else { None }
}
}
}#[instrument(level = "debug", skip(self, parent_scope))]
2880 fn make_missing_super_suggestion(
2881 &mut self,
2882 mut path: Vec<Segment>,
2883 parent_scope: &ParentScope<'ra>,
2884 ) -> Option<(Vec<Segment>, Option<String>)> {
2885 path[0].ident.name = kw::Super;
2887 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2888 debug!(?path, ?result);
2889 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2890 }
2891
2892 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("make_external_crate_suggestion",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2902u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Option<(Vec<Segment>, Option<String>)> = loop {};
return __tracing_attr_fake_return;
}
{
if path[1].ident.span.is_rust_2015() { return None; }
let mut extern_crate_names =
self.extern_prelude.keys().map(|ident|
ident.name).collect::<Vec<_>>();
extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
for name in extern_crate_names.into_iter() {
path[0].ident.name = name;
let result =
self.cm().maybe_resolve_path(&path, None, parent_scope,
None);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2923",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2923u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path", "name",
"result"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&name) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&result) as
&dyn Value))])
});
} else { ; }
};
if let PathResult::Module(..) = result {
return Some((path, None));
}
}
None
}
}
}#[instrument(level = "debug", skip(self, parent_scope))]
2903 fn make_external_crate_suggestion(
2904 &mut self,
2905 mut path: Vec<Segment>,
2906 parent_scope: &ParentScope<'ra>,
2907 ) -> Option<(Vec<Segment>, Option<String>)> {
2908 if path[1].ident.span.is_rust_2015() {
2909 return None;
2910 }
2911
2912 let mut extern_crate_names =
2916 self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2917 extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
2918
2919 for name in extern_crate_names.into_iter() {
2920 path[0].ident.name = name;
2922 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2923 debug!(?path, ?name, ?result);
2924 if let PathResult::Module(..) = result {
2925 return Some((path, None));
2926 }
2927 }
2928
2929 None
2930 }
2931
2932 pub(crate) fn check_for_module_export_macro(
2945 &mut self,
2946 import: Import<'ra>,
2947 module: ModuleOrUniformRoot<'ra>,
2948 ident: Ident,
2949 ) -> Option<(Option<Suggestion>, Option<String>)> {
2950 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2951 return None;
2952 };
2953
2954 while let Some(parent) = crate_module.parent {
2955 crate_module = parent;
2956 }
2957
2958 if module == ModuleOrUniformRoot::Module(crate_module) {
2959 return None;
2961 }
2962
2963 let binding_key = BindingKey::new(IdentKey::new(ident), MacroNS);
2964 let binding = self.resolution(crate_module, binding_key)?.binding()?;
2965 let Res::Def(DefKind::Macro(kinds), _) = binding.res() else {
2966 return None;
2967 };
2968 if !kinds.contains(MacroKinds::BANG) {
2969 return None;
2970 }
2971 let module_name = crate_module.kind.name().unwrap_or(kw::Crate);
2972 let import_snippet = match import.kind {
2973 ImportKind::Single { source, target, .. } if source != target => {
2974 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} as {1}", source, target))
})format!("{source} as {target}")
2975 }
2976 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", ident))
})format!("{ident}"),
2977 };
2978
2979 let mut corrections: Vec<(Span, String)> = Vec::new();
2980 if !import.is_nested() {
2981 corrections.push((import.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}", module_name,
import_snippet))
})format!("{module_name}::{import_snippet}")));
2984 } else {
2985 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2989 self.tcx.sess,
2990 import.span,
2991 import.use_span,
2992 );
2993 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:2993",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2993u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["found_closing_brace",
"binding_span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&found_closing_brace
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&binding_span)
as &dyn Value))])
});
} else { ; }
};debug!(found_closing_brace, ?binding_span);
2994
2995 let mut removal_span = binding_span;
2996
2997 if found_closing_brace
3005 && let Some(previous_span) =
3006 extend_span_to_previous_binding(self.tcx.sess, binding_span)
3007 {
3008 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:3008",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3008u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["previous_span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&previous_span)
as &dyn Value))])
});
} else { ; }
};debug!(?previous_span);
3009 removal_span = removal_span.with_lo(previous_span.lo());
3010 }
3011 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:3011",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3011u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["removal_span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&removal_span)
as &dyn Value))])
});
} else { ; }
};debug!(?removal_span);
3012
3013 corrections.push((removal_span, "".to_string()));
3015
3016 let (has_nested, after_crate_name) =
3023 find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
3024 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/diagnostics.rs:3024",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3024u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["has_nested",
"after_crate_name"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&has_nested as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&after_crate_name)
as &dyn Value))])
});
} else { ; }
};debug!(has_nested, ?after_crate_name);
3025
3026 let source_map = self.tcx.sess.source_map();
3027
3028 let is_definitely_crate = import
3030 .module_path
3031 .first()
3032 .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
3033
3034 let start_point = source_map.start_point(after_crate_name);
3036 if is_definitely_crate
3037 && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
3038 {
3039 corrections.push((
3040 start_point,
3041 if has_nested {
3042 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}, ", start_snippet,
import_snippet))
})format!("{start_snippet}{import_snippet}, ")
3044 } else {
3045 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{{0}, {1}", import_snippet,
start_snippet))
})format!("{{{import_snippet}, {start_snippet}")
3048 },
3049 ));
3050
3051 if !has_nested {
3053 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
3054 }
3055 } else {
3056 corrections.push((
3058 import.use_span.shrink_to_lo(),
3059 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use {0}::{1};\n", module_name,
import_snippet))
})format!("use {module_name}::{import_snippet};\n"),
3060 ));
3061 }
3062 }
3063
3064 let suggestion = Some((
3065 corrections,
3066 String::from("a macro with this name exists at the root of the crate"),
3067 Applicability::MaybeIncorrect,
3068 ));
3069 Some((
3070 suggestion,
3071 Some(
3072 "this could be because a macro annotated with `#[macro_export]` will be exported \
3073 at the root of the crate instead of the module where it is defined"
3074 .to_string(),
3075 ),
3076 ))
3077 }
3078
3079 pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
3081 let local_items;
3082 let symbols = if module.is_local() {
3083 local_items = self
3084 .stripped_cfg_items
3085 .iter()
3086 .filter_map(|item| {
3087 let parent_scope = self.opt_local_def_id(item.parent_scope)?.to_def_id();
3088 Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg.clone() })
3089 })
3090 .collect::<Vec<_>>();
3091 local_items.as_slice()
3092 } else {
3093 self.tcx.stripped_cfg_items(module.krate)
3094 };
3095
3096 for &StrippedCfgItem { parent_scope, ident, ref cfg } in symbols {
3097 if ident.name != *segment {
3098 continue;
3099 }
3100
3101 let parent_module = self.get_nearest_non_block_module(parent_scope).def_id();
3102
3103 fn comes_from_same_module_for_glob(
3104 r: &Resolver<'_, '_>,
3105 parent_module: DefId,
3106 module: DefId,
3107 visited: &mut FxHashMap<DefId, bool>,
3108 ) -> bool {
3109 if let Some(&cached) = visited.get(&parent_module) {
3110 return cached;
3114 }
3115 visited.insert(parent_module, false);
3116 let m = r.expect_module(parent_module);
3117 let mut res = false;
3118 for importer in m.glob_importers.borrow().iter() {
3119 if let Some(next_parent_module) = importer.parent_scope.module.opt_def_id() {
3120 if next_parent_module == module
3121 || comes_from_same_module_for_glob(
3122 r,
3123 next_parent_module,
3124 module,
3125 visited,
3126 )
3127 {
3128 res = true;
3129 break;
3130 }
3131 }
3132 }
3133 visited.insert(parent_module, res);
3134 res
3135 }
3136
3137 let comes_from_same_module = parent_module == module
3138 || comes_from_same_module_for_glob(
3139 self,
3140 parent_module,
3141 module,
3142 &mut Default::default(),
3143 );
3144 if !comes_from_same_module {
3145 continue;
3146 }
3147
3148 let item_was = if let CfgEntry::NameValue { value: Some(feature), .. } = cfg.0 {
3149 errors::ItemWas::BehindFeature { feature, span: cfg.1 }
3150 } else {
3151 errors::ItemWas::CfgOut { span: cfg.1 }
3152 };
3153 let note = errors::FoundItemConfigureOut { span: ident.span, item_was };
3154 err.subdiagnostic(note);
3155 }
3156 }
3157}
3158
3159fn find_span_of_binding_until_next_binding(
3173 sess: &Session,
3174 binding_span: Span,
3175 use_span: Span,
3176) -> (bool, Span) {
3177 let source_map = sess.source_map();
3178
3179 let binding_until_end = binding_span.with_hi(use_span.hi());
3182
3183 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
3186
3187 let mut found_closing_brace = false;
3194 let after_binding_until_next_binding =
3195 source_map.span_take_while(after_binding_until_end, |&ch| {
3196 if ch == '}' {
3197 found_closing_brace = true;
3198 }
3199 ch == ' ' || ch == ','
3200 });
3201
3202 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
3207
3208 (found_closing_brace, span)
3209}
3210
3211fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
3224 let source_map = sess.source_map();
3225
3226 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
3230
3231 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
3232 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
3233 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
3234 return None;
3235 }
3236
3237 let prev_comma = prev_comma.first().unwrap();
3238 let prev_starting_brace = prev_starting_brace.first().unwrap();
3239
3240 if prev_comma.len() > prev_starting_brace.len() {
3244 return None;
3245 }
3246
3247 Some(binding_span.with_lo(BytePos(
3248 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
3251 )))
3252}
3253
3254#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("find_span_immediately_after_crate_name",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3267u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["use_span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: (bool, Span) = loop {};
return __tracing_attr_fake_return;
}
{
let source_map = sess.source_map();
let mut num_colons = 0;
let until_second_colon =
source_map.span_take_while(use_span,
|c|
{
if *c == ':' { num_colons += 1; }
!#[allow(non_exhaustive_omitted_patterns)] match c {
':' if num_colons == 2 => true,
_ => false,
}
});
let from_second_colon =
use_span.with_lo(until_second_colon.hi() + BytePos(1));
let mut found_a_non_whitespace_character = false;
let after_second_colon =
source_map.span_take_while(from_second_colon,
|c|
{
if found_a_non_whitespace_character { return false; }
if !c.is_whitespace() {
found_a_non_whitespace_character = true;
}
true
});
let next_left_bracket =
source_map.span_through_char(from_second_colon, '{');
(next_left_bracket == after_second_colon, from_second_colon)
}
}
}#[instrument(level = "debug", skip(sess))]
3268fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
3269 let source_map = sess.source_map();
3270
3271 let mut num_colons = 0;
3273 let until_second_colon = source_map.span_take_while(use_span, |c| {
3275 if *c == ':' {
3276 num_colons += 1;
3277 }
3278 !matches!(c, ':' if num_colons == 2)
3279 });
3280 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
3282
3283 let mut found_a_non_whitespace_character = false;
3284 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
3286 if found_a_non_whitespace_character {
3287 return false;
3288 }
3289 if !c.is_whitespace() {
3290 found_a_non_whitespace_character = true;
3291 }
3292 true
3293 });
3294
3295 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
3297
3298 (next_left_bracket == after_second_colon, from_second_colon)
3299}
3300
3301enum Instead {
3304 Yes,
3305 No,
3306}
3307
3308enum FoundUse {
3310 Yes,
3311 No,
3312}
3313
3314pub(crate) enum DiagMode {
3316 Normal,
3317 Pattern,
3319 Import {
3321 unresolved_import: bool,
3323 append: bool,
3326 },
3327}
3328
3329pub(crate) fn import_candidates(
3330 tcx: TyCtxt<'_>,
3331 err: &mut Diag<'_>,
3332 use_placement_span: Option<Span>,
3334 candidates: &[ImportSuggestion],
3335 mode: DiagMode,
3336 append: &str,
3337) {
3338 show_candidates(
3339 tcx,
3340 err,
3341 use_placement_span,
3342 candidates,
3343 Instead::Yes,
3344 FoundUse::Yes,
3345 mode,
3346 ::alloc::vec::Vec::new()vec![],
3347 append,
3348 );
3349}
3350
3351type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
3352
3353fn show_candidates(
3358 tcx: TyCtxt<'_>,
3359 err: &mut Diag<'_>,
3360 use_placement_span: Option<Span>,
3362 candidates: &[ImportSuggestion],
3363 instead: Instead,
3364 found_use: FoundUse,
3365 mode: DiagMode,
3366 path: Vec<Segment>,
3367 append: &str,
3368) -> bool {
3369 if candidates.is_empty() {
3370 return false;
3371 }
3372
3373 let mut showed = false;
3374 let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
3375 let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
3376
3377 candidates.iter().for_each(|c| {
3378 if c.accessible {
3379 if c.doc_visible {
3381 accessible_path_strings.push((
3382 pprust::path_to_string(&c.path),
3383 c.descr,
3384 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3385 &c.note,
3386 c.via_import,
3387 ))
3388 }
3389 } else {
3390 inaccessible_path_strings.push((
3391 pprust::path_to_string(&c.path),
3392 c.descr,
3393 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3394 &c.note,
3395 c.via_import,
3396 ))
3397 }
3398 });
3399
3400 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
3403 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
3404 path_strings.dedup_by(|a, b| a.0 == b.0);
3405 let core_path_strings =
3406 path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
3407 let std_path_strings =
3408 path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
3409 let foreign_crate_path_strings =
3410 path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
3411
3412 if std_path_strings.len() == core_path_strings.len() {
3415 path_strings.extend(std_path_strings);
3417 } else {
3418 path_strings.extend(std_path_strings);
3419 path_strings.extend(core_path_strings);
3420 }
3421 path_strings.extend(foreign_crate_path_strings);
3423 }
3424
3425 if !accessible_path_strings.is_empty() {
3426 let (determiner, kind, s, name, through) =
3427 if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
3428 (
3429 "this",
3430 *descr,
3431 "",
3432 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}`", name))
})format!(" `{name}`"),
3433 if *via_import { " through its public re-export" } else { "" },
3434 )
3435 } else {
3436 let kinds = accessible_path_strings
3439 .iter()
3440 .map(|(_, descr, _, _, _)| *descr)
3441 .collect::<UnordSet<&str>>();
3442 let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
3443 let s = if kind.ends_with('s') { "es" } else { "s" };
3444
3445 ("one of these", kind, s, String::new(), "")
3446 };
3447
3448 let instead = if let Instead::Yes = instead { " instead" } else { "" };
3449 let mut msg = if let DiagMode::Pattern = mode {
3450 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you meant to match on {0}{1}{2}{3}, use the full path in the pattern",
kind, s, instead, name))
})format!(
3451 "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
3452 pattern",
3453 )
3454 } else {
3455 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider importing {0} {1}{2}{3}{4}",
determiner, kind, s, through, instead))
})format!("consider importing {determiner} {kind}{s}{through}{instead}")
3456 };
3457
3458 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3459 err.note(note.clone());
3460 }
3461
3462 let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
3463 msg.push(':');
3464
3465 for candidate in accessible_path_strings {
3466 msg.push('\n');
3467 msg.push_str(&candidate.0);
3468 }
3469 };
3470
3471 if let Some(span) = use_placement_span {
3472 let (add_use, trailing) = match mode {
3473 DiagMode::Pattern => {
3474 err.span_suggestions(
3475 span,
3476 msg,
3477 accessible_path_strings.into_iter().map(|a| a.0),
3478 Applicability::MaybeIncorrect,
3479 );
3480 return true;
3481 }
3482 DiagMode::Import { .. } => ("", ""),
3483 DiagMode::Normal => ("use ", ";\n"),
3484 };
3485 for candidate in &mut accessible_path_strings {
3486 let additional_newline = if let FoundUse::No = found_use
3489 && let DiagMode::Normal = mode
3490 {
3491 "\n"
3492 } else {
3493 ""
3494 };
3495 candidate.0 =
3496 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}{2}{3}{4}", candidate.0,
add_use, append, trailing, additional_newline))
})format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
3497 }
3498
3499 match mode {
3500 DiagMode::Import { append: true, .. } => {
3501 append_candidates(&mut msg, accessible_path_strings);
3502 err.span_help(span, msg);
3503 }
3504 _ => {
3505 err.span_suggestions_with_style(
3506 span,
3507 msg,
3508 accessible_path_strings.into_iter().map(|a| a.0),
3509 Applicability::MaybeIncorrect,
3510 SuggestionStyle::ShowAlways,
3511 );
3512 }
3513 }
3514
3515 if let [first, .., last] = &path[..] {
3516 let sp = first.ident.span.until(last.ident.span);
3517 if sp.can_be_used_for_suggestions() && !sp.is_empty() {
3520 err.span_suggestion_verbose(
3521 sp,
3522 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you import `{0}`, refer to it directly",
last.ident))
})format!("if you import `{}`, refer to it directly", last.ident),
3523 "",
3524 Applicability::Unspecified,
3525 );
3526 }
3527 }
3528 } else {
3529 append_candidates(&mut msg, accessible_path_strings);
3530 err.help(msg);
3531 }
3532 showed = true;
3533 }
3534 if !inaccessible_path_strings.is_empty()
3535 && (!#[allow(non_exhaustive_omitted_patterns)] match mode {
DiagMode::Import { unresolved_import: false, .. } => true,
_ => false,
}matches!(mode, DiagMode::Import { unresolved_import: false, .. }))
3536 {
3537 let prefix =
3538 if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
3539 if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
3540 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{2} `{3}`{0} exists but is inaccessible",
if let DiagMode::Pattern = mode { ", which" } else { "" },
prefix, descr, name))
})format!(
3541 "{prefix}{descr} `{name}`{} exists but is inaccessible",
3542 if let DiagMode::Pattern = mode { ", which" } else { "" }
3543 );
3544
3545 if let Some(source_span) = source_span {
3546 let span = tcx.sess.source_map().guess_head_span(*source_span);
3547 let mut multi_span = MultiSpan::from_span(span);
3548 multi_span.push_span_label(span, "not accessible");
3549 err.span_note(multi_span, msg);
3550 } else {
3551 err.note(msg);
3552 }
3553 if let Some(note) = (*note).as_deref() {
3554 err.note(note.to_string());
3555 }
3556 } else {
3557 let descr = inaccessible_path_strings
3558 .iter()
3559 .map(|&(_, descr, _, _, _)| descr)
3560 .all_equal_value()
3561 .unwrap_or("item");
3562 let plural_descr =
3563 if descr.ends_with('s') { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}es", descr))
})format!("{descr}es") } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}s", descr))
})format!("{descr}s") };
3564
3565 let mut msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}these {1} exist but are inaccessible",
prefix, plural_descr))
})format!("{prefix}these {plural_descr} exist but are inaccessible");
3566 let mut has_colon = false;
3567
3568 let mut spans = Vec::new();
3569 for (name, _, source_span, _, _) in &inaccessible_path_strings {
3570 if let Some(source_span) = source_span {
3571 let span = tcx.sess.source_map().guess_head_span(*source_span);
3572 spans.push((name, span));
3573 } else {
3574 if !has_colon {
3575 msg.push(':');
3576 has_colon = true;
3577 }
3578 msg.push('\n');
3579 msg.push_str(name);
3580 }
3581 }
3582
3583 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3584 for (name, span) in spans {
3585 multi_span.push_span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`: not accessible", name))
})format!("`{name}`: not accessible"));
3586 }
3587
3588 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3589 err.note(note.clone());
3590 }
3591
3592 err.span_note(multi_span, msg);
3593 }
3594 showed = true;
3595 }
3596 showed
3597}
3598
3599#[derive(#[automatically_derived]
impl ::core::fmt::Debug for UsePlacementFinder {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"UsePlacementFinder", "target_module", &self.target_module,
"first_legal_span", &self.first_legal_span, "first_use_span",
&&self.first_use_span)
}
}Debug)]
3600struct UsePlacementFinder {
3601 target_module: NodeId,
3602 first_legal_span: Option<Span>,
3603 first_use_span: Option<Span>,
3604}
3605
3606impl UsePlacementFinder {
3607 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3608 let mut finder =
3609 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3610 finder.visit_crate(krate);
3611 if let Some(use_span) = finder.first_use_span {
3612 (Some(use_span), FoundUse::Yes)
3613 } else {
3614 (finder.first_legal_span, FoundUse::No)
3615 }
3616 }
3617}
3618
3619impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
3620 fn visit_crate(&mut self, c: &Crate) {
3621 if self.target_module == CRATE_NODE_ID {
3622 let inject = c.spans.inject_use_span;
3623 if is_span_suitable_for_use_injection(inject) {
3624 self.first_legal_span = Some(inject);
3625 }
3626 self.first_use_span = search_for_any_use_in_items(&c.items);
3627 } else {
3628 visit::walk_crate(self, c);
3629 }
3630 }
3631
3632 fn visit_item(&mut self, item: &'tcx ast::Item) {
3633 if self.target_module == item.id {
3634 if let ItemKind::Mod(_, _, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
3635 let inject = mod_spans.inject_use_span;
3636 if is_span_suitable_for_use_injection(inject) {
3637 self.first_legal_span = Some(inject);
3638 }
3639 self.first_use_span = search_for_any_use_in_items(items);
3640 }
3641 } else {
3642 visit::walk_item(self, item);
3643 }
3644 }
3645}
3646
3647#[derive(#[automatically_derived]
impl ::core::default::Default for BindingVisitor {
#[inline]
fn default() -> BindingVisitor {
BindingVisitor {
identifiers: ::core::default::Default::default(),
spans: ::core::default::Default::default(),
}
}
}Default)]
3648struct BindingVisitor {
3649 identifiers: Vec<Symbol>,
3650 spans: FxHashMap<Symbol, Vec<Span>>,
3651}
3652
3653impl<'tcx> Visitor<'tcx> for BindingVisitor {
3654 fn visit_pat(&mut self, pat: &ast::Pat) {
3655 if let ast::PatKind::Ident(_, ident, _) = pat.kind {
3656 self.identifiers.push(ident.name);
3657 self.spans.entry(ident.name).or_default().push(ident.span);
3658 }
3659 visit::walk_pat(self, pat);
3660 }
3661}
3662
3663fn search_for_any_use_in_items(items: &[Box<ast::Item>]) -> Option<Span> {
3664 for item in items {
3665 if let ItemKind::Use(..) = item.kind
3666 && is_span_suitable_for_use_injection(item.span)
3667 {
3668 let mut lo = item.span.lo();
3669 for attr in &item.attrs {
3670 if attr.span.eq_ctxt(item.span) {
3671 lo = std::cmp::min(lo, attr.span.lo());
3672 }
3673 }
3674 return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3675 }
3676 }
3677 None
3678}
3679
3680fn is_span_suitable_for_use_injection(s: Span) -> bool {
3681 !s.from_expansion()
3684}