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