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