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