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