1use std::mem;
3use std::ops::ControlFlow;
4
5use itertools::Itertools as _;
6use rustc_ast::visit::{self, Visitor};
7use rustc_ast::{
8 self as ast, CRATE_NODE_ID, Crate, DUMMY_NODE_ID, ItemKind, ModKind, NodeId, Path,
9 join_path_idents,
10};
11use rustc_ast_pretty::pprust;
12use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13use rustc_data_structures::unord::{UnordMap, UnordSet};
14use rustc_errors::codes::*;
15use rustc_errors::{
16 Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, MultiSpan, SuggestionStyle,
17 struct_span_code_err,
18};
19use rustc_feature::BUILTIN_ATTRIBUTES;
20use rustc_hir::attrs::{CfgEntry, StrippedCfgItem};
21use rustc_hir::def::Namespace::{self, *};
22use rustc_hir::def::{CtorKind, CtorOf, DefKind, MacroKinds, NonMacroAttrKind, PerNS};
23use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
24use rustc_hir::{PrimTy, Stability, StabilityLevel, find_attr};
25use rustc_middle::bug;
26use rustc_middle::ty::{TyCtxt, Visibility};
27use rustc_session::Session;
28use rustc_session::lint::builtin::{
29 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS, AMBIGUOUS_IMPORT_VISIBILITIES,
30 AMBIGUOUS_PANIC_IMPORTS, MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
31};
32use rustc_session::utils::was_invoked_from_cargo;
33use rustc_span::edit_distance::find_best_match_for_name;
34use rustc_span::edition::Edition;
35use rustc_span::hygiene::MacroKind;
36use rustc_span::source_map::SourceMap;
37use rustc_span::{
38 BytePos, Ident, RemapPathScopeComponents, Span, Spanned, Symbol, SyntaxContext, kw, sym,
39};
40use thin_vec::{ThinVec, thin_vec};
41use tracing::{debug, instrument};
42
43use crate::errors::{
44 self, AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion, ConsiderAddingADerive,
45 ExplicitUnsafeTraits, MacroDefinedLater, MacroRulesNot, MacroSuggMovePosition,
46 MaybeMissingMacroRulesName,
47};
48use crate::hygiene::Macros20NormalizedSyntaxContext;
49use crate::imports::{Import, ImportKind};
50use crate::late::{DiagMetadata, PatternSource, Rib};
51use crate::{
52 AmbiguityError, AmbiguityKind, AmbiguityWarning, BindingError, BindingKey, Decl, DeclKind,
53 DelayedVisResolutionError, Finalize, ForwardGenericParamBanReason, HasGenericParams, IdentKey,
54 LateDecl, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult,
55 PrivacyError, Res, ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used,
56 VisResolutionError, errors as errs, path_names_to_string,
57};
58
59pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
61
62pub(crate) type LabelSuggestion = (Ident, bool);
65
66#[derive(#[automatically_derived]
impl ::core::clone::Clone for StructCtor {
#[inline]
fn clone(&self) -> StructCtor {
StructCtor {
res: ::core::clone::Clone::clone(&self.res),
vis: ::core::clone::Clone::clone(&self.vis),
field_visibilities: ::core::clone::Clone::clone(&self.field_visibilities),
}
}
}Clone)]
67pub(crate) struct StructCtor {
68 pub res: Res,
69 pub vis: Visibility<DefId>,
70 pub field_visibilities: Vec<Visibility<DefId>>,
71}
72
73impl StructCtor {
74 pub(crate) fn has_private_fields<'ra>(&self, m: Module<'ra>, r: &Resolver<'ra, '_>) -> bool {
75 self.field_visibilities.iter().any(|&vis| !r.is_accessible_from(vis, m))
76 }
77}
78
79#[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)]
80pub(crate) enum SuggestionTarget {
81 SimilarlyNamed,
83 SingleItem,
85}
86
87#[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)]
88pub(crate) struct TypoSuggestion {
89 pub candidate: Symbol,
90 pub span: Option<Span>,
93 pub res: Res,
94 pub target: SuggestionTarget,
95}
96
97impl TypoSuggestion {
98 pub(crate) fn new(candidate: Symbol, span: Span, res: Res) -> TypoSuggestion {
99 Self { candidate, span: Some(span), res, target: SuggestionTarget::SimilarlyNamed }
100 }
101 pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
102 Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
103 }
104 pub(crate) fn single_item(candidate: Symbol, span: Span, res: Res) -> TypoSuggestion {
105 Self { candidate, span: Some(span), res, target: SuggestionTarget::SingleItem }
106 }
107}
108
109#[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)]
111pub(crate) struct ImportSuggestion {
112 pub did: Option<DefId>,
113 pub descr: &'static str,
114 pub path: Path,
115 pub accessible: bool,
116 pub doc_visible: bool,
118 pub via_import: bool,
119 pub note: Option<String>,
121 pub is_stable: bool,
122}
123
124fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
132 let impl_span = sm.span_until_char(impl_span, '<');
133 sm.span_until_whitespace(impl_span)
134}
135
136impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
137 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
138 self.tcx.dcx()
139 }
140
141 pub(crate) fn report_errors(&mut self, krate: &Crate) {
142 self.report_delayed_vis_resolution_errors();
143 self.report_with_use_injections(krate);
144
145 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
146 self.lint_buffer.buffer_lint(
147 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
148 CRATE_NODE_ID,
149 span_use,
150 errors::MacroExpandedMacroExportsAccessedByAbsolutePaths { definition: span_def },
151 );
152 }
153
154 for ambiguity_error in &self.ambiguity_errors {
155 let mut diag = self.ambiguity_diagnostic(ambiguity_error);
156
157 if let Some(ambiguity_warning) = ambiguity_error.warning {
158 let node_id = match ambiguity_error.b1.0.kind {
159 DeclKind::Import { import, .. } => import.root_id,
160 DeclKind::Def(_) => CRATE_NODE_ID,
161 };
162
163 let lint = match ambiguity_warning {
164 _ if ambiguity_error.ambig_vis.is_some() => AMBIGUOUS_IMPORT_VISIBILITIES,
165 AmbiguityWarning::GlobImport => AMBIGUOUS_GLOB_IMPORTS,
166 AmbiguityWarning::PanicImport => AMBIGUOUS_PANIC_IMPORTS,
167 };
168
169 self.lint_buffer.buffer_lint(lint, node_id, diag.ident.span, diag);
170 } else {
171 diag.is_error = true;
172 self.dcx().emit_err(diag);
173 }
174 }
175
176 let mut reported_spans = FxHashSet::default();
177 for error in mem::take(&mut self.privacy_errors) {
178 if reported_spans.insert(error.dedup_span) {
179 self.report_privacy_error(&error);
180 }
181 }
182 }
183
184 fn report_delayed_vis_resolution_errors(&mut self) {
185 for DelayedVisResolutionError { vis, parent_scope, error } in
186 mem::take(&mut self.delayed_vis_resolution_errors)
187 {
188 match self.try_resolve_visibility(&parent_scope, &vis, true) {
189 Ok(_) => self.report_vis_error(error),
190 Err(error) => self.report_vis_error(error),
191 };
192 }
193 }
194
195 fn report_with_use_injections(&mut self, krate: &Crate) {
196 for UseError { mut err, candidates, node_id, instead, suggestion, path, is_call } in
197 mem::take(&mut self.use_injections)
198 {
199 let (span, found_use) = if node_id != DUMMY_NODE_ID {
200 UsePlacementFinder::check(krate, node_id)
201 } else {
202 (None, FoundUse::No)
203 };
204
205 if !candidates.is_empty() {
206 show_candidates(
207 self.tcx,
208 &mut err,
209 span,
210 &candidates,
211 if instead { Instead::Yes } else { Instead::No },
212 found_use,
213 DiagMode::Normal,
214 path,
215 "",
216 );
217 err.emit();
218 } else if let Some((span, msg, sugg, appl)) = suggestion {
219 err.span_suggestion_verbose(span, msg, sugg, appl);
220 err.emit();
221 } else if let [segment] = path.as_slice()
222 && is_call
223 {
224 err.stash(segment.ident.span, rustc_errors::StashKey::CallIntoMethod);
225 } else {
226 err.emit();
227 }
228 }
229 }
230
231 pub(crate) fn report_conflict(
232 &mut self,
233 ident: IdentKey,
234 ns: Namespace,
235 old_binding: Decl<'ra>,
236 new_binding: Decl<'ra>,
237 ) {
238 if old_binding.span.lo() > new_binding.span.lo() {
240 return self.report_conflict(ident, ns, new_binding, old_binding);
241 }
242
243 let container = match old_binding.parent_module.unwrap().kind {
244 ModuleKind::Def(kind, def_id, _, _) => kind.descr(def_id),
247 ModuleKind::Block => "block",
248 };
249
250 let (name, span) =
251 (ident.name, self.tcx.sess.source_map().guess_head_span(new_binding.span));
252
253 if self.name_already_seen.get(&name) == Some(&span) {
254 return;
255 }
256
257 let old_kind = match (ns, old_binding.res()) {
258 (ValueNS, _) => "value",
259 (MacroNS, _) => "macro",
260 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
261 (TypeNS, Res::Def(DefKind::Mod, _)) => "module",
262 (TypeNS, Res::Def(DefKind::Trait, _)) => "trait",
263 (TypeNS, _) => "type",
264 };
265
266 let code = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
267 (true, true) => E0259,
268 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
269 true => E0254,
270 false => E0260,
271 },
272 _ => match (old_binding.is_import_user_facing(), new_binding.is_import_user_facing()) {
273 (false, false) => E0428,
274 (true, true) => E0252,
275 _ => E0255,
276 },
277 };
278
279 let label = match new_binding.is_import_user_facing() {
280 true => errors::NameDefinedMultipleTimeLabel::Reimported { span, name },
281 false => errors::NameDefinedMultipleTimeLabel::Redefined { span, name },
282 };
283
284 let old_binding_label =
285 (!old_binding.span.is_dummy() && old_binding.span != span).then(|| {
286 let span = self.tcx.sess.source_map().guess_head_span(old_binding.span);
287 match old_binding.is_import_user_facing() {
288 true => errors::NameDefinedMultipleTimeOldBindingLabel::Import {
289 span,
290 old_kind,
291 name,
292 },
293 false => errors::NameDefinedMultipleTimeOldBindingLabel::Definition {
294 span,
295 old_kind,
296 name,
297 },
298 }
299 });
300
301 let mut err = self
302 .dcx()
303 .create_err(errors::NameDefinedMultipleTime {
304 span,
305 name,
306 descr: ns.descr(),
307 container,
308 label,
309 old_binding_label,
310 })
311 .with_code(code);
312
313 use DeclKind::Import;
315 let can_suggest = |binding: Decl<'_>, import: self::Import<'_>| {
316 !binding.span.is_dummy()
317 && !#[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::MacroUse { .. } | ImportKind::MacroExport => true,
_ => false,
}matches!(import.kind, ImportKind::MacroUse { .. } | ImportKind::MacroExport)
318 };
319 let import = match (&new_binding.kind, &old_binding.kind) {
320 (Import { import: new, .. }, Import { import: old, .. })
323 if {
324 (new.has_attributes || old.has_attributes)
325 && can_suggest(old_binding, *old)
326 && can_suggest(new_binding, *new)
327 } =>
328 {
329 if old.has_attributes {
330 Some((*new, new_binding.span, true))
331 } else {
332 Some((*old, old_binding.span, true))
333 }
334 }
335 (Import { import, .. }, other) if can_suggest(new_binding, *import) => {
337 Some((*import, new_binding.span, other.is_import()))
338 }
339 (other, Import { import, .. }) if can_suggest(old_binding, *import) => {
340 Some((*import, old_binding.span, other.is_import()))
341 }
342 _ => None,
343 };
344
345 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
347 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
348 let from_item =
349 self.extern_prelude.get(&ident).is_none_or(|entry| entry.introduced_by_item());
350 let should_remove_import = duplicate
354 && !has_dummy_span
355 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
356
357 match import {
358 Some((import, span, true)) if should_remove_import && import.is_nested() => {
359 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span);
360 }
361 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
362 err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport {
365 span: import.use_span_with_attributes,
366 });
367 }
368 Some((import, span, _)) => {
369 self.add_suggestion_for_rename_of_use(&mut err, name, import, span);
370 }
371 _ => {}
372 }
373
374 err.emit();
375 self.name_already_seen.insert(name, span);
376 }
377
378 fn add_suggestion_for_rename_of_use(
388 &self,
389 err: &mut Diag<'_>,
390 name: Symbol,
391 import: Import<'_>,
392 binding_span: Span,
393 ) {
394 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
395 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Other{0}", name))
})format!("Other{name}")
396 } else {
397 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("other_{0}", name))
})format!("other_{name}")
398 };
399
400 let mut suggestion = None;
401 let mut span = binding_span;
402 match import.kind {
403 ImportKind::Single { source, .. } => {
404 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
405 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(binding_span)
406 && pos as usize <= snippet.len()
407 {
408 span = binding_span.with_lo(binding_span.lo() + BytePos(pos)).with_hi(
409 binding_span.hi() - BytePos(if snippet.ends_with(';') { 1 } else { 0 }),
410 );
411 suggestion = Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", suggested_name))
})format!(" as {suggested_name}"));
412 }
413 }
414 ImportKind::ExternCrate { source, target, .. } => {
415 suggestion = Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern crate {0} as {1};",
source.unwrap_or(target.name), suggested_name))
})format!(
416 "extern crate {} as {};",
417 source.unwrap_or(target.name),
418 suggested_name,
419 ))
420 }
421 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
422 }
423
424 if let Some(suggestion) = suggestion {
425 err.subdiagnostic(ChangeImportBindingSuggestion { span, suggestion });
426 } else {
427 err.subdiagnostic(ChangeImportBinding { span });
428 }
429 }
430
431 fn add_suggestion_for_duplicate_nested_use(
454 &self,
455 err: &mut Diag<'_>,
456 import: Import<'_>,
457 binding_span: Span,
458 ) {
459 if !import.is_nested() {
::core::panicking::panic("assertion failed: import.is_nested()")
};assert!(import.is_nested());
460
461 let (found_closing_brace, span) =
469 find_span_of_binding_until_next_binding(self.tcx.sess, binding_span, import.use_span);
470
471 if found_closing_brace {
474 if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) {
475 err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport { span });
476 } else {
477 err.subdiagnostic(errors::RemoveUnnecessaryImport {
480 span: import.use_span_with_attributes,
481 });
482 }
483
484 return;
485 }
486
487 err.subdiagnostic(errors::RemoveUnnecessaryImport { span });
488 }
489
490 pub(crate) fn lint_if_path_starts_with_module(
491 &mut self,
492 finalize: Finalize,
493 path: &[Segment],
494 second_binding: Option<Decl<'_>>,
495 ) {
496 let Finalize { node_id, root_span, .. } = finalize;
497
498 let first_name = match path.get(0) {
499 Some(seg) if seg.ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015() => {
501 seg.ident.name
502 }
503 _ => return,
504 };
505
506 if first_name != kw::PathRoot {
509 return;
510 }
511
512 match path.get(1) {
513 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
515 Some(_) => {}
517 None => return,
521 }
522
523 if let Some(binding) = second_binding
527 && let DeclKind::Import { import, .. } = binding.kind
528 && let ImportKind::ExternCrate { source: None, .. } = import.kind
530 {
531 return;
532 }
533
534 self.lint_buffer.dyn_buffer_lint_any(
535 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
536 node_id,
537 root_span,
538 move |dcx, level, sess| {
539 let (replacement, applicability) = match sess
540 .downcast_ref::<Session>()
541 .expect("expected a `Session`")
542 .source_map()
543 .span_to_snippet(root_span)
544 {
545 Ok(ref s) => {
546 let opt_colon = if s.trim_start().starts_with("::") { "" } else { "::" };
549
550 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}{1}", opt_colon, s))
})format!("crate{opt_colon}{s}"), Applicability::MachineApplicable)
551 }
552 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
553 };
554 errors::AbsPathWithModule {
555 sugg: errors::AbsPathWithModuleSugg {
556 span: root_span,
557 applicability,
558 replacement,
559 },
560 }
561 .into_diag(dcx, level)
562 },
563 );
564 }
565
566 pub(crate) fn add_module_candidates(
567 &self,
568 module: Module<'ra>,
569 names: &mut Vec<TypoSuggestion>,
570 filter_fn: &impl Fn(Res) -> bool,
571 ctxt: Option<SyntaxContext>,
572 ) {
573 module.for_each_child(self, |_this, ident, orig_ident_span, _ns, binding| {
574 let res = binding.res();
575 if filter_fn(res) && ctxt.is_none_or(|ctxt| ctxt == *ident.ctxt) {
576 names.push(TypoSuggestion::new(ident.name, orig_ident_span, res));
577 }
578 });
579 }
580
581 pub(crate) fn report_error(
586 &mut self,
587 span: Span,
588 resolution_error: ResolutionError<'ra>,
589 ) -> ErrorGuaranteed {
590 self.into_struct_error(span, resolution_error).emit()
591 }
592
593 pub(crate) fn into_struct_error(
594 &mut self,
595 span: Span,
596 resolution_error: ResolutionError<'ra>,
597 ) -> Diag<'_> {
598 match resolution_error {
599 ResolutionError::GenericParamsFromOuterItem {
600 outer_res,
601 has_generic_params,
602 def_kind,
603 inner_item,
604 current_self_ty,
605 } => {
606 use errs::GenericParamsFromOuterItemLabel as Label;
607 let static_or_const = match def_kind {
608 DefKind::Static { .. } => {
609 Some(errs::GenericParamsFromOuterItemStaticOrConst::Static)
610 }
611 DefKind::Const { .. } => {
612 Some(errs::GenericParamsFromOuterItemStaticOrConst::Const)
613 }
614 _ => None,
615 };
616 let is_self =
617 #[allow(non_exhaustive_omitted_patterns)] match outer_res {
Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => true,
_ => false,
}matches!(outer_res, Res::SelfTyParam { .. } | Res::SelfTyAlias { .. });
618 let mut err = errs::GenericParamsFromOuterItem {
619 span,
620 label: None,
621 refer_to_type_directly: None,
622 use_let: None,
623 sugg: None,
624 static_or_const,
625 is_self,
626 item: inner_item.as_ref().map(|(label_span, _, kind)| {
627 errs::GenericParamsFromOuterItemInnerItem {
628 span: *label_span,
629 descr: kind.descr().to_string(),
630 is_self,
631 }
632 }),
633 };
634
635 let sm = self.tcx.sess.source_map();
636 let def_id = match outer_res {
639 Res::SelfTyParam { .. } => {
640 err.label = Some(Label::SelfTyParam(span));
641 None
642 }
643 Res::SelfTyAlias { alias_to: def_id, .. } => {
644 err.label = Some(Label::SelfTyAlias(reduce_impl_span_to_impl_keyword(
645 sm,
646 self.def_span(def_id),
647 )));
648 err.refer_to_type_directly =
649 current_self_ty.map(|snippet| errs::UseTypeDirectly { span, snippet });
650 None
651 }
652 Res::Def(DefKind::TyParam, def_id) => {
653 err.label = Some(Label::TyParam(self.def_span(def_id)));
654 Some(def_id)
655 }
656 Res::Def(DefKind::ConstParam, def_id) => {
657 err.label = Some(Label::ConstParam(self.def_span(def_id)));
658 Some(def_id)
659 }
660 _ => {
661 ::rustc_middle::util::bug::bug_fmt(format_args!("GenericParamsFromOuterItem should only be used with Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or DefKind::ConstParam"));bug!(
662 "GenericParamsFromOuterItem should only be used with \
663 Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
664 DefKind::ConstParam"
665 );
666 }
667 };
668
669 if let Some((_, item_span, ItemKind::Const(_))) = inner_item.as_ref() {
670 err.use_let = Some(errs::GenericParamsFromOuterItemUseLet {
671 span: sm.span_until_whitespace(*item_span),
672 });
673 }
674
675 if let Some(def_id) = def_id
676 && let HasGenericParams::Yes(span) = has_generic_params
677 && !#[allow(non_exhaustive_omitted_patterns)] match inner_item {
Some((_, _, ItemKind::Delegation(..))) => true,
_ => false,
}matches!(inner_item, Some((_, _, ItemKind::Delegation(..))))
678 {
679 let name = self.tcx.item_name(def_id);
680 let (span, snippet) = if span.is_empty() {
681 let snippet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", name))
})format!("<{name}>");
682 (span, snippet)
683 } else {
684 let span = sm.span_through_char(span, '<').shrink_to_hi();
685 let snippet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", name))
})format!("{name}, ");
686 (span, snippet)
687 };
688 err.sugg = Some(errs::GenericParamsFromOuterItemSugg { span, snippet });
689 }
690
691 self.dcx().create_err(err)
692 }
693 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
694 .dcx()
695 .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
696 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
697 self.dcx().create_err(errs::MethodNotMemberOfTrait {
698 span,
699 method,
700 trait_,
701 sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
702 span: method.span,
703 candidate: c,
704 }),
705 })
706 }
707 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
708 self.dcx().create_err(errs::TypeNotMemberOfTrait {
709 span,
710 type_,
711 trait_,
712 sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
713 span: type_.span,
714 candidate: c,
715 }),
716 })
717 }
718 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
719 self.dcx().create_err(errs::ConstNotMemberOfTrait {
720 span,
721 const_,
722 trait_,
723 sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
724 span: const_.span,
725 candidate: c,
726 }),
727 })
728 }
729 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
730 let BindingError { name, target, origin, could_be_path } = binding_error;
731
732 let mut target_sp = target.iter().map(|pat| pat.span).collect::<Vec<_>>();
733 target_sp.sort();
734 target_sp.dedup();
735 let mut origin_sp = origin.iter().map(|(span, _)| *span).collect::<Vec<_>>();
736 origin_sp.sort();
737 origin_sp.dedup();
738
739 let msp = MultiSpan::from_spans(target_sp.clone());
740 let mut err = self
741 .dcx()
742 .create_err(errors::VariableIsNotBoundInAllPatterns { multispan: msp, name });
743 for sp in target_sp {
744 err.subdiagnostic(errors::PatternDoesntBindName { span: sp, name });
745 }
746 for sp in &origin_sp {
747 err.subdiagnostic(errors::VariableNotInAllPatterns { span: *sp });
748 }
749 let mut suggested_typo = false;
750 if !target.iter().all(|pat| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
ast::PatKind::Ident(..) => true,
_ => false,
}matches!(pat.kind, ast::PatKind::Ident(..)))
751 && !origin.iter().all(|(_, pat)| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
ast::PatKind::Ident(..) => true,
_ => false,
}matches!(pat.kind, ast::PatKind::Ident(..)))
752 {
753 let mut target_visitor = BindingVisitor::default();
756 for pat in &target {
757 target_visitor.visit_pat(pat);
758 }
759 target_visitor.identifiers.sort();
760 target_visitor.identifiers.dedup();
761 let mut origin_visitor = BindingVisitor::default();
762 for (_, pat) in &origin {
763 origin_visitor.visit_pat(pat);
764 }
765 origin_visitor.identifiers.sort();
766 origin_visitor.identifiers.dedup();
767 if let Some(typo) =
769 find_best_match_for_name(&target_visitor.identifiers, name.name, None)
770 && !origin_visitor.identifiers.contains(&typo)
771 {
772 err.subdiagnostic(errors::PatternBindingTypo { spans: origin_sp, typo });
773 suggested_typo = true;
774 }
775 }
776 if could_be_path {
777 let import_suggestions = self.lookup_import_candidates(
778 name,
779 Namespace::ValueNS,
780 &parent_scope,
781 &|res: Res| {
782 #[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!(
783 res,
784 Res::Def(
785 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
786 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
787 | DefKind::Const { .. }
788 | DefKind::AssocConst { .. },
789 _,
790 )
791 )
792 },
793 );
794
795 if import_suggestions.is_empty() && !suggested_typo {
796 let kind_matches: [fn(DefKind) -> bool; 4] = [
797 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => true,
_ => false,
}matches!(kind, DefKind::Ctor(CtorOf::Variant, CtorKind::Const)),
798 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => true,
_ => false,
}matches!(kind, DefKind::Ctor(CtorOf::Struct, CtorKind::Const)),
799 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Const { .. } => true,
_ => false,
}matches!(kind, DefKind::Const { .. }),
800 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::AssocConst { .. } => true,
_ => false,
}matches!(kind, DefKind::AssocConst { .. }),
801 ];
802 let mut local_names = ::alloc::vec::Vec::new()vec![];
803 self.add_module_candidates(
804 parent_scope.module,
805 &mut local_names,
806 &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(_, _) => true,
_ => false,
}matches!(res, Res::Def(_, _)),
807 None,
808 );
809 let local_names: FxHashSet<_> = local_names
810 .into_iter()
811 .filter_map(|s| match s.res {
812 Res::Def(_, def_id) => Some(def_id),
813 _ => None,
814 })
815 .collect();
816
817 let mut local_suggestions = ::alloc::vec::Vec::new()vec![];
818 let mut suggestions = ::alloc::vec::Vec::new()vec![];
819 for matches_kind in kind_matches {
820 if let Some(suggestion) = self.early_lookup_typo_candidate(
821 ScopeSet::All(Namespace::ValueNS),
822 &parent_scope,
823 name,
824 &|res: Res| match res {
825 Res::Def(k, _) => matches_kind(k),
826 _ => false,
827 },
828 ) && let Res::Def(kind, mut def_id) = suggestion.res
829 {
830 if let DefKind::Ctor(_, _) = kind {
831 def_id = self.tcx.parent(def_id);
832 }
833 let kind = kind.descr(def_id);
834 if local_names.contains(&def_id) {
835 local_suggestions.push((
838 suggestion.candidate,
839 suggestion.candidate.to_string(),
840 kind,
841 ));
842 } else {
843 suggestions.push((
844 suggestion.candidate,
845 self.def_path_str(def_id),
846 kind,
847 ));
848 }
849 }
850 }
851 let suggestions = if !local_suggestions.is_empty() {
852 local_suggestions
855 } else {
856 suggestions
857 };
858 for (name, sugg, kind) in suggestions {
859 err.span_suggestion_verbose(
860 span,
861 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use the similarly named {0} `{1}`",
kind, name))
})format!(
862 "you might have meant to use the similarly named {kind} `{name}`",
863 ),
864 sugg,
865 Applicability::MaybeIncorrect,
866 );
867 suggested_typo = true;
868 }
869 }
870 if import_suggestions.is_empty() && !suggested_typo {
871 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!(
872 "if you meant to match on a unit struct, unit variant or a `const` \
873 item, consider making the path in the pattern qualified: \
874 `path::to::ModOrType::{name}`",
875 );
876 err.span_help(span, help_msg);
877 }
878 show_candidates(
879 self.tcx,
880 &mut err,
881 Some(span),
882 &import_suggestions,
883 Instead::No,
884 FoundUse::Yes,
885 DiagMode::Pattern,
886 ::alloc::vec::Vec::new()vec![],
887 "",
888 );
889 }
890 err
891 }
892 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
893 self.dcx().create_err(errs::VariableBoundWithDifferentMode {
894 span,
895 first_binding_span,
896 variable_name,
897 })
898 }
899 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
900 .dcx()
901 .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
902 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
903 .dcx()
904 .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
905 ResolutionError::UndeclaredLabel { name, suggestion } => {
906 let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
907 {
908 Some((ident, true)) => (
910 (
911 Some(errs::LabelWithSimilarNameReachable(ident.span)),
912 Some(errs::TryUsingSimilarlyNamedLabel {
913 span,
914 ident_name: ident.name,
915 }),
916 ),
917 None,
918 ),
919 Some((ident, false)) => (
921 (None, None),
922 Some(errs::UnreachableLabelWithSimilarNameExists {
923 ident_span: ident.span,
924 }),
925 ),
926 None => ((None, None), None),
928 };
929 self.dcx().create_err(errs::UndeclaredLabel {
930 span,
931 name,
932 sub_reachable,
933 sub_reachable_suggestion,
934 sub_unreachable,
935 })
936 }
937 ResolutionError::FailedToResolve { segment, label, suggestion, module, message } => {
938 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}");
939 err.span_label(span, label);
940
941 if let Some((suggestions, msg, applicability)) = suggestion {
942 if suggestions.is_empty() {
943 err.help(msg);
944 return err;
945 }
946 err.multipart_suggestion(msg, suggestions, applicability);
947 }
948
949 let module = match module {
950 Some(ModuleOrUniformRoot::Module(m)) if let Some(id) = m.opt_def_id() => id,
951 _ => CRATE_DEF_ID.to_def_id(),
952 };
953 self.find_cfg_stripped(&mut err, &segment, module);
954
955 err
956 }
957 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
958 self.dcx().create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
959 }
960 ResolutionError::AttemptToUseNonConstantValueInConstant {
961 ident,
962 suggestion,
963 current,
964 type_span,
965 } => {
966 let sp = self
975 .tcx
976 .sess
977 .source_map()
978 .span_extend_to_prev_str(ident.span, current, true, false);
979
980 let (with, with_label, without) = match sp {
981 Some(sp) if !self.tcx.sess.source_map().is_multiline(sp) => {
982 let sp = sp
983 .with_lo(BytePos(sp.lo().0 - (current.len() as u32)))
984 .until(ident.span);
985
986 let is_simple_binding =
994 self.tcx.sess.source_map().span_to_snippet(sp).is_ok_and(|snippet| {
995 let after_keyword = snippet[current.len()..].trim();
996 after_keyword.is_empty() || after_keyword == "mut"
997 });
998
999 if is_simple_binding {
1000 (
1001 Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
1002 span: sp,
1003 suggestion,
1004 current,
1005 type_span,
1006 }),
1007 Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion { span }),
1008 None,
1009 )
1010 } else {
1011 (
1012 None,
1013 Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion { span }),
1014 None,
1015 )
1016 }
1017 }
1018 _ => (
1019 None,
1020 None,
1021 Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
1022 ident_span: ident.span,
1023 suggestion,
1024 }),
1025 ),
1026 };
1027
1028 self.dcx().create_err(errs::AttemptToUseNonConstantValueInConstant {
1029 span,
1030 with,
1031 with_label,
1032 without,
1033 })
1034 }
1035 ResolutionError::BindingShadowsSomethingUnacceptable {
1036 shadowing_binding,
1037 name,
1038 participle,
1039 article,
1040 shadowed_binding,
1041 shadowed_binding_span,
1042 } => self.dcx().create_err(errs::BindingShadowsSomethingUnacceptable {
1043 span,
1044 shadowing_binding,
1045 shadowed_binding,
1046 article,
1047 sub_suggestion: match (shadowing_binding, shadowed_binding) {
1048 (
1049 PatternSource::Match,
1050 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
1051 ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
1052 _ => None,
1053 },
1054 shadowed_binding_span,
1055 participle,
1056 name,
1057 }),
1058 ResolutionError::ForwardDeclaredGenericParam(param, reason) => match reason {
1059 ForwardGenericParamBanReason::Default => {
1060 self.dcx().create_err(errs::ForwardDeclaredGenericParam { param, span })
1061 }
1062 ForwardGenericParamBanReason::ConstParamTy => self
1063 .dcx()
1064 .create_err(errs::ForwardDeclaredGenericInConstParamTy { param, span }),
1065 },
1066 ResolutionError::ParamInTyOfConstParam { name } => {
1067 self.dcx().create_err(errs::ParamInTyOfConstParam { span, name })
1068 }
1069 ResolutionError::ParamInNonTrivialAnonConst { is_gca, name, param_kind: is_type } => {
1070 self.dcx().create_err(errs::ParamInNonTrivialAnonConst {
1071 span,
1072 name,
1073 param_kind: is_type,
1074 help: self.tcx.sess.is_nightly_build(),
1075 is_gca,
1076 help_gca: is_gca,
1077 })
1078 }
1079 ResolutionError::ParamInEnumDiscriminant { name, param_kind: is_type } => self
1080 .dcx()
1081 .create_err(errs::ParamInEnumDiscriminant { span, name, param_kind: is_type }),
1082 ResolutionError::ForwardDeclaredSelf(reason) => match reason {
1083 ForwardGenericParamBanReason::Default => {
1084 self.dcx().create_err(errs::SelfInGenericParamDefault { span })
1085 }
1086 ForwardGenericParamBanReason::ConstParamTy => {
1087 self.dcx().create_err(errs::SelfInConstGenericTy { span })
1088 }
1089 },
1090 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
1091 let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
1092 match suggestion {
1093 Some((ident, true)) => (
1095 (
1096 Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
1097 Some(errs::UnreachableLabelSubSuggestion {
1098 span,
1099 ident_name: ident.name,
1102 }),
1103 ),
1104 None,
1105 ),
1106 Some((ident, false)) => (
1108 (None, None),
1109 Some(errs::UnreachableLabelSubLabelUnreachable {
1110 ident_span: ident.span,
1111 }),
1112 ),
1113 None => ((None, None), None),
1115 };
1116 self.dcx().create_err(errs::UnreachableLabel {
1117 span,
1118 name,
1119 definition_span,
1120 sub_suggestion,
1121 sub_suggestion_label,
1122 sub_unreachable_label,
1123 })
1124 }
1125 ResolutionError::TraitImplMismatch {
1126 name,
1127 kind,
1128 code,
1129 trait_item_span,
1130 trait_path,
1131 } => self
1132 .dcx()
1133 .create_err(errors::TraitImplMismatch {
1134 span,
1135 name,
1136 kind,
1137 trait_path,
1138 trait_item_span,
1139 })
1140 .with_code(code),
1141 ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
1142 .dcx()
1143 .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
1144 ResolutionError::InvalidAsmSym => self.dcx().create_err(errs::InvalidAsmSym { span }),
1145 ResolutionError::LowercaseSelf => self.dcx().create_err(errs::LowercaseSelf { span }),
1146 ResolutionError::BindingInNeverPattern => {
1147 self.dcx().create_err(errs::BindingInNeverPattern { span })
1148 }
1149 }
1150 }
1151
1152 pub(crate) fn report_vis_error(
1153 &mut self,
1154 vis_resolution_error: VisResolutionError,
1155 ) -> ErrorGuaranteed {
1156 match vis_resolution_error {
1157 VisResolutionError::Relative2018(span, path) => {
1158 self.dcx().create_err(errs::Relative2018 {
1159 span,
1160 path_span: path.span,
1161 path_str: pprust::path_to_string(&path),
1164 })
1165 }
1166 VisResolutionError::AncestorOnly(span) => {
1167 self.dcx().create_err(errs::AncestorOnly(span))
1168 }
1169 VisResolutionError::FailedToResolve(span, segment, label, suggestion, message) => self
1170 .into_struct_error(
1171 span,
1172 ResolutionError::FailedToResolve {
1173 segment,
1174 label,
1175 suggestion,
1176 module: None,
1177 message,
1178 },
1179 ),
1180 VisResolutionError::ExpectedFound(span, path_str, res) => {
1181 self.dcx().create_err(errs::ExpectedModuleFound { span, res, path_str })
1182 }
1183 VisResolutionError::Indeterminate(span) => {
1184 self.dcx().create_err(errs::Indeterminate(span))
1185 }
1186 VisResolutionError::ModuleOnly(span) => self.dcx().create_err(errs::ModuleOnly(span)),
1187 }
1188 .emit()
1189 }
1190
1191 fn def_path_str(&self, mut def_id: DefId) -> String {
1192 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];
1194 while let Some(parent) = self.tcx.opt_parent(def_id) {
1195 def_id = parent;
1196 path.push(def_id);
1197 if def_id.is_top_level_module() {
1198 break;
1199 }
1200 }
1201 path.into_iter()
1203 .rev()
1204 .map(|def_id| {
1205 self.tcx
1206 .opt_item_name(def_id)
1207 .map(|name| {
1208 match (
1209 def_id.is_top_level_module(),
1210 def_id.is_local(),
1211 self.tcx.sess.edition(),
1212 ) {
1213 (true, true, Edition::Edition2015) => String::new(),
1214 (true, true, _) => kw::Crate.to_string(),
1215 (true, false, _) | (false, _, _) => name.to_string(),
1216 }
1217 })
1218 .unwrap_or_else(|| "_".to_string())
1219 })
1220 .collect::<Vec<String>>()
1221 .join("::")
1222 }
1223
1224 pub(crate) fn add_scope_set_candidates(
1225 &mut self,
1226 suggestions: &mut Vec<TypoSuggestion>,
1227 scope_set: ScopeSet<'ra>,
1228 ps: &ParentScope<'ra>,
1229 sp: Span,
1230 filter_fn: &impl Fn(Res) -> bool,
1231 ) {
1232 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
1233 self.cm().visit_scopes(scope_set, ps, ctxt, sp, None, |this, scope, use_prelude, _| {
1234 match scope {
1235 Scope::DeriveHelpers(expn_id) => {
1236 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1237 if filter_fn(res) {
1238 suggestions.extend(
1239 this.helper_attrs.get(&expn_id).into_iter().flatten().map(
1240 |&(ident, orig_ident_span, _)| {
1241 TypoSuggestion::new(ident.name, orig_ident_span, res)
1242 },
1243 ),
1244 );
1245 }
1246 }
1247 Scope::DeriveHelpersCompat => {
1248 }
1250 Scope::MacroRules(macro_rules_scope) => {
1251 if let MacroRulesScope::Def(macro_rules_def) = macro_rules_scope.get() {
1252 let res = macro_rules_def.decl.res();
1253 if filter_fn(res) {
1254 suggestions.push(TypoSuggestion::new(
1255 macro_rules_def.ident.name,
1256 macro_rules_def.orig_ident_span,
1257 res,
1258 ))
1259 }
1260 }
1261 }
1262 Scope::ModuleNonGlobs(module, _) => {
1263 this.add_module_candidates(module, suggestions, filter_fn, None);
1264 }
1265 Scope::ModuleGlobs(..) => {
1266 }
1268 Scope::MacroUsePrelude => {
1269 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1270 |(name, binding)| {
1271 let res = binding.res();
1272 filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1273 },
1274 ));
1275 }
1276 Scope::BuiltinAttrs => {
1277 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(sym::dummy));
1278 if filter_fn(res) {
1279 suggestions.extend(
1280 BUILTIN_ATTRIBUTES
1281 .iter()
1282 .filter(|attr| {
1285 !#[allow(non_exhaustive_omitted_patterns)] match attr.name {
sym::cfg_trace | sym::cfg_attr_trace => true,
_ => false,
}matches!(attr.name, sym::cfg_trace | sym::cfg_attr_trace)
1286 })
1287 .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1288 );
1289 }
1290 }
1291 Scope::ExternPreludeItems => {
1292 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, entry)| {
1294 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1295 filter_fn(res).then_some(TypoSuggestion::new(ident.name, entry.span(), res))
1296 }));
1297 }
1298 Scope::ExternPreludeFlags => {}
1299 Scope::ToolPrelude => {
1300 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1301 suggestions.extend(
1302 this.registered_tools
1303 .iter()
1304 .map(|ident| TypoSuggestion::new(ident.name, ident.span, res)),
1305 );
1306 }
1307 Scope::StdLibPrelude => {
1308 if let Some(prelude) = this.prelude {
1309 let mut tmp_suggestions = Vec::new();
1310 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1311 suggestions.extend(
1312 tmp_suggestions
1313 .into_iter()
1314 .filter(|s| use_prelude.into() || this.is_builtin_macro(s.res)),
1315 );
1316 }
1317 }
1318 Scope::BuiltinTypes => {
1319 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1320 let res = Res::PrimTy(*prim_ty);
1321 filter_fn(res)
1322 .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1323 }))
1324 }
1325 }
1326
1327 ControlFlow::<()>::Continue(())
1328 });
1329 }
1330
1331 fn early_lookup_typo_candidate(
1333 &mut self,
1334 scope_set: ScopeSet<'ra>,
1335 parent_scope: &ParentScope<'ra>,
1336 ident: Ident,
1337 filter_fn: &impl Fn(Res) -> bool,
1338 ) -> Option<TypoSuggestion> {
1339 let mut suggestions = Vec::new();
1340 self.add_scope_set_candidates(
1341 &mut suggestions,
1342 scope_set,
1343 parent_scope,
1344 ident.span,
1345 filter_fn,
1346 );
1347
1348 suggestions.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
1350
1351 match find_best_match_for_name(
1352 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1353 ident.name,
1354 None,
1355 ) {
1356 Some(found) if found != ident.name => {
1357 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1358 }
1359 _ => None,
1360 }
1361 }
1362
1363 fn lookup_import_candidates_from_module<FilterFn>(
1364 &self,
1365 lookup_ident: Ident,
1366 namespace: Namespace,
1367 parent_scope: &ParentScope<'ra>,
1368 start_module: Module<'ra>,
1369 crate_path: ThinVec<ast::PathSegment>,
1370 filter_fn: FilterFn,
1371 ) -> Vec<ImportSuggestion>
1372 where
1373 FilterFn: Fn(Res) -> bool,
1374 {
1375 let mut candidates = Vec::new();
1376 let mut seen_modules = FxHashSet::default();
1377 let start_did = start_module.def_id();
1378 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![(
1379 start_module,
1380 ThinVec::<ast::PathSegment>::new(),
1381 true,
1382 start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
1383 true,
1384 )];
1385 let mut worklist_via_import = ::alloc::vec::Vec::new()vec![];
1386
1387 while let Some((in_module, path_segments, accessible, doc_visible, is_stable)) =
1388 match worklist.pop() {
1389 None => worklist_via_import.pop(),
1390 Some(x) => Some(x),
1391 }
1392 {
1393 let in_module_is_extern = !in_module.def_id().is_local();
1394 in_module.for_each_child(self, |this, ident, orig_ident_span, ns, name_binding| {
1395 if name_binding.is_assoc_item()
1397 && !this.tcx.features().import_trait_associated_functions()
1398 {
1399 return;
1400 }
1401
1402 if ident.name == kw::Underscore {
1403 return;
1404 }
1405
1406 let child_accessible =
1407 accessible && this.is_accessible_from(name_binding.vis(), parent_scope.module);
1408
1409 if in_module_is_extern && !child_accessible {
1411 return;
1412 }
1413
1414 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1415
1416 if via_import && name_binding.is_possibly_imported_variant() {
1422 return;
1423 }
1424
1425 if let DeclKind::Import { source_decl, .. } = name_binding.kind
1427 && this.is_accessible_from(source_decl.vis(), parent_scope.module)
1428 && !this.is_accessible_from(name_binding.vis(), parent_scope.module)
1429 {
1430 return;
1431 }
1432
1433 let res = name_binding.res();
1434 let did = match res {
1435 Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1436 _ => res.opt_def_id(),
1437 };
1438 let child_doc_visible = doc_visible
1439 && did.is_none_or(|did| did.is_local() || !this.tcx.is_doc_hidden(did));
1440
1441 if ident.name == lookup_ident.name
1445 && ns == namespace
1446 && in_module != parent_scope.module
1447 && ident.ctxt.is_root()
1448 && filter_fn(res)
1449 {
1450 let mut segms = if lookup_ident.span.at_least_rust_2018() {
1452 crate_path.clone()
1455 } else {
1456 ThinVec::new()
1457 };
1458 segms.append(&mut path_segments.clone());
1459
1460 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
1461 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1462
1463 if child_accessible
1464 && let Some(idx) = candidates
1466 .iter()
1467 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1468 {
1469 candidates.remove(idx);
1470 }
1471
1472 let is_stable = if is_stable
1473 && let Some(did) = did
1474 && this.is_stable(did, path.span)
1475 {
1476 true
1477 } else {
1478 false
1479 };
1480
1481 if is_stable
1486 && let Some(idx) = candidates
1487 .iter()
1488 .position(|v: &ImportSuggestion| v.did == did && !v.is_stable)
1489 {
1490 candidates.remove(idx);
1491 }
1492
1493 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1494 let note = if let Some(did) = did {
1497 let requires_note = !did.is_local()
1498 && {
{
'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!(
1499 this.tcx,
1500 did,
1501 RustcDiagnosticItem(
1502 sym::TryInto | sym::TryFrom | sym::FromIterator
1503 )
1504 );
1505 requires_note.then(|| {
1506 ::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!(
1507 "'{}' is included in the prelude starting in Edition 2021",
1508 path_names_to_string(&path)
1509 )
1510 })
1511 } else {
1512 None
1513 };
1514
1515 candidates.push(ImportSuggestion {
1516 did,
1517 descr: res.descr(),
1518 path,
1519 accessible: child_accessible,
1520 doc_visible: child_doc_visible,
1521 note,
1522 via_import,
1523 is_stable,
1524 });
1525 }
1526 }
1527
1528 if let Some(def_id) = name_binding.res().module_like_def_id() {
1530 let mut path_segments = path_segments.clone();
1532 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
1533
1534 let alias_import = if let DeclKind::Import { import, .. } = name_binding.kind
1535 && let ImportKind::ExternCrate { source: Some(_), .. } = import.kind
1536 && import.parent_scope.expansion == parent_scope.expansion
1537 {
1538 true
1539 } else {
1540 false
1541 };
1542
1543 let is_extern_crate_that_also_appears_in_prelude =
1544 name_binding.is_extern_crate() && lookup_ident.span.at_least_rust_2018();
1545
1546 if !is_extern_crate_that_also_appears_in_prelude || alias_import {
1547 if seen_modules.insert(def_id) {
1549 if via_import { &mut worklist_via_import } else { &mut worklist }.push(
1550 (
1551 this.expect_module(def_id),
1552 path_segments,
1553 child_accessible,
1554 child_doc_visible,
1555 is_stable && this.is_stable(def_id, name_binding.span),
1556 ),
1557 );
1558 }
1559 }
1560 }
1561 })
1562 }
1563
1564 candidates
1565 }
1566
1567 fn is_stable(&self, did: DefId, span: Span) -> bool {
1568 if did.is_local() {
1569 return true;
1570 }
1571
1572 match self.tcx.lookup_stability(did) {
1573 Some(Stability {
1574 level: StabilityLevel::Unstable { implied_by, .. }, feature, ..
1575 }) => {
1576 if span.allows_unstable(feature) {
1577 true
1578 } else if self.tcx.features().enabled(feature) {
1579 true
1580 } else if let Some(implied_by) = implied_by
1581 && self.tcx.features().enabled(implied_by)
1582 {
1583 true
1584 } else {
1585 false
1586 }
1587 }
1588 Some(_) => true,
1589 None => false,
1590 }
1591 }
1592
1593 pub(crate) fn lookup_import_candidates<FilterFn>(
1601 &mut self,
1602 lookup_ident: Ident,
1603 namespace: Namespace,
1604 parent_scope: &ParentScope<'ra>,
1605 filter_fn: FilterFn,
1606 ) -> Vec<ImportSuggestion>
1607 where
1608 FilterFn: Fn(Res) -> bool,
1609 {
1610 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))];
1611 let mut suggestions = self.lookup_import_candidates_from_module(
1612 lookup_ident,
1613 namespace,
1614 parent_scope,
1615 self.graph_root.to_module(),
1616 crate_path,
1617 &filter_fn,
1618 );
1619
1620 if lookup_ident.span.at_least_rust_2018() {
1621 for (ident, entry) in &self.extern_prelude {
1622 if entry.span().from_expansion() {
1623 continue;
1629 }
1630 let Some(crate_id) =
1631 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
1632 else {
1633 continue;
1634 };
1635
1636 let crate_def_id = crate_id.as_def_id();
1637 let crate_root = self.expect_module(crate_def_id);
1638
1639 let needs_disambiguation =
1643 self.resolutions(parent_scope.module).borrow().iter().any(
1644 |(key, name_resolution)| {
1645 if key.ns == TypeNS
1646 && key.ident == *ident
1647 && let Some(decl) = name_resolution.borrow().best_decl()
1648 {
1649 match decl.res() {
1650 Res::Def(_, def_id) => def_id != crate_def_id,
1653 Res::PrimTy(_) => true,
1654 _ => false,
1655 }
1656 } else {
1657 false
1658 }
1659 },
1660 );
1661 let mut crate_path = ThinVec::new();
1662 if needs_disambiguation {
1663 crate_path.push(ast::PathSegment::path_root(rustc_span::DUMMY_SP));
1664 }
1665 crate_path.push(ast::PathSegment::from_ident(ident.orig(entry.span())));
1666
1667 suggestions.extend(self.lookup_import_candidates_from_module(
1668 lookup_ident,
1669 namespace,
1670 parent_scope,
1671 crate_root,
1672 crate_path,
1673 &filter_fn,
1674 ));
1675 }
1676 }
1677
1678 suggestions.retain(|suggestion| suggestion.is_stable || self.tcx.sess.is_nightly_build());
1679 suggestions
1680 }
1681
1682 pub(crate) fn unresolved_macro_suggestions(
1683 &mut self,
1684 err: &mut Diag<'_>,
1685 macro_kind: MacroKind,
1686 parent_scope: &ParentScope<'ra>,
1687 ident: Ident,
1688 krate: &Crate,
1689 sugg_span: Option<Span>,
1690 ) {
1691 self.register_macros_for_all_crates();
1694
1695 let is_expected =
1696 &|res: Res| res.macro_kinds().is_some_and(|k| k.contains(macro_kind.into()));
1697 let suggestion = self.early_lookup_typo_candidate(
1698 ScopeSet::Macro(macro_kind),
1699 parent_scope,
1700 ident,
1701 is_expected,
1702 );
1703 if !self.add_typo_suggestion(err, suggestion, ident.span) {
1704 self.detect_derive_attribute(err, ident, parent_scope, sugg_span);
1705 }
1706
1707 let import_suggestions =
1708 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1709 let (span, found_use) = match parent_scope.module.nearest_parent_mod_node_id() {
1710 DUMMY_NODE_ID => (None, FoundUse::No),
1711 node_id => UsePlacementFinder::check(krate, node_id),
1712 };
1713 show_candidates(
1714 self.tcx,
1715 err,
1716 span,
1717 &import_suggestions,
1718 Instead::No,
1719 found_use,
1720 DiagMode::Normal,
1721 ::alloc::vec::Vec::new()vec![],
1722 "",
1723 );
1724
1725 if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1726 let label_span = ident.span.shrink_to_hi();
1727 let mut spans = MultiSpan::from_span(label_span);
1728 spans.push_span_label(label_span, "put a macro name here");
1729 err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1730 return;
1731 }
1732
1733 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1734 err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1735 return;
1736 }
1737
1738 let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1739 if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1740 });
1741
1742 if let Some((def_id, unused_ident)) = unused_macro {
1743 let scope = self.local_macro_def_scopes[&def_id];
1744 let parent_nearest = parent_scope.module.nearest_parent_mod();
1745 let unused_macro_kinds = self.local_macro_map[def_id].macro_kinds();
1746 if !unused_macro_kinds.contains(macro_kind.into()) {
1747 match macro_kind {
1748 MacroKind::Bang => {
1749 err.subdiagnostic(MacroRulesNot::Func { span: unused_ident.span, ident });
1750 }
1751 MacroKind::Attr => {
1752 err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1753 }
1754 MacroKind::Derive => {
1755 err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1756 }
1757 }
1758 return;
1759 }
1760 if Some(parent_nearest) == scope.opt_def_id() {
1761 err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1762 err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1763 return;
1764 }
1765 }
1766
1767 if ident.name == kw::Default
1768 && let ModuleKind::Def(DefKind::Enum, def_id, _, _) = parent_scope.module.kind
1769 {
1770 let span = self.def_span(def_id);
1771 let source_map = self.tcx.sess.source_map();
1772 let head_span = source_map.guess_head_span(span);
1773 err.subdiagnostic(ConsiderAddingADerive {
1774 span: head_span.shrink_to_lo(),
1775 suggestion: "#[derive(Default)]\n".to_string(),
1776 });
1777 }
1778 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1779 let Ok(binding) = self.cm().resolve_ident_in_scope_set(
1780 ident,
1781 ScopeSet::All(ns),
1782 parent_scope,
1783 None,
1784 None,
1785 None,
1786 ) else {
1787 continue;
1788 };
1789
1790 let desc = match binding.res() {
1791 Res::Def(DefKind::Macro(MacroKinds::BANG), _) => {
1792 "a function-like macro".to_string()
1793 }
1794 Res::Def(DefKind::Macro(MacroKinds::ATTR), _) | Res::NonMacroAttr(..) => {
1795 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("an attribute: `#[{0}]`", ident))
})format!("an attribute: `#[{ident}]`")
1796 }
1797 Res::Def(DefKind::Macro(MacroKinds::DERIVE), _) => {
1798 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a derive macro: `#[derive({0})]`",
ident))
})format!("a derive macro: `#[derive({ident})]`")
1799 }
1800 Res::Def(DefKind::Macro(kinds), _) => {
1801 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", kinds.article(),
kinds.descr()))
})format!("{} {}", kinds.article(), kinds.descr())
1802 }
1803 Res::ToolMod | Res::OpenMod(..) => {
1804 continue;
1806 }
1807 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1808 "only a trait, without a derive macro".to_string()
1809 }
1810 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!(
1811 "{} {}, not {} {}",
1812 res.article(),
1813 res.descr(),
1814 macro_kind.article(),
1815 macro_kind.descr_expected(),
1816 ),
1817 };
1818 if let crate::DeclKind::Import { import, .. } = binding.kind
1819 && !import.span.is_dummy()
1820 {
1821 let note = errors::IdentImporterHereButItIsDesc {
1822 span: import.span,
1823 imported_ident: ident,
1824 imported_ident_desc: &desc,
1825 };
1826 err.subdiagnostic(note);
1827 self.record_use(ident, binding, Used::Other);
1830 return;
1831 }
1832 let note = errors::IdentInScopeButItIsDesc {
1833 imported_ident: ident,
1834 imported_ident_desc: &desc,
1835 };
1836 err.subdiagnostic(note);
1837 return;
1838 }
1839
1840 if self.macro_names.contains(&IdentKey::new(ident)) {
1841 err.subdiagnostic(AddedMacroUse);
1842 return;
1843 }
1844 }
1845
1846 fn detect_derive_attribute(
1849 &self,
1850 err: &mut Diag<'_>,
1851 ident: Ident,
1852 parent_scope: &ParentScope<'ra>,
1853 sugg_span: Option<Span>,
1854 ) {
1855 let mut derives = ::alloc::vec::Vec::new()vec![];
1860 let mut all_attrs: UnordMap<Symbol, Vec<_>> = UnordMap::default();
1861 #[allow(rustc::potential_query_instability)]
1863 for (def_id, ext) in self
1864 .local_macro_map
1865 .iter()
1866 .map(|(local_id, ext)| (local_id.to_def_id(), ext))
1867 .chain(self.extern_macro_map.borrow().iter().map(|(id, d)| (*id, d)))
1868 {
1869 for helper_attr in &ext.helper_attrs {
1870 let item_name = self.tcx.item_name(def_id);
1871 all_attrs.entry(*helper_attr).or_default().push(item_name);
1872 if helper_attr == &ident.name {
1873 derives.push(item_name);
1874 }
1875 }
1876 }
1877 let kind = MacroKind::Derive.descr();
1878 if !derives.is_empty() {
1879 let mut derives: Vec<String> = derives.into_iter().map(|d| d.to_string()).collect();
1881 derives.sort();
1882 derives.dedup();
1883 let msg = match &derives[..] {
1884 [derive] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}`", derive))
})format!(" `{derive}`"),
1885 [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!(
1886 "s {} and `{last}`",
1887 start.iter().map(|d| format!("`{d}`")).collect::<Vec<_>>().join(", ")
1888 ),
1889 [] => {
::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!?"),
1890 };
1891 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!(
1892 "`{}` is an attribute that can be used by the {kind}{msg}, you might be \
1893 missing a `derive` attribute",
1894 ident.name,
1895 );
1896 let sugg_span =
1897 if let ModuleKind::Def(DefKind::Enum, id, _, _) = parent_scope.module.kind {
1898 let span = self.def_span(id);
1899 if span.from_expansion() {
1900 None
1901 } else {
1902 Some(span.shrink_to_lo())
1904 }
1905 } else {
1906 sugg_span
1908 };
1909 match sugg_span {
1910 Some(span) => {
1911 err.span_suggestion_verbose(
1912 span,
1913 msg,
1914 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n",
derives.join(", ")))
})format!("#[derive({})]\n", derives.join(", ")),
1915 Applicability::MaybeIncorrect,
1916 );
1917 }
1918 None => {
1919 err.note(msg);
1920 }
1921 }
1922 } else {
1923 let all_attr_names = all_attrs.keys().map(|s| *s).into_sorted_stable_ord();
1925 if let Some(best_match) = find_best_match_for_name(&all_attr_names, ident.name, None)
1926 && let Some(macros) = all_attrs.get(&best_match)
1927 {
1928 let mut macros: Vec<String> = macros.into_iter().map(|d| d.to_string()).collect();
1929 macros.sort();
1930 macros.dedup();
1931 let msg = match ¯os[..] {
1932 [] => return,
1933 [name] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}` accepts", name))
})format!(" `{name}` accepts"),
1934 [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!(
1935 "s {} and `{end}` accept",
1936 start.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", "),
1937 ),
1938 };
1939 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");
1940 err.span_suggestion_verbose(
1941 ident.span,
1942 msg,
1943 best_match,
1944 Applicability::MaybeIncorrect,
1945 );
1946 }
1947 }
1948 }
1949
1950 pub(crate) fn add_typo_suggestion(
1951 &self,
1952 err: &mut Diag<'_>,
1953 suggestion: Option<TypoSuggestion>,
1954 span: Span,
1955 ) -> bool {
1956 let suggestion = match suggestion {
1957 None => return false,
1958 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1960 Some(suggestion) => suggestion,
1961 };
1962
1963 let mut did_label_def_span = false;
1964
1965 if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1966 if span.overlaps(def_span) {
1967 return false;
1986 }
1987 let span = self.tcx.sess.source_map().guess_head_span(def_span);
1988 let candidate_descr = suggestion.res.descr();
1989 let candidate = suggestion.candidate;
1990 let label = match suggestion.target {
1991 SuggestionTarget::SimilarlyNamed => {
1992 errors::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
1993 }
1994 SuggestionTarget::SingleItem => {
1995 errors::DefinedHere::SingleItem { span, candidate_descr, candidate }
1996 }
1997 };
1998 did_label_def_span = true;
1999 err.subdiagnostic(label);
2000 }
2001
2002 let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
2003 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2004 && let Some(span) = suggestion.span
2005 && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
2006 && snippet == candidate
2007 {
2008 let candidate = suggestion.candidate;
2009 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!(
2012 "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
2013 );
2014 if !did_label_def_span {
2015 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", candidate))
})format!("`{candidate}` defined here"));
2016 }
2017 (span, msg, snippet)
2018 } else {
2019 let msg = match suggestion.target {
2020 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!(
2021 "{} {} with a similar name exists",
2022 suggestion.res.article(),
2023 suggestion.res.descr()
2024 ),
2025 SuggestionTarget::SingleItem => {
2026 ::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())
2027 }
2028 };
2029 (span, msg, suggestion.candidate.to_ident_string())
2030 };
2031 err.span_suggestion_verbose(span, msg, sugg, Applicability::MaybeIncorrect);
2032 true
2033 }
2034
2035 fn decl_description(&self, b: Decl<'_>, ident: Ident, scope: Scope<'_>) -> String {
2036 let res = b.res();
2037 if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
2038 let (built_in, from) = match scope {
2039 Scope::StdLibPrelude | Scope::MacroUsePrelude => ("", " from prelude"),
2040 Scope::ExternPreludeFlags
2041 if self.tcx.sess.opts.externs.get(ident.as_str()).is_some()
2042 || #[allow(non_exhaustive_omitted_patterns)] match res {
Res::OpenMod(..) => true,
_ => false,
}matches!(res, Res::OpenMod(..)) =>
2043 {
2044 ("", " passed with `--extern`")
2045 }
2046 _ => {
2047 if #[allow(non_exhaustive_omitted_patterns)] match res {
Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => true,
_ => false,
}matches!(res, Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod) {
2048 ("", "")
2050 } else {
2051 (" built-in", "")
2052 }
2053 }
2054 };
2055
2056 let a = if built_in.is_empty() { res.article() } else { "a" };
2057 ::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())
2058 } else {
2059 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
2060 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} {1} here", res.descr(),
introduced))
})format!("the {thing} {introduced} here", thing = res.descr())
2061 }
2062 }
2063
2064 fn ambiguity_diagnostic(&self, ambiguity_error: &AmbiguityError<'ra>) -> errors::Ambiguity {
2065 let AmbiguityError { kind, ambig_vis, ident, b1, b2, scope1, scope2, .. } =
2066 *ambiguity_error;
2067 let extern_prelude_ambiguity = || {
2068 #[allow(non_exhaustive_omitted_patterns)] match scope2 {
Scope::ExternPreludeFlags => true,
_ => false,
}matches!(scope2, Scope::ExternPreludeFlags)
2070 && self
2071 .extern_prelude
2072 .get(&IdentKey::new(ident))
2073 .is_some_and(|entry| entry.item_decl.map(|(b, ..)| b) == Some(b1))
2074 };
2075 let (b1, b2, scope1, scope2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
2076 (b2, b1, scope2, scope1, true)
2078 } else {
2079 (b1, b2, scope1, scope2, false)
2080 };
2081
2082 let could_refer_to = |b: Decl<'_>, scope: Scope<'ra>, also: &str| {
2083 let what = self.decl_description(b, ident, scope);
2084 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}");
2085
2086 let thing = b.res().descr();
2087 let mut help_msgs = Vec::new();
2088 if b.is_glob_import()
2089 && (kind == AmbiguityKind::GlobVsGlob
2090 || kind == AmbiguityKind::GlobVsExpanded
2091 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
2092 {
2093 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider adding an explicit import of `{0}` to disambiguate",
ident))
})format!(
2094 "consider adding an explicit import of `{ident}` to disambiguate"
2095 ))
2096 }
2097 if b.is_extern_crate() && ident.span.at_least_rust_2018() && !extern_prelude_ambiguity()
2098 {
2099 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"))
2100 }
2101
2102 if kind != AmbiguityKind::GlobVsGlob {
2103 if let Scope::ModuleNonGlobs(module, _) | Scope::ModuleGlobs(module, _) = scope {
2104 if module == self.graph_root.to_module() {
2105 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `crate::{0}` to refer to this {1} unambiguously",
ident, thing))
})format!(
2106 "use `crate::{ident}` to refer to this {thing} unambiguously"
2107 ));
2108 } else if module.is_normal() {
2109 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `self::{0}` to refer to this {1} unambiguously",
ident, thing))
})format!(
2110 "use `self::{ident}` to refer to this {thing} unambiguously"
2111 ));
2112 }
2113 }
2114 }
2115
2116 (
2117 Spanned { node: note_msg, span: b.span },
2118 help_msgs
2119 .iter()
2120 .enumerate()
2121 .map(|(i, help_msg)| {
2122 let or = if i == 0 { "" } else { "or " };
2123 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", or, help_msg))
})format!("{or}{help_msg}")
2124 })
2125 .collect::<Vec<_>>(),
2126 )
2127 };
2128 let (b1_note, b1_help_msgs) = could_refer_to(b1, scope1, "");
2129 let (b2_note, b2_help_msgs) = could_refer_to(b2, scope2, " also");
2130 let help = if kind == AmbiguityKind::GlobVsGlob
2131 && b1
2132 .parent_module
2133 .and_then(|m| m.opt_def_id())
2134 .map(|d| !d.is_local())
2135 .unwrap_or_default()
2136 {
2137 Some(&[
2138 "consider updating this dependency to resolve this error",
2139 "if updating the dependency does not resolve the problem report the problem to the author of the relevant crate",
2140 ] as &[_])
2141 } else {
2142 None
2143 };
2144
2145 let ambig_vis = ambig_vis.map(|(vis1, vis2)| {
2146 ::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!(
2147 "{} or {}",
2148 vis1.to_string(CRATE_DEF_ID, self.tcx),
2149 vis2.to_string(CRATE_DEF_ID, self.tcx)
2150 )
2151 });
2152
2153 errors::Ambiguity {
2154 ident,
2155 help,
2156 ambig_vis,
2157 kind: kind.descr(),
2158 b1_note,
2159 b1_help_msgs,
2160 b2_note,
2161 b2_help_msgs,
2162 is_error: false,
2163 }
2164 }
2165
2166 fn ctor_fields_span(&self, decl: Decl<'_>) -> Option<Span> {
2169 let DeclKind::Def(Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id)) =
2170 decl.kind
2171 else {
2172 return None;
2173 };
2174
2175 let def_id = self.tcx.parent(ctor_def_id);
2176 self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) }
2178
2179 fn module_path_names(&self, module: Module<'ra>) -> Option<Vec<Symbol>> {
2183 let mut path = Vec::new();
2184 let mut def_id = module.opt_def_id()?;
2185 while let Some(parent) = self.tcx.opt_parent(def_id) {
2186 if let Some(name) = self.tcx.opt_item_name(def_id) {
2187 path.push(name);
2188 }
2189 if parent.is_top_level_module() {
2190 break;
2191 }
2192 def_id = parent;
2193 }
2194 path.reverse();
2195 path.insert(0, kw::Crate);
2196 Some(path)
2197 }
2198
2199 fn shorten_candidate_path(
2203 &self,
2204 suggestion: &mut ImportSuggestion,
2205 current_module: Module<'ra>,
2206 ) {
2207 const MAX_SUPER_PATH_ITEMS_IN_SUGGESTION: usize = 1;
2208
2209 if suggestion.did.is_none_or(|did| !did.is_local()) {
2211 return;
2212 }
2213
2214 let Some(current_mod_path) = self.module_path_names(current_module) else {
2216 return;
2217 };
2218
2219 let candidate_names = {
2223 let filtered_segments: Vec<_> = suggestion
2224 .path
2225 .segments
2226 .iter()
2227 .filter(|segment| segment.ident.name != kw::PathRoot)
2228 .collect();
2229
2230 let mut candidate_names: Vec<Symbol> =
2231 filtered_segments.iter().map(|segment| segment.ident.name).collect();
2232 if candidate_names.first() != Some(&kw::Crate) {
2233 candidate_names.insert(0, kw::Crate);
2234 }
2235 if candidate_names.len() < 2 {
2236 return;
2237 }
2238 candidate_names
2239 };
2240
2241 let candidate_mod_names = &candidate_names[..candidate_names.len() - 1];
2243
2244 let common_prefix_length = current_mod_path
2246 .iter()
2247 .zip(candidate_mod_names.iter())
2248 .take_while(|(current, candidate)| current == candidate)
2249 .count();
2250
2251 if common_prefix_length == 0 {
2253 return;
2254 }
2255
2256 let super_count = current_mod_path.len() - common_prefix_length;
2257
2258 let at_crate_root = current_mod_path.len() == 1;
2261
2262 let mut new_segments = if super_count == 0 && at_crate_root {
2263 ThinVec::new()
2264 } else {
2265 let prefix_keyword = match super_count {
2266 0 => kw::SelfLower,
2267 1..=MAX_SUPER_PATH_ITEMS_IN_SUGGESTION => kw::Super,
2268 _ => return, };
2270 {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(ast::PathSegment::from_ident(Ident::with_dummy_span(prefix_keyword)));
vec
}thin_vec![ast::PathSegment::from_ident(Ident::with_dummy_span(prefix_keyword),)]
2271 };
2272 for &name in &candidate_names[common_prefix_length..] {
2273 new_segments.push(ast::PathSegment::from_ident(Ident::with_dummy_span(name)));
2274 }
2275
2276 if new_segments.len() >= suggestion.path.segments.len() {
2278 return;
2279 }
2280
2281 suggestion.path = Path { span: suggestion.path.span, segments: new_segments, tokens: None };
2282 }
2283
2284 fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
2285 let PrivacyError {
2286 ident,
2287 decl,
2288 outermost_res,
2289 parent_scope,
2290 single_nested,
2291 dedup_span,
2292 ref source,
2293 } = *privacy_error;
2294
2295 let res = decl.res();
2296 let ctor_fields_span = self.ctor_fields_span(decl);
2297 let plain_descr = res.descr().to_string();
2298 let nonimport_descr =
2299 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
2300 let import_descr = nonimport_descr.clone() + " import";
2301 let get_descr = |b: Decl<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
2302
2303 let ident_descr = get_descr(decl);
2305 let mut err =
2306 self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
2307
2308 self.mention_default_field_values(source, ident, &mut err);
2309
2310 if let Some((this_res, outer_ident)) = outermost_res {
2311 let mut import_suggestions = self.lookup_import_candidates(
2312 outer_ident,
2313 this_res.ns().unwrap_or(Namespace::TypeNS),
2314 &parent_scope,
2315 &|res: Res| res == this_res,
2316 );
2317 for suggestion in &mut import_suggestions {
2319 self.shorten_candidate_path(suggestion, parent_scope.module);
2320 }
2321 let point_to_def = !show_candidates(
2322 self.tcx,
2323 &mut err,
2324 Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
2325 &import_suggestions,
2326 Instead::Yes,
2327 FoundUse::Yes,
2328 DiagMode::Import { append: single_nested, unresolved_import: false },
2329 ::alloc::vec::Vec::new()vec![],
2330 "",
2331 );
2332 if point_to_def && ident.span != outer_ident.span {
2334 let label = errors::OuterIdentIsNotPubliclyReexported {
2335 span: outer_ident.span,
2336 outer_ident_descr: this_res.descr(),
2337 outer_ident,
2338 };
2339 err.subdiagnostic(label);
2340 }
2341 }
2342
2343 let mut non_exhaustive = None;
2344 if let Some(def_id) = res.opt_def_id()
2348 && !def_id.is_local()
2349 && 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)
2350 {
2351 non_exhaustive = Some(attr_span);
2352 } else if let Some(span) = ctor_fields_span {
2353 let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
2354 err.subdiagnostic(label);
2355 if let Res::Def(_, d) = res
2356 && let Some(fields) = self.field_visibility_spans.get(&d)
2357 {
2358 let spans = fields.iter().map(|span| *span).collect();
2359 let sugg =
2360 errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
2361 err.subdiagnostic(sugg);
2362 }
2363 }
2364
2365 let mut sugg_paths: Vec<(Vec<Ident>, bool)> = ::alloc::vec::Vec::new()vec![];
2366 if let Some(mut def_id) = res.opt_def_id() {
2367 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];
2369 while let Some(parent) = self.tcx.opt_parent(def_id) {
2370 def_id = parent;
2371 if !def_id.is_top_level_module() {
2372 path.push(def_id);
2373 } else {
2374 break;
2375 }
2376 }
2377 let path_names: Option<Vec<Ident>> = path
2379 .iter()
2380 .rev()
2381 .map(|def_id| {
2382 self.tcx.opt_item_name(*def_id).map(|name| {
2383 Ident::with_dummy_span(if def_id.is_top_level_module() {
2384 kw::Crate
2385 } else {
2386 name
2387 })
2388 })
2389 })
2390 .collect();
2391 if let Some(&def_id) = path.get(0)
2392 && let Some(path) = path_names
2393 {
2394 if let Some(def_id) = def_id.as_local() {
2395 if self.effective_visibilities.is_directly_public(def_id) {
2396 sugg_paths.push((path, false));
2397 }
2398 } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
2399 {
2400 sugg_paths.push((path, false));
2401 }
2402 }
2403 }
2404
2405 let first_binding = decl;
2407 let mut next_binding = Some(decl);
2408 let mut next_ident = ident;
2409 while let Some(binding) = next_binding {
2410 let name = next_ident;
2411 next_binding = match binding.kind {
2412 _ if res == Res::Err => None,
2413 DeclKind::Import { source_decl, import, .. } => match import.kind {
2414 _ if source_decl.span.is_dummy() => None,
2415 ImportKind::Single { source, .. } => {
2416 next_ident = source;
2417 Some(source_decl)
2418 }
2419 ImportKind::Glob { .. }
2420 | ImportKind::MacroUse { .. }
2421 | ImportKind::MacroExport => Some(source_decl),
2422 ImportKind::ExternCrate { .. } => None,
2423 },
2424 _ => None,
2425 };
2426
2427 match binding.kind {
2428 DeclKind::Import { source_decl, import, .. } => {
2429 let path = import
2432 .module_path
2433 .iter()
2434 .filter(|seg| seg.ident.name != kw::PathRoot)
2435 .map(|seg| seg.ident.clone())
2436 .chain(std::iter::once(ident))
2437 .collect::<Vec<_>>();
2438 let through_reexport = !#[allow(non_exhaustive_omitted_patterns)] match source_decl.kind {
DeclKind::Def(_) => true,
_ => false,
}matches!(source_decl.kind, DeclKind::Def(_));
2439 sugg_paths.push((path, through_reexport));
2440 }
2441 DeclKind::Def(_) => {}
2442 }
2443 let first = binding == first_binding;
2444 let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
2445 let mut note_span = MultiSpan::from_span(def_span);
2446 if !first && binding.vis().is_public() {
2447 let desc = match binding.kind {
2448 DeclKind::Import { .. } => "re-export",
2449 _ => "directly",
2450 };
2451 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}"));
2452 }
2453 if next_binding.is_none()
2456 && let Some(span) = non_exhaustive
2457 {
2458 note_span.push_span_label(
2459 span,
2460 "cannot be constructed because it is `#[non_exhaustive]`",
2461 );
2462 }
2463 let note = errors::NoteAndRefersToTheItemDefinedHere {
2464 span: note_span,
2465 binding_descr: get_descr(binding),
2466 binding_name: name,
2467 first,
2468 dots: next_binding.is_some(),
2469 };
2470 err.subdiagnostic(note);
2471 }
2472 let can_replace_use =
2480 !single_nested && !outermost_res.is_some_and(|(_, outer)| outer.span != ident.span);
2481 if can_replace_use {
2482 sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0].name == sym::core, *reexport));
2485 for (sugg, reexport) in sugg_paths {
2486 if sugg.len() <= 1 {
2487 continue;
2490 }
2491 let path = join_path_idents(sugg);
2492 let sugg = if reexport {
2493 errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
2494 } else {
2495 errors::ImportIdent::Directly { span: dedup_span, ident, path }
2496 };
2497 err.subdiagnostic(sugg);
2498 break;
2499 }
2500 }
2501
2502 err.emit();
2503 }
2504
2505 fn mention_default_field_values(
2525 &self,
2526 source: &Option<ast::Expr>,
2527 ident: Ident,
2528 err: &mut Diag<'_>,
2529 ) {
2530 let Some(expr) = source else { return };
2531 let ast::ExprKind::Struct(struct_expr) = &expr.kind else { return };
2532 let Some(segment) = struct_expr.path.segments.last() else { return };
2535 let Some(partial_res) = self.partial_res_map.get(&segment.id) else { return };
2536 let Some(Res::Def(_, def_id)) = partial_res.full_res() else {
2537 return;
2538 };
2539 let Some(default_fields) = self.field_defaults(def_id) else { return };
2540 if struct_expr.fields.is_empty() {
2541 return;
2542 }
2543 let last_span = struct_expr.fields.iter().last().unwrap().span;
2544 let mut iter = struct_expr.fields.iter().peekable();
2545 let mut prev: Option<Span> = None;
2546 while let Some(field) = iter.next() {
2547 if field.expr.span.overlaps(ident.span) {
2548 err.span_label(field.ident.span, "while setting this field");
2549 if default_fields.contains(&field.ident.name) {
2550 let sugg = if last_span == field.span {
2551 ::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())]
2552 } else {
2553 ::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![
2554 (
2555 match (prev, iter.peek()) {
2557 (_, Some(next)) => field.span.with_hi(next.span.lo()),
2558 (Some(prev), _) => field.span.with_lo(prev.hi()),
2559 (None, None) => field.span,
2560 },
2561 String::new(),
2562 ),
2563 (last_span.shrink_to_hi(), ", ..".to_string()),
2564 ]
2565 };
2566 err.multipart_suggestion(
2567 ::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!(
2568 "the type `{ident}` of field `{}` is private, but you can construct \
2569 the default value defined for it in `{}` using `..` in the struct \
2570 initializer expression",
2571 field.ident,
2572 self.tcx.item_name(def_id),
2573 ),
2574 sugg,
2575 Applicability::MachineApplicable,
2576 );
2577 break;
2578 }
2579 }
2580 prev = Some(field.span);
2581 }
2582 }
2583
2584 pub(crate) fn find_similarly_named_module_or_crate(
2585 &self,
2586 ident: Symbol,
2587 current_module: Module<'ra>,
2588 ) -> Option<Symbol> {
2589 let mut candidates = self
2590 .extern_prelude
2591 .keys()
2592 .map(|ident| ident.name)
2593 .chain(
2594 self.local_module_map
2595 .iter()
2596 .filter(|(_, module)| {
2597 let module = module.to_module();
2598 current_module.is_ancestor_of(module) && current_module != module
2599 })
2600 .flat_map(|(_, module)| module.kind.name()),
2601 )
2602 .chain(
2603 self.extern_module_map
2604 .borrow()
2605 .iter()
2606 .filter(|(_, module)| {
2607 let module = module.to_module();
2608 current_module.is_ancestor_of(module) && current_module != module
2609 })
2610 .flat_map(|(_, module)| module.kind.name()),
2611 )
2612 .filter(|c| !c.to_string().is_empty())
2613 .collect::<Vec<_>>();
2614 candidates.sort();
2615 candidates.dedup();
2616 find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
2617 }
2618
2619 pub(crate) fn report_path_resolution_error(
2620 &mut self,
2621 path: &[Segment],
2622 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
2624 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
2625 ignore_decl: Option<Decl<'ra>>,
2626 ignore_import: Option<Import<'ra>>,
2627 module: Option<ModuleOrUniformRoot<'ra>>,
2628 failed_segment_idx: usize,
2629 ident: Ident,
2630 diag_metadata: Option<&DiagMetadata<'_>>,
2631 ) -> (String, String, Option<Suggestion>) {
2632 let is_last = failed_segment_idx == path.len() - 1;
2633 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2634 let module_res = match module {
2635 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2636 _ => None,
2637 };
2638 let scope = match &path[..failed_segment_idx] {
2639 [.., prev] => {
2640 if prev.ident.name == kw::PathRoot {
2641 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the crate root"))
})format!("the crate root")
2642 } else {
2643 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", prev.ident))
})format!("`{}`", prev.ident)
2644 }
2645 }
2646 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this scope"))
})format!("this scope"),
2647 };
2648 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find `{0}` in {1}", ident,
scope))
})format!("cannot find `{ident}` in {scope}");
2649
2650 if module_res == self.graph_root.res() {
2651 let is_mod = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _));
2652 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2653 candidates
2654 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2655 if let Some(candidate) = candidates.get(0) {
2656 let path = {
2657 let len = candidate.path.segments.len();
2659 let start_index = (0..=failed_segment_idx.min(len - 1))
2660 .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2661 .unwrap_or_default();
2662 let segments =
2663 (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2664 Path { segments, span: Span::default(), tokens: None }
2665 };
2666 (
2667 message,
2668 String::from("unresolved import"),
2669 Some((
2670 ::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))],
2671 String::from("a similar path exists"),
2672 Applicability::MaybeIncorrect,
2673 )),
2674 )
2675 } else if ident.name == sym::core {
2676 (
2677 message,
2678 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might be missing crate `{0}`",
ident))
})format!("you might be missing crate `{ident}`"),
2679 Some((
2680 ::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())],
2681 "try using `std` instead of `core`".to_string(),
2682 Applicability::MaybeIncorrect,
2683 )),
2684 )
2685 } else if ident.name == kw::Underscore {
2686 (
2687 "invalid crate or module name `_`".to_string(),
2688 "`_` is not a valid crate or module name".to_string(),
2689 None,
2690 )
2691 } else if self.tcx.sess.is_rust_2015() {
2692 (
2693 ::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}"),
2694 ::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}`"),
2695 Some((
2696 ::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![(
2697 self.current_crate_outer_attr_insert_span,
2698 format!("extern crate {ident};\n"),
2699 )],
2700 if was_invoked_from_cargo() {
2701 ::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!(
2702 "if you wanted to use a crate named `{ident}`, use `cargo add \
2703 {ident}` to add it to your `Cargo.toml` and import it in your \
2704 code",
2705 )
2706 } else {
2707 ::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!(
2708 "you might be missing a crate named `{ident}`, add it to your \
2709 project and import it in your code",
2710 )
2711 },
2712 Applicability::MaybeIncorrect,
2713 )),
2714 )
2715 } else {
2716 (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)
2717 }
2718 } else if failed_segment_idx > 0 {
2719 let parent = path[failed_segment_idx - 1].ident.name;
2720 let parent = match parent {
2721 kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2724 "the list of imported crates".to_owned()
2725 }
2726 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2727 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", parent))
})format!("`{parent}`"),
2728 };
2729
2730 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}");
2731 if ns == TypeNS || ns == ValueNS {
2732 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2733 let binding = if let Some(module) = module {
2734 self.cm()
2735 .resolve_ident_in_module(
2736 module,
2737 ident,
2738 ns_to_try,
2739 parent_scope,
2740 None,
2741 ignore_decl,
2742 ignore_import,
2743 )
2744 .ok()
2745 } else if let Some(ribs) = ribs
2746 && let Some(TypeNS | ValueNS) = opt_ns
2747 {
2748 if !ignore_import.is_none() {
::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
2749 match self.resolve_ident_in_lexical_scope(
2750 ident,
2751 ns_to_try,
2752 parent_scope,
2753 None,
2754 &ribs[ns_to_try],
2755 ignore_decl,
2756 diag_metadata,
2757 ) {
2758 Some(LateDecl::Decl(binding)) => Some(binding),
2760 _ => None,
2761 }
2762 } else {
2763 self.cm()
2764 .resolve_ident_in_scope_set(
2765 ident,
2766 ScopeSet::All(ns_to_try),
2767 parent_scope,
2768 None,
2769 ignore_decl,
2770 ignore_import,
2771 )
2772 .ok()
2773 };
2774 if let Some(binding) = binding {
2775 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!(
2776 "expected {}, found {} `{ident}` in {parent}",
2777 ns.descr(),
2778 binding.res().descr(),
2779 );
2780 };
2781 }
2782 (message, msg, None)
2783 } else if ident.name == kw::SelfUpper {
2784 if opt_ns.is_none() {
2788 (message, "`Self` cannot be used in imports".to_string(), None)
2789 } else {
2790 (
2791 message,
2792 "`Self` is only available in impls, traits, and type definitions".to_string(),
2793 None,
2794 )
2795 }
2796 } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2797 let binding = if let Some(ribs) = ribs {
2799 if !ignore_import.is_none() {
::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
2800 self.resolve_ident_in_lexical_scope(
2801 ident,
2802 ValueNS,
2803 parent_scope,
2804 None,
2805 &ribs[ValueNS],
2806 ignore_decl,
2807 diag_metadata,
2808 )
2809 } else {
2810 None
2811 };
2812 let match_span = match binding {
2813 Some(LateDecl::RibDef(Res::Local(id))) => {
2822 Some((*self.pat_span_map.get(&id).unwrap(), "a", "local binding"))
2823 }
2824 Some(LateDecl::Decl(name_binding)) => Some((
2836 name_binding.span,
2837 name_binding.res().article(),
2838 name_binding.res().descr(),
2839 )),
2840 _ => None,
2841 };
2842
2843 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}");
2844 let label = if let Some((span, article, descr)) = match_span {
2845 ::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!(
2846 "`{ident}` is declared as {article} {descr} at `{}`, not a type",
2847 self.tcx
2848 .sess
2849 .source_map()
2850 .span_to_short_string(span, RemapPathScopeComponents::DIAGNOSTICS)
2851 )
2852 } else {
2853 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use of undeclared type `{0}`",
ident))
})format!("use of undeclared type `{ident}`")
2854 };
2855 (message, label, None)
2856 } else {
2857 let mut suggestion = None;
2858 if ident.name == sym::alloc {
2859 suggestion = Some((
2860 ::alloc::vec::Vec::new()vec![],
2861 String::from("add `extern crate alloc` to use the `alloc` crate"),
2862 Applicability::MaybeIncorrect,
2863 ))
2864 }
2865
2866 suggestion = suggestion.or_else(|| {
2867 self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2868 |sugg| {
2869 (
2870 ::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())],
2871 String::from("there is a crate or module with a similar name"),
2872 Applicability::MaybeIncorrect,
2873 )
2874 },
2875 )
2876 });
2877 if let Ok(binding) = self.cm().resolve_ident_in_scope_set(
2878 ident,
2879 ScopeSet::All(ValueNS),
2880 parent_scope,
2881 None,
2882 ignore_decl,
2883 ignore_import,
2884 ) {
2885 let descr = binding.res().descr();
2886 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}");
2887 (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)
2888 } else {
2889 let suggestion = if suggestion.is_some() {
2890 suggestion
2891 } else if let Some(m) = self.undeclared_module_exists(ident) {
2892 self.undeclared_module_suggest_declare(ident, m)
2893 } else if was_invoked_from_cargo() {
2894 Some((
2895 ::alloc::vec::Vec::new()vec![],
2896 ::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!(
2897 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2898 to add it to your `Cargo.toml`",
2899 ),
2900 Applicability::MaybeIncorrect,
2901 ))
2902 } else {
2903 Some((
2904 ::alloc::vec::Vec::new()vec![],
2905 ::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}`",),
2906 Applicability::MaybeIncorrect,
2907 ))
2908 };
2909 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}");
2910 (
2911 message,
2912 ::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}`"),
2913 suggestion,
2914 )
2915 }
2916 }
2917 }
2918
2919 fn undeclared_module_suggest_declare(
2920 &self,
2921 ident: Ident,
2922 path: std::path::PathBuf,
2923 ) -> Option<(Vec<(Span, String)>, String, Applicability)> {
2924 Some((
2925 ::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"))],
2926 ::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!(
2927 "to make use of source file {}, use `mod {ident}` \
2928 in this file to declare the module",
2929 path.display()
2930 ),
2931 Applicability::MaybeIncorrect,
2932 ))
2933 }
2934
2935 fn undeclared_module_exists(&self, ident: Ident) -> Option<std::path::PathBuf> {
2936 let map = self.tcx.sess.source_map();
2937
2938 let src = map.span_to_filename(ident.span).into_local_path()?;
2939 let i = ident.as_str();
2940 let dir = src.parent()?;
2942 let src = src.file_stem()?.to_str()?;
2943 for file in [
2944 dir.join(i).with_extension("rs"),
2946 dir.join(i).join("mod.rs"),
2948 ] {
2949 if file.exists() {
2950 return Some(file);
2951 }
2952 }
2953 if !#[allow(non_exhaustive_omitted_patterns)] match src {
"main" | "lib" | "mod" => true,
_ => false,
}matches!(src, "main" | "lib" | "mod") {
2954 for file in [
2955 dir.join(src).join(i).with_extension("rs"),
2957 dir.join(src).join(i).join("mod.rs"),
2959 ] {
2960 if file.exists() {
2961 return Some(file);
2962 }
2963 }
2964 }
2965 None
2966 }
2967
2968 #[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(2969u32),
::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))]
2970 pub(crate) fn make_path_suggestion(
2971 &mut self,
2972 mut path: Vec<Segment>,
2973 parent_scope: &ParentScope<'ra>,
2974 ) -> Option<(Vec<Segment>, Option<String>)> {
2975 match path[..] {
2976 [first, second, ..]
2979 if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2980 [first, ..]
2982 if first.ident.span.at_least_rust_2018()
2983 && !first.ident.is_path_segment_keyword() =>
2984 {
2985 path.insert(0, Segment::from_ident(Ident::dummy()));
2987 }
2988 _ => return None,
2989 }
2990
2991 self.make_missing_self_suggestion(path.clone(), parent_scope)
2992 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2993 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2994 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2995 }
2996
2997 #[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(3004u32),
::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:3013",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3013u32),
::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))]
3005 fn make_missing_self_suggestion(
3006 &mut self,
3007 mut path: Vec<Segment>,
3008 parent_scope: &ParentScope<'ra>,
3009 ) -> Option<(Vec<Segment>, Option<String>)> {
3010 path[0].ident.name = kw::SelfLower;
3012 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
3013 debug!(?path, ?result);
3014 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
3015 }
3016
3017 #[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(3024u32),
::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:3033",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3033u32),
::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))]
3025 fn make_missing_crate_suggestion(
3026 &mut self,
3027 mut path: Vec<Segment>,
3028 parent_scope: &ParentScope<'ra>,
3029 ) -> Option<(Vec<Segment>, Option<String>)> {
3030 path[0].ident.name = kw::Crate;
3032 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
3033 debug!(?path, ?result);
3034 if let PathResult::Module(..) = result {
3035 Some((
3036 path,
3037 Some(
3038 "`use` statements changed in Rust 2018; read more at \
3039 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
3040 clarity.html>"
3041 .to_string(),
3042 ),
3043 ))
3044 } else {
3045 None
3046 }
3047 }
3048
3049 #[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(3056u32),
::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:3065",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3065u32),
::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))]
3057 fn make_missing_super_suggestion(
3058 &mut self,
3059 mut path: Vec<Segment>,
3060 parent_scope: &ParentScope<'ra>,
3061 ) -> Option<(Vec<Segment>, Option<String>)> {
3062 path[0].ident.name = kw::Super;
3064 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
3065 debug!(?path, ?result);
3066 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
3067 }
3068
3069 #[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(3079u32),
::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:3100",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3100u32),
::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))]
3080 fn make_external_crate_suggestion(
3081 &mut self,
3082 mut path: Vec<Segment>,
3083 parent_scope: &ParentScope<'ra>,
3084 ) -> Option<(Vec<Segment>, Option<String>)> {
3085 if path[1].ident.span.is_rust_2015() {
3086 return None;
3087 }
3088
3089 let mut extern_crate_names =
3093 self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
3094 extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
3095
3096 for name in extern_crate_names.into_iter() {
3097 path[0].ident.name = name;
3099 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
3100 debug!(?path, ?name, ?result);
3101 if let PathResult::Module(..) = result {
3102 return Some((path, None));
3103 }
3104 }
3105
3106 None
3107 }
3108
3109 pub(crate) fn check_for_module_export_macro(
3122 &mut self,
3123 import: Import<'ra>,
3124 module: ModuleOrUniformRoot<'ra>,
3125 ident: Ident,
3126 ) -> Option<(Option<Suggestion>, Option<String>)> {
3127 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
3128 return None;
3129 };
3130
3131 while let Some(parent) = crate_module.parent {
3132 crate_module = parent;
3133 }
3134
3135 if module == ModuleOrUniformRoot::Module(crate_module) {
3136 return None;
3138 }
3139
3140 let binding_key = BindingKey::new(IdentKey::new(ident), MacroNS);
3141 let binding = self.resolution(crate_module, binding_key)?.best_decl()?;
3142 let Res::Def(DefKind::Macro(kinds), _) = binding.res() else {
3143 return None;
3144 };
3145 if !kinds.contains(MacroKinds::BANG) {
3146 return None;
3147 }
3148 let module_name = crate_module.kind.name().unwrap_or(kw::Crate);
3149 let import_snippet = match import.kind {
3150 ImportKind::Single { source, target, .. } if source != target => {
3151 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} as {1}", source, target))
})format!("{source} as {target}")
3152 }
3153 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", ident))
})format!("{ident}"),
3154 };
3155
3156 let mut corrections: Vec<(Span, String)> = Vec::new();
3157 if !import.is_nested() {
3158 corrections.push((import.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}", module_name,
import_snippet))
})format!("{module_name}::{import_snippet}")));
3161 } else {
3162 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
3166 self.tcx.sess,
3167 import.span,
3168 import.use_span,
3169 );
3170 {
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:3170",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3170u32),
::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);
3171
3172 let mut removal_span = binding_span;
3173
3174 if found_closing_brace
3182 && let Some(previous_span) =
3183 extend_span_to_previous_binding(self.tcx.sess, binding_span)
3184 {
3185 {
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:3185",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3185u32),
::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);
3186 removal_span = removal_span.with_lo(previous_span.lo());
3187 }
3188 {
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:3188",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3188u32),
::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);
3189
3190 corrections.push((removal_span, "".to_string()));
3192
3193 let (has_nested, after_crate_name) =
3200 find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
3201 {
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:3201",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3201u32),
::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);
3202
3203 let source_map = self.tcx.sess.source_map();
3204
3205 let is_definitely_crate = import
3207 .module_path
3208 .first()
3209 .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
3210
3211 let start_point = source_map.start_point(after_crate_name);
3213 if is_definitely_crate
3214 && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
3215 {
3216 corrections.push((
3217 start_point,
3218 if has_nested {
3219 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}, ", start_snippet,
import_snippet))
})format!("{start_snippet}{import_snippet}, ")
3221 } else {
3222 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{{0}, {1}", import_snippet,
start_snippet))
})format!("{{{import_snippet}, {start_snippet}")
3225 },
3226 ));
3227
3228 if !has_nested {
3230 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
3231 }
3232 } else {
3233 corrections.push((
3235 import.use_span.shrink_to_lo(),
3236 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use {0}::{1};\n", module_name,
import_snippet))
})format!("use {module_name}::{import_snippet};\n"),
3237 ));
3238 }
3239 }
3240
3241 let suggestion = Some((
3242 corrections,
3243 String::from("a macro with this name exists at the root of the crate"),
3244 Applicability::MaybeIncorrect,
3245 ));
3246 Some((
3247 suggestion,
3248 Some(
3249 "this could be because a macro annotated with `#[macro_export]` will be exported \
3250 at the root of the crate instead of the module where it is defined"
3251 .to_string(),
3252 ),
3253 ))
3254 }
3255
3256 pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
3258 let local_items;
3259 let symbols = if module.is_local() {
3260 local_items = self
3261 .stripped_cfg_items
3262 .iter()
3263 .filter_map(|item| {
3264 let parent_scope = self.opt_local_def_id(item.parent_scope)?.to_def_id();
3265 Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg.clone() })
3266 })
3267 .collect::<Vec<_>>();
3268 local_items.as_slice()
3269 } else {
3270 self.tcx.stripped_cfg_items(module.krate)
3271 };
3272
3273 for &StrippedCfgItem { parent_scope, ident, ref cfg } in symbols {
3274 if ident.name != *segment {
3275 continue;
3276 }
3277
3278 let parent_module = self.get_nearest_non_block_module(parent_scope).def_id();
3279
3280 fn comes_from_same_module_for_glob(
3281 r: &Resolver<'_, '_>,
3282 parent_module: DefId,
3283 module: DefId,
3284 visited: &mut FxHashMap<DefId, bool>,
3285 ) -> bool {
3286 if let Some(&cached) = visited.get(&parent_module) {
3287 return cached;
3291 }
3292 visited.insert(parent_module, false);
3293 let m = r.expect_module(parent_module);
3294 let mut res = false;
3295 for importer in m.glob_importers.borrow().iter() {
3296 if let Some(next_parent_module) = importer.parent_scope.module.opt_def_id() {
3297 if next_parent_module == module
3298 || comes_from_same_module_for_glob(
3299 r,
3300 next_parent_module,
3301 module,
3302 visited,
3303 )
3304 {
3305 res = true;
3306 break;
3307 }
3308 }
3309 }
3310 visited.insert(parent_module, res);
3311 res
3312 }
3313
3314 let comes_from_same_module = parent_module == module
3315 || comes_from_same_module_for_glob(
3316 self,
3317 parent_module,
3318 module,
3319 &mut Default::default(),
3320 );
3321 if !comes_from_same_module {
3322 continue;
3323 }
3324
3325 let item_was = if let CfgEntry::NameValue { value: Some(feature), .. } = cfg.0 {
3326 errors::ItemWas::BehindFeature { feature, span: cfg.1 }
3327 } else {
3328 errors::ItemWas::CfgOut { span: cfg.1 }
3329 };
3330 let note = errors::FoundItemConfigureOut { span: ident.span, item_was };
3331 err.subdiagnostic(note);
3332 }
3333 }
3334
3335 pub(crate) fn struct_ctor(&self, def_id: DefId) -> Option<StructCtor> {
3336 match def_id.as_local() {
3337 Some(def_id) => self.struct_ctors.get(&def_id).cloned(),
3338 None => {
3339 self.cstore().ctor_untracked(self.tcx, def_id).map(|(ctor_kind, ctor_def_id)| {
3340 let res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
3341 let vis = self.tcx.visibility(ctor_def_id);
3342 let field_visibilities = self
3343 .tcx
3344 .associated_item_def_ids(def_id)
3345 .iter()
3346 .map(|&field_id| self.tcx.visibility(field_id))
3347 .collect();
3348 StructCtor { res, vis, field_visibilities }
3349 })
3350 }
3351 }
3352 }
3353}
3354
3355fn find_span_of_binding_until_next_binding(
3369 sess: &Session,
3370 binding_span: Span,
3371 use_span: Span,
3372) -> (bool, Span) {
3373 let source_map = sess.source_map();
3374
3375 let binding_until_end = binding_span.with_hi(use_span.hi());
3378
3379 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
3382
3383 let mut found_closing_brace = false;
3390 let after_binding_until_next_binding =
3391 source_map.span_take_while(after_binding_until_end, |&ch| {
3392 if ch == '}' {
3393 found_closing_brace = true;
3394 }
3395 ch == ' ' || ch == ','
3396 });
3397
3398 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
3403
3404 (found_closing_brace, span)
3405}
3406
3407fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
3420 let source_map = sess.source_map();
3421
3422 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
3426
3427 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
3428 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
3429 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
3430 return None;
3431 }
3432
3433 let prev_comma = prev_comma.first().unwrap();
3434 let prev_starting_brace = prev_starting_brace.first().unwrap();
3435
3436 if prev_comma.len() > prev_starting_brace.len() {
3440 return None;
3441 }
3442
3443 Some(binding_span.with_lo(BytePos(
3444 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
3447 )))
3448}
3449
3450#[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(3463u32),
::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))]
3464fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
3465 let source_map = sess.source_map();
3466
3467 let mut num_colons = 0;
3469 let until_second_colon = source_map.span_take_while(use_span, |c| {
3471 if *c == ':' {
3472 num_colons += 1;
3473 }
3474 !matches!(c, ':' if num_colons == 2)
3475 });
3476 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
3478
3479 let mut found_a_non_whitespace_character = false;
3480 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
3482 if found_a_non_whitespace_character {
3483 return false;
3484 }
3485 if !c.is_whitespace() {
3486 found_a_non_whitespace_character = true;
3487 }
3488 true
3489 });
3490
3491 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
3493
3494 (next_left_bracket == after_second_colon, from_second_colon)
3495}
3496
3497enum Instead {
3500 Yes,
3501 No,
3502}
3503
3504enum FoundUse {
3506 Yes,
3507 No,
3508}
3509
3510pub(crate) enum DiagMode {
3512 Normal,
3513 Pattern,
3515 Import {
3517 unresolved_import: bool,
3519 append: bool,
3522 },
3523}
3524
3525pub(crate) fn import_candidates(
3526 tcx: TyCtxt<'_>,
3527 err: &mut Diag<'_>,
3528 use_placement_span: Option<Span>,
3530 candidates: &[ImportSuggestion],
3531 mode: DiagMode,
3532 append: &str,
3533) {
3534 show_candidates(
3535 tcx,
3536 err,
3537 use_placement_span,
3538 candidates,
3539 Instead::Yes,
3540 FoundUse::Yes,
3541 mode,
3542 ::alloc::vec::Vec::new()vec![],
3543 append,
3544 );
3545}
3546
3547type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
3548
3549fn show_candidates(
3554 tcx: TyCtxt<'_>,
3555 err: &mut Diag<'_>,
3556 use_placement_span: Option<Span>,
3558 candidates: &[ImportSuggestion],
3559 instead: Instead,
3560 found_use: FoundUse,
3561 mode: DiagMode,
3562 path: Vec<Segment>,
3563 append: &str,
3564) -> bool {
3565 if candidates.is_empty() {
3566 return false;
3567 }
3568
3569 let mut showed = false;
3570 let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
3571 let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
3572
3573 candidates.iter().for_each(|c| {
3574 if c.accessible {
3575 if c.doc_visible {
3577 accessible_path_strings.push((
3578 pprust::path_to_string(&c.path),
3579 c.descr,
3580 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3581 &c.note,
3582 c.via_import,
3583 ))
3584 }
3585 } else {
3586 inaccessible_path_strings.push((
3587 pprust::path_to_string(&c.path),
3588 c.descr,
3589 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3590 &c.note,
3591 c.via_import,
3592 ))
3593 }
3594 });
3595
3596 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
3599 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
3600 path_strings.dedup_by(|a, b| a.0 == b.0);
3601 let core_path_strings =
3602 path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
3603 let std_path_strings =
3604 path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
3605 let foreign_crate_path_strings =
3606 path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
3607
3608 if std_path_strings.len() == core_path_strings.len() {
3611 path_strings.extend(std_path_strings);
3613 } else {
3614 path_strings.extend(std_path_strings);
3615 path_strings.extend(core_path_strings);
3616 }
3617 path_strings.extend(foreign_crate_path_strings);
3619 }
3620
3621 if !accessible_path_strings.is_empty() {
3622 let (determiner, kind, s, name, through) =
3623 if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
3624 (
3625 "this",
3626 *descr,
3627 "",
3628 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}`", name))
})format!(" `{name}`"),
3629 if *via_import { " through its public re-export" } else { "" },
3630 )
3631 } else {
3632 let kinds = accessible_path_strings
3635 .iter()
3636 .map(|(_, descr, _, _, _)| *descr)
3637 .collect::<UnordSet<&str>>();
3638 let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
3639 let s = if kind.ends_with('s') { "es" } else { "s" };
3640
3641 ("one of these", kind, s, String::new(), "")
3642 };
3643
3644 let instead = if let Instead::Yes = instead { " instead" } else { "" };
3645 let mut msg = if let DiagMode::Pattern = mode {
3646 ::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!(
3647 "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
3648 pattern",
3649 )
3650 } else {
3651 ::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}")
3652 };
3653
3654 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3655 err.note(note.clone());
3656 }
3657
3658 let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
3659 msg.push(':');
3660
3661 for candidate in accessible_path_strings {
3662 msg.push('\n');
3663 msg.push_str(&candidate.0);
3664 }
3665 };
3666
3667 if let Some(span) = use_placement_span {
3668 let (add_use, trailing) = match mode {
3669 DiagMode::Pattern => {
3670 err.span_suggestions(
3671 span,
3672 msg,
3673 accessible_path_strings.into_iter().map(|a| a.0),
3674 Applicability::MaybeIncorrect,
3675 );
3676 return true;
3677 }
3678 DiagMode::Import { .. } => ("", ""),
3679 DiagMode::Normal => ("use ", ";\n"),
3680 };
3681 for candidate in &mut accessible_path_strings {
3682 let additional_newline = if let FoundUse::No = found_use
3685 && let DiagMode::Normal = mode
3686 {
3687 "\n"
3688 } else {
3689 ""
3690 };
3691 candidate.0 =
3692 ::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);
3693 }
3694
3695 match mode {
3696 DiagMode::Import { append: true, .. } => {
3697 append_candidates(&mut msg, accessible_path_strings);
3698 err.span_help(span, msg);
3699 }
3700 _ => {
3701 err.span_suggestions_with_style(
3702 span,
3703 msg,
3704 accessible_path_strings.into_iter().map(|a| a.0),
3705 Applicability::MaybeIncorrect,
3706 SuggestionStyle::ShowAlways,
3707 );
3708 }
3709 }
3710
3711 if let [first, .., last] = &path[..] {
3712 let sp = first.ident.span.until(last.ident.span);
3713 if sp.can_be_used_for_suggestions() && !sp.is_empty() {
3716 err.span_suggestion_verbose(
3717 sp,
3718 ::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),
3719 "",
3720 Applicability::Unspecified,
3721 );
3722 }
3723 }
3724 } else {
3725 append_candidates(&mut msg, accessible_path_strings);
3726 err.help(msg);
3727 }
3728 showed = true;
3729 }
3730 if !inaccessible_path_strings.is_empty()
3731 && (!#[allow(non_exhaustive_omitted_patterns)] match mode {
DiagMode::Import { unresolved_import: false, .. } => true,
_ => false,
}matches!(mode, DiagMode::Import { unresolved_import: false, .. }))
3732 {
3733 let prefix =
3734 if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
3735 if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
3736 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!(
3737 "{prefix}{descr} `{name}`{} exists but is inaccessible",
3738 if let DiagMode::Pattern = mode { ", which" } else { "" }
3739 );
3740
3741 if let Some(source_span) = source_span {
3742 let span = tcx.sess.source_map().guess_head_span(*source_span);
3743 let mut multi_span = MultiSpan::from_span(span);
3744 multi_span.push_span_label(span, "not accessible");
3745 err.span_note(multi_span, msg);
3746 } else {
3747 err.note(msg);
3748 }
3749 if let Some(note) = (*note).as_deref() {
3750 err.note(note.to_string());
3751 }
3752 } else {
3753 let descr = inaccessible_path_strings
3754 .iter()
3755 .map(|&(_, descr, _, _, _)| descr)
3756 .all_equal_value()
3757 .unwrap_or("item");
3758 let plural_descr =
3759 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") };
3760
3761 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");
3762 let mut has_colon = false;
3763
3764 let mut spans = Vec::new();
3765 for (name, _, source_span, _, _) in &inaccessible_path_strings {
3766 if let Some(source_span) = source_span {
3767 let span = tcx.sess.source_map().guess_head_span(*source_span);
3768 spans.push((name, span));
3769 } else {
3770 if !has_colon {
3771 msg.push(':');
3772 has_colon = true;
3773 }
3774 msg.push('\n');
3775 msg.push_str(name);
3776 }
3777 }
3778
3779 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3780 for (name, span) in spans {
3781 multi_span.push_span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`: not accessible", name))
})format!("`{name}`: not accessible"));
3782 }
3783
3784 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3785 err.note(note.clone());
3786 }
3787
3788 err.span_note(multi_span, msg);
3789 }
3790 showed = true;
3791 }
3792 showed
3793}
3794
3795#[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)]
3796struct UsePlacementFinder {
3797 target_module: NodeId,
3798 first_legal_span: Option<Span>,
3799 first_use_span: Option<Span>,
3800}
3801
3802impl UsePlacementFinder {
3803 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3804 let mut finder =
3805 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3806 finder.visit_crate(krate);
3807 if let Some(use_span) = finder.first_use_span {
3808 (Some(use_span), FoundUse::Yes)
3809 } else {
3810 (finder.first_legal_span, FoundUse::No)
3811 }
3812 }
3813}
3814
3815impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
3816 fn visit_crate(&mut self, c: &Crate) {
3817 if self.target_module == CRATE_NODE_ID {
3818 let inject = c.spans.inject_use_span;
3819 if is_span_suitable_for_use_injection(inject) {
3820 self.first_legal_span = Some(inject);
3821 }
3822 self.first_use_span = search_for_any_use_in_items(&c.items);
3823 } else {
3824 visit::walk_crate(self, c);
3825 }
3826 }
3827
3828 fn visit_item(&mut self, item: &'tcx ast::Item) {
3829 if self.target_module == item.id {
3830 if let ItemKind::Mod(_, _, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
3831 let inject = mod_spans.inject_use_span;
3832 if is_span_suitable_for_use_injection(inject) {
3833 self.first_legal_span = Some(inject);
3834 }
3835 self.first_use_span = search_for_any_use_in_items(items);
3836 }
3837 } else {
3838 visit::walk_item(self, item);
3839 }
3840 }
3841}
3842
3843#[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)]
3844struct BindingVisitor {
3845 identifiers: Vec<Symbol>,
3846 spans: FxHashMap<Symbol, Vec<Span>>,
3847}
3848
3849impl<'tcx> Visitor<'tcx> for BindingVisitor {
3850 fn visit_pat(&mut self, pat: &ast::Pat) {
3851 if let ast::PatKind::Ident(_, ident, _) = pat.kind {
3852 self.identifiers.push(ident.name);
3853 self.spans.entry(ident.name).or_default().push(ident.span);
3854 }
3855 visit::walk_pat(self, pat);
3856 }
3857}
3858
3859fn search_for_any_use_in_items(items: &[Box<ast::Item>]) -> Option<Span> {
3860 for item in items {
3861 if let ItemKind::Use(..) = item.kind
3862 && is_span_suitable_for_use_injection(item.span)
3863 {
3864 let mut lo = item.span.lo();
3865 for attr in &item.attrs {
3866 if attr.span.eq_ctxt(item.span) {
3867 lo = std::cmp::min(lo, attr.span.lo());
3868 }
3869 }
3870 return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3871 }
3872 }
3873 None
3874}
3875
3876fn is_span_suitable_for_use_injection(s: Span) -> bool {
3877 !s.from_expansion()
3880}