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::{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, RemapPathScopeComponents, 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::FailedToResolve { segment, label, suggestion, module, message } => {
897 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", message))
})).with_code(E0433)
}struct_span_code_err!(self.dcx(), span, E0433, "{message}");
898 err.span_label(span, label);
899
900 if let Some((suggestions, msg, applicability)) = suggestion {
901 if suggestions.is_empty() {
902 err.help(msg);
903 return err;
904 }
905 err.multipart_suggestion(msg, suggestions, applicability);
906 }
907
908 let module = match module {
909 Some(ModuleOrUniformRoot::Module(m)) if let Some(id) = m.opt_def_id() => id,
910 _ => CRATE_DEF_ID.to_def_id(),
911 };
912 self.find_cfg_stripped(&mut err, &segment, module);
913
914 err
915 }
916 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
917 self.dcx().create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
918 }
919 ResolutionError::AttemptToUseNonConstantValueInConstant {
920 ident,
921 suggestion,
922 current,
923 type_span,
924 } => {
925 let sp = self
934 .tcx
935 .sess
936 .source_map()
937 .span_extend_to_prev_str(ident.span, current, true, false);
938
939 let ((with, with_label), without) = match sp {
940 Some(sp) if !self.tcx.sess.source_map().is_multiline(sp) => {
941 let sp = sp
942 .with_lo(BytePos(sp.lo().0 - (current.len() as u32)))
943 .until(ident.span);
944 (
945 (Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
946 span: sp,
947 suggestion,
948 current,
949 type_span,
950 }), Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion {span})),
951 None,
952 )
953 }
954 _ => (
955 (None, None),
956 Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
957 ident_span: ident.span,
958 suggestion,
959 }),
960 ),
961 };
962
963 self.dcx().create_err(errs::AttemptToUseNonConstantValueInConstant {
964 span,
965 with,
966 with_label,
967 without,
968 })
969 }
970 ResolutionError::BindingShadowsSomethingUnacceptable {
971 shadowing_binding,
972 name,
973 participle,
974 article,
975 shadowed_binding,
976 shadowed_binding_span,
977 } => self.dcx().create_err(errs::BindingShadowsSomethingUnacceptable {
978 span,
979 shadowing_binding,
980 shadowed_binding,
981 article,
982 sub_suggestion: match (shadowing_binding, shadowed_binding) {
983 (
984 PatternSource::Match,
985 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
986 ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
987 _ => None,
988 },
989 shadowed_binding_span,
990 participle,
991 name,
992 }),
993 ResolutionError::ForwardDeclaredGenericParam(param, reason) => match reason {
994 ForwardGenericParamBanReason::Default => {
995 self.dcx().create_err(errs::ForwardDeclaredGenericParam { param, span })
996 }
997 ForwardGenericParamBanReason::ConstParamTy => self
998 .dcx()
999 .create_err(errs::ForwardDeclaredGenericInConstParamTy { param, span }),
1000 },
1001 ResolutionError::ParamInTyOfConstParam { name } => {
1002 self.dcx().create_err(errs::ParamInTyOfConstParam { span, name })
1003 }
1004 ResolutionError::ParamInNonTrivialAnonConst { name, param_kind: is_type } => {
1005 self.dcx().create_err(errs::ParamInNonTrivialAnonConst {
1006 span,
1007 name,
1008 param_kind: is_type,
1009 help: self.tcx.sess.is_nightly_build(),
1010 })
1011 }
1012 ResolutionError::ParamInEnumDiscriminant { name, param_kind: is_type } => self
1013 .dcx()
1014 .create_err(errs::ParamInEnumDiscriminant { span, name, param_kind: is_type }),
1015 ResolutionError::ForwardDeclaredSelf(reason) => match reason {
1016 ForwardGenericParamBanReason::Default => {
1017 self.dcx().create_err(errs::SelfInGenericParamDefault { span })
1018 }
1019 ForwardGenericParamBanReason::ConstParamTy => {
1020 self.dcx().create_err(errs::SelfInConstGenericTy { span })
1021 }
1022 },
1023 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
1024 let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
1025 match suggestion {
1026 Some((ident, true)) => (
1028 (
1029 Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
1030 Some(errs::UnreachableLabelSubSuggestion {
1031 span,
1032 ident_name: ident.name,
1035 }),
1036 ),
1037 None,
1038 ),
1039 Some((ident, false)) => (
1041 (None, None),
1042 Some(errs::UnreachableLabelSubLabelUnreachable {
1043 ident_span: ident.span,
1044 }),
1045 ),
1046 None => ((None, None), None),
1048 };
1049 self.dcx().create_err(errs::UnreachableLabel {
1050 span,
1051 name,
1052 definition_span,
1053 sub_suggestion,
1054 sub_suggestion_label,
1055 sub_unreachable_label,
1056 })
1057 }
1058 ResolutionError::TraitImplMismatch {
1059 name,
1060 kind,
1061 code,
1062 trait_item_span,
1063 trait_path,
1064 } => self
1065 .dcx()
1066 .create_err(errors::TraitImplMismatch {
1067 span,
1068 name,
1069 kind,
1070 trait_path,
1071 trait_item_span,
1072 })
1073 .with_code(code),
1074 ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
1075 .dcx()
1076 .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
1077 ResolutionError::InvalidAsmSym => self.dcx().create_err(errs::InvalidAsmSym { span }),
1078 ResolutionError::LowercaseSelf => self.dcx().create_err(errs::LowercaseSelf { span }),
1079 ResolutionError::BindingInNeverPattern => {
1080 self.dcx().create_err(errs::BindingInNeverPattern { span })
1081 }
1082 }
1083 }
1084
1085 pub(crate) fn report_vis_error(
1086 &mut self,
1087 vis_resolution_error: VisResolutionError<'_>,
1088 ) -> ErrorGuaranteed {
1089 match vis_resolution_error {
1090 VisResolutionError::Relative2018(span, path) => {
1091 self.dcx().create_err(errs::Relative2018 {
1092 span,
1093 path_span: path.span,
1094 path_str: pprust::path_to_string(path),
1097 })
1098 }
1099 VisResolutionError::AncestorOnly(span) => {
1100 self.dcx().create_err(errs::AncestorOnly(span))
1101 }
1102 VisResolutionError::FailedToResolve(span, segment, label, suggestion, message) => self
1103 .into_struct_error(
1104 span,
1105 ResolutionError::FailedToResolve {
1106 segment,
1107 label,
1108 suggestion,
1109 module: None,
1110 message,
1111 },
1112 ),
1113 VisResolutionError::ExpectedFound(span, path_str, res) => {
1114 self.dcx().create_err(errs::ExpectedModuleFound { span, res, path_str })
1115 }
1116 VisResolutionError::Indeterminate(span) => {
1117 self.dcx().create_err(errs::Indeterminate(span))
1118 }
1119 VisResolutionError::ModuleOnly(span) => self.dcx().create_err(errs::ModuleOnly(span)),
1120 }
1121 .emit()
1122 }
1123
1124 fn def_path_str(&self, mut def_id: DefId) -> String {
1125 let mut path = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[def_id]))vec![def_id];
1127 while let Some(parent) = self.tcx.opt_parent(def_id) {
1128 def_id = parent;
1129 path.push(def_id);
1130 if def_id.is_top_level_module() {
1131 break;
1132 }
1133 }
1134 path.into_iter()
1136 .rev()
1137 .map(|def_id| {
1138 self.tcx
1139 .opt_item_name(def_id)
1140 .map(|name| {
1141 match (
1142 def_id.is_top_level_module(),
1143 def_id.is_local(),
1144 self.tcx.sess.edition(),
1145 ) {
1146 (true, true, Edition::Edition2015) => String::new(),
1147 (true, true, _) => kw::Crate.to_string(),
1148 (true, false, _) | (false, _, _) => name.to_string(),
1149 }
1150 })
1151 .unwrap_or_else(|| "_".to_string())
1152 })
1153 .collect::<Vec<String>>()
1154 .join("::")
1155 }
1156
1157 pub(crate) fn add_scope_set_candidates(
1158 &mut self,
1159 suggestions: &mut Vec<TypoSuggestion>,
1160 scope_set: ScopeSet<'ra>,
1161 ps: &ParentScope<'ra>,
1162 sp: Span,
1163 filter_fn: &impl Fn(Res) -> bool,
1164 ) {
1165 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
1166 self.cm().visit_scopes(scope_set, ps, ctxt, sp, None, |this, scope, use_prelude, _| {
1167 match scope {
1168 Scope::DeriveHelpers(expn_id) => {
1169 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1170 if filter_fn(res) {
1171 suggestions.extend(
1172 this.helper_attrs.get(&expn_id).into_iter().flatten().map(
1173 |&(ident, orig_ident_span, _)| {
1174 TypoSuggestion::new(ident.name, orig_ident_span, res)
1175 },
1176 ),
1177 );
1178 }
1179 }
1180 Scope::DeriveHelpersCompat => {
1181 }
1183 Scope::MacroRules(macro_rules_scope) => {
1184 if let MacroRulesScope::Def(macro_rules_def) = macro_rules_scope.get() {
1185 let res = macro_rules_def.decl.res();
1186 if filter_fn(res) {
1187 suggestions.push(TypoSuggestion::new(
1188 macro_rules_def.ident.name,
1189 macro_rules_def.orig_ident_span,
1190 res,
1191 ))
1192 }
1193 }
1194 }
1195 Scope::ModuleNonGlobs(module, _) => {
1196 this.add_module_candidates(module, suggestions, filter_fn, None);
1197 }
1198 Scope::ModuleGlobs(..) => {
1199 }
1201 Scope::MacroUsePrelude => {
1202 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1203 |(name, binding)| {
1204 let res = binding.res();
1205 filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1206 },
1207 ));
1208 }
1209 Scope::BuiltinAttrs => {
1210 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(sym::dummy));
1211 if filter_fn(res) {
1212 suggestions.extend(
1213 BUILTIN_ATTRIBUTES
1214 .iter()
1215 .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1216 );
1217 }
1218 }
1219 Scope::ExternPreludeItems => {
1220 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, entry)| {
1222 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1223 filter_fn(res).then_some(TypoSuggestion::new(ident.name, entry.span(), res))
1224 }));
1225 }
1226 Scope::ExternPreludeFlags => {}
1227 Scope::ToolPrelude => {
1228 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1229 suggestions.extend(
1230 this.registered_tools
1231 .iter()
1232 .map(|ident| TypoSuggestion::new(ident.name, ident.span, res)),
1233 );
1234 }
1235 Scope::StdLibPrelude => {
1236 if let Some(prelude) = this.prelude {
1237 let mut tmp_suggestions = Vec::new();
1238 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1239 suggestions.extend(
1240 tmp_suggestions
1241 .into_iter()
1242 .filter(|s| use_prelude.into() || this.is_builtin_macro(s.res)),
1243 );
1244 }
1245 }
1246 Scope::BuiltinTypes => {
1247 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1248 let res = Res::PrimTy(*prim_ty);
1249 filter_fn(res)
1250 .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1251 }))
1252 }
1253 }
1254
1255 ControlFlow::<()>::Continue(())
1256 });
1257 }
1258
1259 fn early_lookup_typo_candidate(
1261 &mut self,
1262 scope_set: ScopeSet<'ra>,
1263 parent_scope: &ParentScope<'ra>,
1264 ident: Ident,
1265 filter_fn: &impl Fn(Res) -> bool,
1266 ) -> Option<TypoSuggestion> {
1267 let mut suggestions = Vec::new();
1268 self.add_scope_set_candidates(
1269 &mut suggestions,
1270 scope_set,
1271 parent_scope,
1272 ident.span,
1273 filter_fn,
1274 );
1275
1276 suggestions.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
1278
1279 match find_best_match_for_name(
1280 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1281 ident.name,
1282 None,
1283 ) {
1284 Some(found) if found != ident.name => {
1285 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1286 }
1287 _ => None,
1288 }
1289 }
1290
1291 fn lookup_import_candidates_from_module<FilterFn>(
1292 &self,
1293 lookup_ident: Ident,
1294 namespace: Namespace,
1295 parent_scope: &ParentScope<'ra>,
1296 start_module: Module<'ra>,
1297 crate_path: ThinVec<ast::PathSegment>,
1298 filter_fn: FilterFn,
1299 ) -> Vec<ImportSuggestion>
1300 where
1301 FilterFn: Fn(Res) -> bool,
1302 {
1303 let mut candidates = Vec::new();
1304 let mut seen_modules = FxHashSet::default();
1305 let start_did = start_module.def_id();
1306 let mut worklist = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(start_module, ThinVec::<ast::PathSegment>::new(), true,
start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
true)]))vec![(
1307 start_module,
1308 ThinVec::<ast::PathSegment>::new(),
1309 true,
1310 start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
1311 true,
1312 )];
1313 let mut worklist_via_import = ::alloc::vec::Vec::new()vec![];
1314
1315 while let Some((in_module, path_segments, accessible, doc_visible, is_stable)) =
1316 match worklist.pop() {
1317 None => worklist_via_import.pop(),
1318 Some(x) => Some(x),
1319 }
1320 {
1321 let in_module_is_extern = !in_module.def_id().is_local();
1322 in_module.for_each_child(self, |this, ident, orig_ident_span, ns, name_binding| {
1323 if name_binding.is_assoc_item()
1325 && !this.tcx.features().import_trait_associated_functions()
1326 {
1327 return;
1328 }
1329
1330 if ident.name == kw::Underscore {
1331 return;
1332 }
1333
1334 let child_accessible =
1335 accessible && this.is_accessible_from(name_binding.vis(), parent_scope.module);
1336
1337 if in_module_is_extern && !child_accessible {
1339 return;
1340 }
1341
1342 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1343
1344 if via_import && name_binding.is_possibly_imported_variant() {
1350 return;
1351 }
1352
1353 if let DeclKind::Import { source_decl, .. } = name_binding.kind
1355 && this.is_accessible_from(source_decl.vis(), parent_scope.module)
1356 && !this.is_accessible_from(name_binding.vis(), parent_scope.module)
1357 {
1358 return;
1359 }
1360
1361 let res = name_binding.res();
1362 let did = match res {
1363 Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1364 _ => res.opt_def_id(),
1365 };
1366 let child_doc_visible = doc_visible
1367 && did.is_none_or(|did| did.is_local() || !this.tcx.is_doc_hidden(did));
1368
1369 if ident.name == lookup_ident.name
1373 && ns == namespace
1374 && in_module != parent_scope.module
1375 && ident.ctxt.is_root()
1376 && filter_fn(res)
1377 {
1378 let mut segms = if lookup_ident.span.at_least_rust_2018() {
1380 crate_path.clone()
1383 } else {
1384 ThinVec::new()
1385 };
1386 segms.append(&mut path_segments.clone());
1387
1388 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
1389 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1390
1391 if child_accessible
1392 && let Some(idx) = candidates
1394 .iter()
1395 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1396 {
1397 candidates.remove(idx);
1398 }
1399
1400 let is_stable = if is_stable
1401 && let Some(did) = did
1402 && this.is_stable(did, path.span)
1403 {
1404 true
1405 } else {
1406 false
1407 };
1408
1409 if is_stable
1414 && let Some(idx) = candidates
1415 .iter()
1416 .position(|v: &ImportSuggestion| v.did == did && !v.is_stable)
1417 {
1418 candidates.remove(idx);
1419 }
1420
1421 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1422 let note = if let Some(did) = did {
1425 let requires_note = !did.is_local()
1426 && {
#[allow(deprecated)]
{
{
'done:
{
for i in this.tcx.get_all_attrs(did) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcDiagnosticItem(sym::TryInto
| sym::TryFrom | sym::FromIterator)) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}.is_some()find_attr!(
1427 this.tcx,
1428 did,
1429 RustcDiagnosticItem(
1430 sym::TryInto | sym::TryFrom | sym::FromIterator
1431 )
1432 );
1433 requires_note.then(|| {
1434 ::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!(
1435 "'{}' is included in the prelude starting in Edition 2021",
1436 path_names_to_string(&path)
1437 )
1438 })
1439 } else {
1440 None
1441 };
1442
1443 candidates.push(ImportSuggestion {
1444 did,
1445 descr: res.descr(),
1446 path,
1447 accessible: child_accessible,
1448 doc_visible: child_doc_visible,
1449 note,
1450 via_import,
1451 is_stable,
1452 });
1453 }
1454 }
1455
1456 if let Some(def_id) = name_binding.res().module_like_def_id() {
1458 let mut path_segments = path_segments.clone();
1460 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
1461
1462 let alias_import = if let DeclKind::Import { import, .. } = name_binding.kind
1463 && let ImportKind::ExternCrate { source: Some(_), .. } = import.kind
1464 && import.parent_scope.expansion == parent_scope.expansion
1465 {
1466 true
1467 } else {
1468 false
1469 };
1470
1471 let is_extern_crate_that_also_appears_in_prelude =
1472 name_binding.is_extern_crate() && lookup_ident.span.at_least_rust_2018();
1473
1474 if !is_extern_crate_that_also_appears_in_prelude || alias_import {
1475 if seen_modules.insert(def_id) {
1477 if via_import { &mut worklist_via_import } else { &mut worklist }.push(
1478 (
1479 this.expect_module(def_id),
1480 path_segments,
1481 child_accessible,
1482 child_doc_visible,
1483 is_stable && this.is_stable(def_id, name_binding.span),
1484 ),
1485 );
1486 }
1487 }
1488 }
1489 })
1490 }
1491
1492 candidates
1493 }
1494
1495 fn is_stable(&self, did: DefId, span: Span) -> bool {
1496 if did.is_local() {
1497 return true;
1498 }
1499
1500 match self.tcx.lookup_stability(did) {
1501 Some(Stability {
1502 level: StabilityLevel::Unstable { implied_by, .. }, feature, ..
1503 }) => {
1504 if span.allows_unstable(feature) {
1505 true
1506 } else if self.tcx.features().enabled(feature) {
1507 true
1508 } else if let Some(implied_by) = implied_by
1509 && self.tcx.features().enabled(implied_by)
1510 {
1511 true
1512 } else {
1513 false
1514 }
1515 }
1516 Some(_) => true,
1517 None => false,
1518 }
1519 }
1520
1521 pub(crate) fn lookup_import_candidates<FilterFn>(
1529 &mut self,
1530 lookup_ident: Ident,
1531 namespace: Namespace,
1532 parent_scope: &ParentScope<'ra>,
1533 filter_fn: FilterFn,
1534 ) -> Vec<ImportSuggestion>
1535 where
1536 FilterFn: Fn(Res) -> bool,
1537 {
1538 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))];
1539 let mut suggestions = self.lookup_import_candidates_from_module(
1540 lookup_ident,
1541 namespace,
1542 parent_scope,
1543 self.graph_root,
1544 crate_path,
1545 &filter_fn,
1546 );
1547
1548 if lookup_ident.span.at_least_rust_2018() {
1549 for (ident, entry) in &self.extern_prelude {
1550 if entry.span().from_expansion() {
1551 continue;
1557 }
1558 let Some(crate_id) =
1559 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
1560 else {
1561 continue;
1562 };
1563
1564 let crate_def_id = crate_id.as_def_id();
1565 let crate_root = self.expect_module(crate_def_id);
1566
1567 let needs_disambiguation =
1571 self.resolutions(parent_scope.module).borrow().iter().any(
1572 |(key, name_resolution)| {
1573 if key.ns == TypeNS
1574 && key.ident == *ident
1575 && let Some(decl) = name_resolution.borrow().best_decl()
1576 {
1577 match decl.res() {
1578 Res::Def(_, def_id) => def_id != crate_def_id,
1581 Res::PrimTy(_) => true,
1582 _ => false,
1583 }
1584 } else {
1585 false
1586 }
1587 },
1588 );
1589 let mut crate_path = ThinVec::new();
1590 if needs_disambiguation {
1591 crate_path.push(ast::PathSegment::path_root(rustc_span::DUMMY_SP));
1592 }
1593 crate_path.push(ast::PathSegment::from_ident(ident.orig(entry.span())));
1594
1595 suggestions.extend(self.lookup_import_candidates_from_module(
1596 lookup_ident,
1597 namespace,
1598 parent_scope,
1599 crate_root,
1600 crate_path,
1601 &filter_fn,
1602 ));
1603 }
1604 }
1605
1606 suggestions.retain(|suggestion| suggestion.is_stable || self.tcx.sess.is_nightly_build());
1607 suggestions
1608 }
1609
1610 pub(crate) fn unresolved_macro_suggestions(
1611 &mut self,
1612 err: &mut Diag<'_>,
1613 macro_kind: MacroKind,
1614 parent_scope: &ParentScope<'ra>,
1615 ident: Ident,
1616 krate: &Crate,
1617 sugg_span: Option<Span>,
1618 ) {
1619 self.register_macros_for_all_crates();
1622
1623 let is_expected =
1624 &|res: Res| res.macro_kinds().is_some_and(|k| k.contains(macro_kind.into()));
1625 let suggestion = self.early_lookup_typo_candidate(
1626 ScopeSet::Macro(macro_kind),
1627 parent_scope,
1628 ident,
1629 is_expected,
1630 );
1631 if !self.add_typo_suggestion(err, suggestion, ident.span) {
1632 self.detect_derive_attribute(err, ident, parent_scope, sugg_span);
1633 }
1634
1635 let import_suggestions =
1636 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1637 let (span, found_use) = match parent_scope.module.nearest_parent_mod().as_local() {
1638 Some(def_id) => UsePlacementFinder::check(krate, self.def_id_to_node_id(def_id)),
1639 None => (None, FoundUse::No),
1640 };
1641 show_candidates(
1642 self.tcx,
1643 err,
1644 span,
1645 &import_suggestions,
1646 Instead::No,
1647 found_use,
1648 DiagMode::Normal,
1649 ::alloc::vec::Vec::new()vec![],
1650 "",
1651 );
1652
1653 if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1654 let label_span = ident.span.shrink_to_hi();
1655 let mut spans = MultiSpan::from_span(label_span);
1656 spans.push_span_label(label_span, "put a macro name here");
1657 err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1658 return;
1659 }
1660
1661 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1662 err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1663 return;
1664 }
1665
1666 let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1667 if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1668 });
1669
1670 if let Some((def_id, unused_ident)) = unused_macro {
1671 let scope = self.local_macro_def_scopes[&def_id];
1672 let parent_nearest = parent_scope.module.nearest_parent_mod();
1673 let unused_macro_kinds = self.local_macro_map[def_id].ext.macro_kinds();
1674 if !unused_macro_kinds.contains(macro_kind.into()) {
1675 match macro_kind {
1676 MacroKind::Bang => {
1677 err.subdiagnostic(MacroRulesNot::Func { span: unused_ident.span, ident });
1678 }
1679 MacroKind::Attr => {
1680 err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1681 }
1682 MacroKind::Derive => {
1683 err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1684 }
1685 }
1686 return;
1687 }
1688 if Some(parent_nearest) == scope.opt_def_id() {
1689 err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1690 err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1691 return;
1692 }
1693 }
1694
1695 if ident.name == kw::Default
1696 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1697 {
1698 let span = self.def_span(def_id);
1699 let source_map = self.tcx.sess.source_map();
1700 let head_span = source_map.guess_head_span(span);
1701 err.subdiagnostic(ConsiderAddingADerive {
1702 span: head_span.shrink_to_lo(),
1703 suggestion: "#[derive(Default)]\n".to_string(),
1704 });
1705 }
1706 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1707 let Ok(binding) = self.cm().resolve_ident_in_scope_set(
1708 ident,
1709 ScopeSet::All(ns),
1710 parent_scope,
1711 None,
1712 None,
1713 None,
1714 ) else {
1715 continue;
1716 };
1717
1718 let desc = match binding.res() {
1719 Res::Def(DefKind::Macro(MacroKinds::BANG), _) => {
1720 "a function-like macro".to_string()
1721 }
1722 Res::Def(DefKind::Macro(MacroKinds::ATTR), _) | Res::NonMacroAttr(..) => {
1723 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("an attribute: `#[{0}]`", ident))
})format!("an attribute: `#[{ident}]`")
1724 }
1725 Res::Def(DefKind::Macro(MacroKinds::DERIVE), _) => {
1726 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a derive macro: `#[derive({0})]`",
ident))
})format!("a derive macro: `#[derive({ident})]`")
1727 }
1728 Res::Def(DefKind::Macro(kinds), _) => {
1729 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", kinds.article(),
kinds.descr()))
})format!("{} {}", kinds.article(), kinds.descr())
1730 }
1731 Res::ToolMod => {
1732 continue;
1734 }
1735 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1736 "only a trait, without a derive macro".to_string()
1737 }
1738 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!(
1739 "{} {}, not {} {}",
1740 res.article(),
1741 res.descr(),
1742 macro_kind.article(),
1743 macro_kind.descr_expected(),
1744 ),
1745 };
1746 if let crate::DeclKind::Import { import, .. } = binding.kind
1747 && !import.span.is_dummy()
1748 {
1749 let note = errors::IdentImporterHereButItIsDesc {
1750 span: import.span,
1751 imported_ident: ident,
1752 imported_ident_desc: &desc,
1753 };
1754 err.subdiagnostic(note);
1755 self.record_use(ident, binding, Used::Other);
1758 return;
1759 }
1760 let note = errors::IdentInScopeButItIsDesc {
1761 imported_ident: ident,
1762 imported_ident_desc: &desc,
1763 };
1764 err.subdiagnostic(note);
1765 return;
1766 }
1767
1768 if self.macro_names.contains(&IdentKey::new(ident)) {
1769 err.subdiagnostic(AddedMacroUse);
1770 return;
1771 }
1772 }
1773
1774 fn detect_derive_attribute(
1777 &self,
1778 err: &mut Diag<'_>,
1779 ident: Ident,
1780 parent_scope: &ParentScope<'ra>,
1781 sugg_span: Option<Span>,
1782 ) {
1783 let mut derives = ::alloc::vec::Vec::new()vec![];
1788 let mut all_attrs: UnordMap<Symbol, Vec<_>> = UnordMap::default();
1789 #[allow(rustc::potential_query_instability)]
1791 for (def_id, data) in self
1792 .local_macro_map
1793 .iter()
1794 .map(|(local_id, data)| (local_id.to_def_id(), data))
1795 .chain(self.extern_macro_map.borrow().iter().map(|(id, d)| (*id, d)))
1796 {
1797 for helper_attr in &data.ext.helper_attrs {
1798 let item_name = self.tcx.item_name(def_id);
1799 all_attrs.entry(*helper_attr).or_default().push(item_name);
1800 if helper_attr == &ident.name {
1801 derives.push(item_name);
1802 }
1803 }
1804 }
1805 let kind = MacroKind::Derive.descr();
1806 if !derives.is_empty() {
1807 let mut derives: Vec<String> = derives.into_iter().map(|d| d.to_string()).collect();
1809 derives.sort();
1810 derives.dedup();
1811 let msg = match &derives[..] {
1812 [derive] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}`", derive))
})format!(" `{derive}`"),
1813 [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!(
1814 "s {} and `{last}`",
1815 start.iter().map(|d| format!("`{d}`")).collect::<Vec<_>>().join(", ")
1816 ),
1817 [] => {
::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!?"),
1818 };
1819 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!(
1820 "`{}` is an attribute that can be used by the {kind}{msg}, you might be \
1821 missing a `derive` attribute",
1822 ident.name,
1823 );
1824 let sugg_span = if let ModuleKind::Def(DefKind::Enum, id, _) = parent_scope.module.kind
1825 {
1826 let span = self.def_span(id);
1827 if span.from_expansion() {
1828 None
1829 } else {
1830 Some(span.shrink_to_lo())
1832 }
1833 } else {
1834 sugg_span
1836 };
1837 match sugg_span {
1838 Some(span) => {
1839 err.span_suggestion_verbose(
1840 span,
1841 msg,
1842 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n",
derives.join(", ")))
})format!("#[derive({})]\n", derives.join(", ")),
1843 Applicability::MaybeIncorrect,
1844 );
1845 }
1846 None => {
1847 err.note(msg);
1848 }
1849 }
1850 } else {
1851 let all_attr_names = all_attrs.keys().map(|s| *s).into_sorted_stable_ord();
1853 if let Some(best_match) = find_best_match_for_name(&all_attr_names, ident.name, None)
1854 && let Some(macros) = all_attrs.get(&best_match)
1855 {
1856 let mut macros: Vec<String> = macros.into_iter().map(|d| d.to_string()).collect();
1857 macros.sort();
1858 macros.dedup();
1859 let msg = match ¯os[..] {
1860 [] => return,
1861 [name] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}` accepts", name))
})format!(" `{name}` accepts"),
1862 [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!(
1863 "s {} and `{end}` accept",
1864 start.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", "),
1865 ),
1866 };
1867 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");
1868 err.span_suggestion_verbose(
1869 ident.span,
1870 msg,
1871 best_match,
1872 Applicability::MaybeIncorrect,
1873 );
1874 }
1875 }
1876 }
1877
1878 pub(crate) fn add_typo_suggestion(
1879 &self,
1880 err: &mut Diag<'_>,
1881 suggestion: Option<TypoSuggestion>,
1882 span: Span,
1883 ) -> bool {
1884 let suggestion = match suggestion {
1885 None => return false,
1886 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1888 Some(suggestion) => suggestion,
1889 };
1890
1891 let mut did_label_def_span = false;
1892
1893 if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
1894 if span.overlaps(def_span) {
1895 return false;
1914 }
1915 let span = self.tcx.sess.source_map().guess_head_span(def_span);
1916 let candidate_descr = suggestion.res.descr();
1917 let candidate = suggestion.candidate;
1918 let label = match suggestion.target {
1919 SuggestionTarget::SimilarlyNamed => {
1920 errors::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
1921 }
1922 SuggestionTarget::SingleItem => {
1923 errors::DefinedHere::SingleItem { span, candidate_descr, candidate }
1924 }
1925 };
1926 did_label_def_span = true;
1927 err.subdiagnostic(label);
1928 }
1929
1930 let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
1931 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1932 && let Some(span) = suggestion.span
1933 && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
1934 && snippet == candidate
1935 {
1936 let candidate = suggestion.candidate;
1937 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!(
1940 "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
1941 );
1942 if !did_label_def_span {
1943 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", candidate))
})format!("`{candidate}` defined here"));
1944 }
1945 (span, msg, snippet)
1946 } else {
1947 let msg = match suggestion.target {
1948 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!(
1949 "{} {} with a similar name exists",
1950 suggestion.res.article(),
1951 suggestion.res.descr()
1952 ),
1953 SuggestionTarget::SingleItem => {
1954 ::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())
1955 }
1956 };
1957 (span, msg, suggestion.candidate.to_ident_string())
1958 };
1959 err.span_suggestion_verbose(span, msg, sugg, Applicability::MaybeIncorrect);
1960 true
1961 }
1962
1963 fn decl_description(&self, b: Decl<'_>, ident: Ident, scope: Scope<'_>) -> String {
1964 let res = b.res();
1965 if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
1966 let (built_in, from) = match scope {
1967 Scope::StdLibPrelude | Scope::MacroUsePrelude => ("", " from prelude"),
1968 Scope::ExternPreludeFlags
1969 if self.tcx.sess.opts.externs.get(ident.as_str()).is_some() =>
1970 {
1971 ("", " passed with `--extern`")
1972 }
1973 _ => {
1974 if #[allow(non_exhaustive_omitted_patterns)] match res {
Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => true,
_ => false,
}matches!(res, Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod) {
1975 ("", "")
1977 } else {
1978 (" built-in", "")
1979 }
1980 }
1981 };
1982
1983 let a = if built_in.is_empty() { res.article() } else { "a" };
1984 ::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())
1985 } else {
1986 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1987 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} {1} here", res.descr(),
introduced))
})format!("the {thing} {introduced} here", thing = res.descr())
1988 }
1989 }
1990
1991 fn ambiguity_diagnostic(&self, ambiguity_error: &AmbiguityError<'ra>) -> errors::Ambiguity {
1992 let AmbiguityError { kind, ambig_vis, ident, b1, b2, scope1, scope2, .. } =
1993 *ambiguity_error;
1994 let extern_prelude_ambiguity = || {
1995 #[allow(non_exhaustive_omitted_patterns)] match scope2 {
Scope::ExternPreludeFlags => true,
_ => false,
}matches!(scope2, Scope::ExternPreludeFlags)
1997 && self
1998 .extern_prelude
1999 .get(&IdentKey::new(ident))
2000 .is_some_and(|entry| entry.item_decl.map(|(b, ..)| b) == Some(b1))
2001 };
2002 let (b1, b2, scope1, scope2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
2003 (b2, b1, scope2, scope1, true)
2005 } else {
2006 (b1, b2, scope1, scope2, false)
2007 };
2008
2009 let could_refer_to = |b: Decl<'_>, scope: Scope<'ra>, also: &str| {
2010 let what = self.decl_description(b, ident, scope);
2011 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}");
2012
2013 let thing = b.res().descr();
2014 let mut help_msgs = Vec::new();
2015 if b.is_glob_import()
2016 && (kind == AmbiguityKind::GlobVsGlob
2017 || kind == AmbiguityKind::GlobVsExpanded
2018 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
2019 {
2020 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider adding an explicit import of `{0}` to disambiguate",
ident))
})format!(
2021 "consider adding an explicit import of `{ident}` to disambiguate"
2022 ))
2023 }
2024 if b.is_extern_crate() && ident.span.at_least_rust_2018() && !extern_prelude_ambiguity()
2025 {
2026 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"))
2027 }
2028
2029 if kind != AmbiguityKind::GlobVsGlob {
2030 if let Scope::ModuleNonGlobs(module, _) | Scope::ModuleGlobs(module, _) = scope {
2031 if module == self.graph_root {
2032 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `crate::{0}` to refer to this {1} unambiguously",
ident, thing))
})format!(
2033 "use `crate::{ident}` to refer to this {thing} unambiguously"
2034 ));
2035 } else if module.is_normal() {
2036 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `self::{0}` to refer to this {1} unambiguously",
ident, thing))
})format!(
2037 "use `self::{ident}` to refer to this {thing} unambiguously"
2038 ));
2039 }
2040 }
2041 }
2042
2043 (
2044 Spanned { node: note_msg, span: b.span },
2045 help_msgs
2046 .iter()
2047 .enumerate()
2048 .map(|(i, help_msg)| {
2049 let or = if i == 0 { "" } else { "or " };
2050 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", or, help_msg))
})format!("{or}{help_msg}")
2051 })
2052 .collect::<Vec<_>>(),
2053 )
2054 };
2055 let (b1_note, b1_help_msgs) = could_refer_to(b1, scope1, "");
2056 let (b2_note, b2_help_msgs) = could_refer_to(b2, scope2, " also");
2057 let help = if kind == AmbiguityKind::GlobVsGlob
2058 && b1
2059 .parent_module
2060 .and_then(|m| m.opt_def_id())
2061 .map(|d| !d.is_local())
2062 .unwrap_or_default()
2063 {
2064 Some(&[
2065 "consider updating this dependency to resolve this error",
2066 "if updating the dependency does not resolve the problem report the problem to the author of the relevant crate",
2067 ] as &[_])
2068 } else {
2069 None
2070 };
2071
2072 let ambig_vis = ambig_vis.map(|(vis1, vis2)| {
2073 ::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!(
2074 "{} or {}",
2075 vis1.to_string(CRATE_DEF_ID, self.tcx),
2076 vis2.to_string(CRATE_DEF_ID, self.tcx)
2077 )
2078 });
2079
2080 errors::Ambiguity {
2081 ident,
2082 help,
2083 ambig_vis,
2084 kind: kind.descr(),
2085 b1_note,
2086 b1_help_msgs,
2087 b2_note,
2088 b2_help_msgs,
2089 }
2090 }
2091
2092 fn ctor_fields_span(&self, decl: Decl<'_>) -> Option<Span> {
2095 let DeclKind::Def(Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id)) =
2096 decl.kind
2097 else {
2098 return None;
2099 };
2100
2101 let def_id = self.tcx.parent(ctor_def_id);
2102 self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) }
2104
2105 fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
2106 let PrivacyError {
2107 ident,
2108 decl,
2109 outermost_res,
2110 parent_scope,
2111 single_nested,
2112 dedup_span,
2113 ref source,
2114 } = *privacy_error;
2115
2116 let res = decl.res();
2117 let ctor_fields_span = self.ctor_fields_span(decl);
2118 let plain_descr = res.descr().to_string();
2119 let nonimport_descr =
2120 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
2121 let import_descr = nonimport_descr.clone() + " import";
2122 let get_descr = |b: Decl<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
2123
2124 let ident_descr = get_descr(decl);
2126 let mut err =
2127 self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
2128
2129 self.mention_default_field_values(source, ident, &mut err);
2130
2131 let mut not_publicly_reexported = false;
2132 if let Some((this_res, outer_ident)) = outermost_res {
2133 let import_suggestions = self.lookup_import_candidates(
2134 outer_ident,
2135 this_res.ns().unwrap_or(Namespace::TypeNS),
2136 &parent_scope,
2137 &|res: Res| res == this_res,
2138 );
2139 let point_to_def = !show_candidates(
2140 self.tcx,
2141 &mut err,
2142 Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
2143 &import_suggestions,
2144 Instead::Yes,
2145 FoundUse::Yes,
2146 DiagMode::Import { append: single_nested, unresolved_import: false },
2147 ::alloc::vec::Vec::new()vec![],
2148 "",
2149 );
2150 if point_to_def && ident.span != outer_ident.span {
2152 not_publicly_reexported = true;
2153 let label = errors::OuterIdentIsNotPubliclyReexported {
2154 span: outer_ident.span,
2155 outer_ident_descr: this_res.descr(),
2156 outer_ident,
2157 };
2158 err.subdiagnostic(label);
2159 }
2160 }
2161
2162 let mut non_exhaustive = None;
2163 if let Some(def_id) = res.opt_def_id()
2167 && !def_id.is_local()
2168 && let Some(attr_span) = {
#[allow(deprecated)]
{
{
'done:
{
for i in self.tcx.get_all_attrs(def_id) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(NonExhaustive(span)) => {
break 'done Some(*span);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}find_attr!(self.tcx, def_id, NonExhaustive(span) => *span)
2169 {
2170 non_exhaustive = Some(attr_span);
2171 } else if let Some(span) = ctor_fields_span {
2172 let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
2173 err.subdiagnostic(label);
2174 if let Res::Def(_, d) = res
2175 && let Some(fields) = self.field_visibility_spans.get(&d)
2176 {
2177 let spans = fields.iter().map(|span| *span).collect();
2178 let sugg =
2179 errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
2180 err.subdiagnostic(sugg);
2181 }
2182 }
2183
2184 let mut sugg_paths: Vec<(Vec<Ident>, bool)> = ::alloc::vec::Vec::new()vec![];
2185 if let Some(mut def_id) = res.opt_def_id() {
2186 let mut path = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[def_id]))vec![def_id];
2188 while let Some(parent) = self.tcx.opt_parent(def_id) {
2189 def_id = parent;
2190 if !def_id.is_top_level_module() {
2191 path.push(def_id);
2192 } else {
2193 break;
2194 }
2195 }
2196 let path_names: Option<Vec<Ident>> = path
2198 .iter()
2199 .rev()
2200 .map(|def_id| {
2201 self.tcx.opt_item_name(*def_id).map(|name| {
2202 Ident::with_dummy_span(if def_id.is_top_level_module() {
2203 kw::Crate
2204 } else {
2205 name
2206 })
2207 })
2208 })
2209 .collect();
2210 if let Some(def_id) = path.get(0)
2211 && let Some(path) = path_names
2212 {
2213 if let Some(def_id) = def_id.as_local() {
2214 if self.effective_visibilities.is_directly_public(def_id) {
2215 sugg_paths.push((path, false));
2216 }
2217 } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
2218 {
2219 sugg_paths.push((path, false));
2220 }
2221 }
2222 }
2223
2224 let first_binding = decl;
2226 let mut next_binding = Some(decl);
2227 let mut next_ident = ident;
2228 let mut path = ::alloc::vec::Vec::new()vec![];
2229 while let Some(binding) = next_binding {
2230 let name = next_ident;
2231 next_binding = match binding.kind {
2232 _ if res == Res::Err => None,
2233 DeclKind::Import { source_decl, import, .. } => match import.kind {
2234 _ if source_decl.span.is_dummy() => None,
2235 ImportKind::Single { source, .. } => {
2236 next_ident = source;
2237 Some(source_decl)
2238 }
2239 ImportKind::Glob { .. }
2240 | ImportKind::MacroUse { .. }
2241 | ImportKind::MacroExport => Some(source_decl),
2242 ImportKind::ExternCrate { .. } => None,
2243 },
2244 _ => None,
2245 };
2246
2247 match binding.kind {
2248 DeclKind::Import { import, .. } => {
2249 for segment in import.module_path.iter().skip(1) {
2250 if segment.ident.name != kw::PathRoot {
2253 path.push(segment.ident);
2254 }
2255 }
2256 sugg_paths.push((
2257 path.iter().cloned().chain(std::iter::once(ident)).collect::<Vec<_>>(),
2258 true, ));
2260 }
2261 DeclKind::Def(_) => {}
2262 }
2263 let first = binding == first_binding;
2264 let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
2265 let mut note_span = MultiSpan::from_span(def_span);
2266 if !first && binding.vis().is_public() {
2267 let desc = match binding.kind {
2268 DeclKind::Import { .. } => "re-export",
2269 _ => "directly",
2270 };
2271 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}"));
2272 }
2273 if next_binding.is_none()
2276 && let Some(span) = non_exhaustive
2277 {
2278 note_span.push_span_label(
2279 span,
2280 "cannot be constructed because it is `#[non_exhaustive]`",
2281 );
2282 }
2283 let note = errors::NoteAndRefersToTheItemDefinedHere {
2284 span: note_span,
2285 binding_descr: get_descr(binding),
2286 binding_name: name,
2287 first,
2288 dots: next_binding.is_some(),
2289 };
2290 err.subdiagnostic(note);
2291 }
2292 sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0].name == sym::core, *reexport));
2294 for (sugg, reexport) in sugg_paths {
2295 if not_publicly_reexported {
2296 break;
2297 }
2298 if sugg.len() <= 1 {
2299 continue;
2302 }
2303 let path = join_path_idents(sugg);
2304 let sugg = if reexport {
2305 errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
2306 } else {
2307 errors::ImportIdent::Directly { span: dedup_span, ident, path }
2308 };
2309 err.subdiagnostic(sugg);
2310 break;
2311 }
2312
2313 err.emit();
2314 }
2315
2316 fn mention_default_field_values(
2336 &self,
2337 source: &Option<ast::Expr>,
2338 ident: Ident,
2339 err: &mut Diag<'_>,
2340 ) {
2341 let Some(expr) = source else { return };
2342 let ast::ExprKind::Struct(struct_expr) = &expr.kind else { return };
2343 let Some(segment) = struct_expr.path.segments.last() else { return };
2346 let Some(partial_res) = self.partial_res_map.get(&segment.id) else { return };
2347 let Some(Res::Def(_, def_id)) = partial_res.full_res() else {
2348 return;
2349 };
2350 let Some(default_fields) = self.field_defaults(def_id) else { return };
2351 if struct_expr.fields.is_empty() {
2352 return;
2353 }
2354 let last_span = struct_expr.fields.iter().last().unwrap().span;
2355 let mut iter = struct_expr.fields.iter().peekable();
2356 let mut prev: Option<Span> = None;
2357 while let Some(field) = iter.next() {
2358 if field.expr.span.overlaps(ident.span) {
2359 err.span_label(field.ident.span, "while setting this field");
2360 if default_fields.contains(&field.ident.name) {
2361 let sugg = if last_span == field.span {
2362 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(field.span, "..".to_string())]))vec![(field.span, "..".to_string())]
2363 } else {
2364 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(match (prev, iter.peek()) {
(_, Some(next)) => field.span.with_hi(next.span.lo()),
(Some(prev), _) => field.span.with_lo(prev.hi()),
(None, None) => field.span,
}, String::new()),
(last_span.shrink_to_hi(), ", ..".to_string())]))vec![
2365 (
2366 match (prev, iter.peek()) {
2368 (_, Some(next)) => field.span.with_hi(next.span.lo()),
2369 (Some(prev), _) => field.span.with_lo(prev.hi()),
2370 (None, None) => field.span,
2371 },
2372 String::new(),
2373 ),
2374 (last_span.shrink_to_hi(), ", ..".to_string()),
2375 ]
2376 };
2377 err.multipart_suggestion(
2378 ::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!(
2379 "the type `{ident}` of field `{}` is private, but you can construct \
2380 the default value defined for it in `{}` using `..` in the struct \
2381 initializer expression",
2382 field.ident,
2383 self.tcx.item_name(def_id),
2384 ),
2385 sugg,
2386 Applicability::MachineApplicable,
2387 );
2388 break;
2389 }
2390 }
2391 prev = Some(field.span);
2392 }
2393 }
2394
2395 pub(crate) fn find_similarly_named_module_or_crate(
2396 &self,
2397 ident: Symbol,
2398 current_module: Module<'ra>,
2399 ) -> Option<Symbol> {
2400 let mut candidates = self
2401 .extern_prelude
2402 .keys()
2403 .map(|ident| ident.name)
2404 .chain(
2405 self.local_module_map
2406 .iter()
2407 .filter(|(_, module)| {
2408 current_module.is_ancestor_of(**module) && current_module != **module
2409 })
2410 .flat_map(|(_, module)| module.kind.name()),
2411 )
2412 .chain(
2413 self.extern_module_map
2414 .borrow()
2415 .iter()
2416 .filter(|(_, module)| {
2417 current_module.is_ancestor_of(**module) && current_module != **module
2418 })
2419 .flat_map(|(_, module)| module.kind.name()),
2420 )
2421 .filter(|c| !c.to_string().is_empty())
2422 .collect::<Vec<_>>();
2423 candidates.sort();
2424 candidates.dedup();
2425 find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
2426 }
2427
2428 pub(crate) fn report_path_resolution_error(
2429 &mut self,
2430 path: &[Segment],
2431 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
2433 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
2434 ignore_decl: Option<Decl<'ra>>,
2435 ignore_import: Option<Import<'ra>>,
2436 module: Option<ModuleOrUniformRoot<'ra>>,
2437 failed_segment_idx: usize,
2438 ident: Ident,
2439 diag_metadata: Option<&DiagMetadata<'_>>,
2440 ) -> (String, String, Option<Suggestion>) {
2441 let is_last = failed_segment_idx == path.len() - 1;
2442 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2443 let module_res = match module {
2444 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2445 _ => None,
2446 };
2447 let scope = match &path[..failed_segment_idx] {
2448 [.., prev] => {
2449 if prev.ident.name == kw::PathRoot {
2450 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the crate root"))
})format!("the crate root")
2451 } else {
2452 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", prev.ident))
})format!("`{}`", prev.ident)
2453 }
2454 }
2455 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this scope"))
})format!("this scope"),
2456 };
2457 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find `{0}` in {1}", ident,
scope))
})format!("cannot find `{ident}` in {scope}");
2458
2459 if module_res == self.graph_root.res() {
2460 let is_mod = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _));
2461 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2462 candidates
2463 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2464 if let Some(candidate) = candidates.get(0) {
2465 let path = {
2466 let len = candidate.path.segments.len();
2468 let start_index = (0..=failed_segment_idx.min(len - 1))
2469 .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2470 .unwrap_or_default();
2471 let segments =
2472 (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2473 Path { segments, span: Span::default(), tokens: None }
2474 };
2475 (
2476 message,
2477 String::from("unresolved import"),
2478 Some((
2479 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, pprust::path_to_string(&path))]))vec![(ident.span, pprust::path_to_string(&path))],
2480 String::from("a similar path exists"),
2481 Applicability::MaybeIncorrect,
2482 )),
2483 )
2484 } else if ident.name == sym::core {
2485 (
2486 message,
2487 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might be missing crate `{0}`",
ident))
})format!("you might be missing crate `{ident}`"),
2488 Some((
2489 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, "std".to_string())]))vec![(ident.span, "std".to_string())],
2490 "try using `std` instead of `core`".to_string(),
2491 Applicability::MaybeIncorrect,
2492 )),
2493 )
2494 } else if ident.name == kw::Underscore {
2495 (
2496 "invalid crate or module name `_`".to_string(),
2497 "`_` is not a valid crate or module name".to_string(),
2498 None,
2499 )
2500 } else if self.tcx.sess.is_rust_2015() {
2501 (
2502 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
ident, scope))
})format!("cannot find module or crate `{ident}` in {scope}"),
2503 ::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}`"),
2504 Some((
2505 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.current_crate_outer_attr_insert_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern crate {0};\n",
ident))
}))]))vec![(
2506 self.current_crate_outer_attr_insert_span,
2507 format!("extern crate {ident};\n"),
2508 )],
2509 if was_invoked_from_cargo() {
2510 ::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!(
2511 "if you wanted to use a crate named `{ident}`, use `cargo add \
2512 {ident}` to add it to your `Cargo.toml` and import it in your \
2513 code",
2514 )
2515 } else {
2516 ::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!(
2517 "you might be missing a crate named `{ident}`, add it to your \
2518 project and import it in your code",
2519 )
2520 },
2521 Applicability::MaybeIncorrect,
2522 )),
2523 )
2524 } else {
2525 (message, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not find `{0}` in the crate root",
ident))
})format!("could not find `{ident}` in the crate root"), None)
2526 }
2527 } else if failed_segment_idx > 0 {
2528 let parent = path[failed_segment_idx - 1].ident.name;
2529 let parent = match parent {
2530 kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2533 "the list of imported crates".to_owned()
2534 }
2535 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2536 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", parent))
})format!("`{parent}`"),
2537 };
2538
2539 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}");
2540 if ns == TypeNS || ns == ValueNS {
2541 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2542 let binding = if let Some(module) = module {
2543 self.cm()
2544 .resolve_ident_in_module(
2545 module,
2546 ident,
2547 ns_to_try,
2548 parent_scope,
2549 None,
2550 ignore_decl,
2551 ignore_import,
2552 )
2553 .ok()
2554 } else if let Some(ribs) = ribs
2555 && let Some(TypeNS | ValueNS) = opt_ns
2556 {
2557 if !ignore_import.is_none() {
::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
2558 match self.resolve_ident_in_lexical_scope(
2559 ident,
2560 ns_to_try,
2561 parent_scope,
2562 None,
2563 &ribs[ns_to_try],
2564 ignore_decl,
2565 diag_metadata,
2566 ) {
2567 Some(LateDecl::Decl(binding)) => Some(binding),
2569 _ => None,
2570 }
2571 } else {
2572 self.cm()
2573 .resolve_ident_in_scope_set(
2574 ident,
2575 ScopeSet::All(ns_to_try),
2576 parent_scope,
2577 None,
2578 ignore_decl,
2579 ignore_import,
2580 )
2581 .ok()
2582 };
2583 if let Some(binding) = binding {
2584 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!(
2585 "expected {}, found {} `{ident}` in {parent}",
2586 ns.descr(),
2587 binding.res().descr(),
2588 );
2589 };
2590 }
2591 (message, msg, None)
2592 } else if ident.name == kw::SelfUpper {
2593 if opt_ns.is_none() {
2597 (message, "`Self` cannot be used in imports".to_string(), None)
2598 } else {
2599 (
2600 message,
2601 "`Self` is only available in impls, traits, and type definitions".to_string(),
2602 None,
2603 )
2604 }
2605 } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
2606 let binding = if let Some(ribs) = ribs {
2608 if !ignore_import.is_none() {
::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
2609 self.resolve_ident_in_lexical_scope(
2610 ident,
2611 ValueNS,
2612 parent_scope,
2613 None,
2614 &ribs[ValueNS],
2615 ignore_decl,
2616 diag_metadata,
2617 )
2618 } else {
2619 None
2620 };
2621 let match_span = match binding {
2622 Some(LateDecl::RibDef(Res::Local(id))) => {
2631 Some((*self.pat_span_map.get(&id).unwrap(), "a", "local binding"))
2632 }
2633 Some(LateDecl::Decl(name_binding)) => Some((
2645 name_binding.span,
2646 name_binding.res().article(),
2647 name_binding.res().descr(),
2648 )),
2649 _ => None,
2650 };
2651
2652 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find type `{0}` in {1}",
ident, scope))
})format!("cannot find type `{ident}` in {scope}");
2653 let label = if let Some((span, article, descr)) = match_span {
2654 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{1}` is declared as {2} {3} at `{0}`, not a type",
self.tcx.sess.source_map().span_to_short_string(span,
RemapPathScopeComponents::DIAGNOSTICS), ident, article,
descr))
})format!(
2655 "`{ident}` is declared as {article} {descr} at `{}`, not a type",
2656 self.tcx
2657 .sess
2658 .source_map()
2659 .span_to_short_string(span, RemapPathScopeComponents::DIAGNOSTICS)
2660 )
2661 } else {
2662 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use of undeclared type `{0}`",
ident))
})format!("use of undeclared type `{ident}`")
2663 };
2664 (message, label, None)
2665 } else {
2666 let mut suggestion = None;
2667 if ident.name == sym::alloc {
2668 suggestion = Some((
2669 ::alloc::vec::Vec::new()vec![],
2670 String::from("add `extern crate alloc` to use the `alloc` crate"),
2671 Applicability::MaybeIncorrect,
2672 ))
2673 }
2674
2675 suggestion = suggestion.or_else(|| {
2676 self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
2677 |sugg| {
2678 (
2679 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, sugg.to_string())]))vec![(ident.span, sugg.to_string())],
2680 String::from("there is a crate or module with a similar name"),
2681 Applicability::MaybeIncorrect,
2682 )
2683 },
2684 )
2685 });
2686 if let Ok(binding) = self.cm().resolve_ident_in_scope_set(
2687 ident,
2688 ScopeSet::All(ValueNS),
2689 parent_scope,
2690 None,
2691 ignore_decl,
2692 ignore_import,
2693 ) {
2694 let descr = binding.res().descr();
2695 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
ident, scope))
})format!("cannot find module or crate `{ident}` in {scope}");
2696 (message, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` is not a crate or module",
descr, ident))
})format!("{descr} `{ident}` is not a crate or module"), suggestion)
2697 } else {
2698 let suggestion = if suggestion.is_some() {
2699 suggestion
2700 } else if let Some(m) = self.undeclared_module_exists(ident) {
2701 self.undeclared_module_suggest_declare(ident, m)
2702 } else if was_invoked_from_cargo() {
2703 Some((
2704 ::alloc::vec::Vec::new()vec![],
2705 ::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!(
2706 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
2707 to add it to your `Cargo.toml`",
2708 ),
2709 Applicability::MaybeIncorrect,
2710 ))
2711 } else {
2712 Some((
2713 ::alloc::vec::Vec::new()vec![],
2714 ::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}`",),
2715 Applicability::MaybeIncorrect,
2716 ))
2717 };
2718 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
ident, scope))
})format!("cannot find module or crate `{ident}` in {scope}");
2719 (
2720 message,
2721 ::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}`"),
2722 suggestion,
2723 )
2724 }
2725 }
2726 }
2727
2728 fn undeclared_module_suggest_declare(
2729 &self,
2730 ident: Ident,
2731 path: std::path::PathBuf,
2732 ) -> Option<(Vec<(Span, String)>, String, Applicability)> {
2733 Some((
2734 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.current_crate_outer_attr_insert_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("mod {0};\n", ident))
}))]))vec![(self.current_crate_outer_attr_insert_span, format!("mod {ident};\n"))],
2735 ::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!(
2736 "to make use of source file {}, use `mod {ident}` \
2737 in this file to declare the module",
2738 path.display()
2739 ),
2740 Applicability::MaybeIncorrect,
2741 ))
2742 }
2743
2744 fn undeclared_module_exists(&self, ident: Ident) -> Option<std::path::PathBuf> {
2745 let map = self.tcx.sess.source_map();
2746
2747 let src = map.span_to_filename(ident.span).into_local_path()?;
2748 let i = ident.as_str();
2749 let dir = src.parent()?;
2751 let src = src.file_stem()?.to_str()?;
2752 for file in [
2753 dir.join(i).with_extension("rs"),
2755 dir.join(i).join("mod.rs"),
2757 ] {
2758 if file.exists() {
2759 return Some(file);
2760 }
2761 }
2762 if !#[allow(non_exhaustive_omitted_patterns)] match src {
"main" | "lib" | "mod" => true,
_ => false,
}matches!(src, "main" | "lib" | "mod") {
2763 for file in [
2764 dir.join(src).join(i).with_extension("rs"),
2766 dir.join(src).join(i).join("mod.rs"),
2768 ] {
2769 if file.exists() {
2770 return Some(file);
2771 }
2772 }
2773 }
2774 None
2775 }
2776
2777 #[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(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;
}
{
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))]
2779 pub(crate) fn make_path_suggestion(
2780 &mut self,
2781 mut path: Vec<Segment>,
2782 parent_scope: &ParentScope<'ra>,
2783 ) -> Option<(Vec<Segment>, Option<String>)> {
2784 match path[..] {
2785 [first, second, ..]
2788 if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
2789 [first, ..]
2791 if first.ident.span.at_least_rust_2018()
2792 && !first.ident.is_path_segment_keyword() =>
2793 {
2794 path.insert(0, Segment::from_ident(Ident::dummy()));
2796 }
2797 _ => return None,
2798 }
2799
2800 self.make_missing_self_suggestion(path.clone(), parent_scope)
2801 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2802 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2803 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2804 }
2805
2806 #[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(2813u32),
::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:2822",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2822u32),
::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))]
2814 fn make_missing_self_suggestion(
2815 &mut self,
2816 mut path: Vec<Segment>,
2817 parent_scope: &ParentScope<'ra>,
2818 ) -> Option<(Vec<Segment>, Option<String>)> {
2819 path[0].ident.name = kw::SelfLower;
2821 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2822 debug!(?path, ?result);
2823 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2824 }
2825
2826 #[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(2833u32),
::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:2842",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2842u32),
::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))]
2834 fn make_missing_crate_suggestion(
2835 &mut self,
2836 mut path: Vec<Segment>,
2837 parent_scope: &ParentScope<'ra>,
2838 ) -> Option<(Vec<Segment>, Option<String>)> {
2839 path[0].ident.name = kw::Crate;
2841 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2842 debug!(?path, ?result);
2843 if let PathResult::Module(..) = result {
2844 Some((
2845 path,
2846 Some(
2847 "`use` statements changed in Rust 2018; read more at \
2848 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2849 clarity.html>"
2850 .to_string(),
2851 ),
2852 ))
2853 } else {
2854 None
2855 }
2856 }
2857
2858 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("make_missing_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(2865u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Option<(Vec<Segment>, Option<String>)> = loop {};
return __tracing_attr_fake_return;
}
{
path[0].ident.name = kw::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:2874",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2874u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["path", "result"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&result) as
&dyn Value))])
});
} else { ; }
};
if let PathResult::Module(..) = result {
Some((path, None))
} else { None }
}
}
}#[instrument(level = "debug", skip(self, parent_scope))]
2866 fn make_missing_super_suggestion(
2867 &mut self,
2868 mut path: Vec<Segment>,
2869 parent_scope: &ParentScope<'ra>,
2870 ) -> Option<(Vec<Segment>, Option<String>)> {
2871 path[0].ident.name = kw::Super;
2873 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2874 debug!(?path, ?result);
2875 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
2876 }
2877
2878 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("make_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(2888u32),
::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:2909",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2909u32),
::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))]
2889 fn make_external_crate_suggestion(
2890 &mut self,
2891 mut path: Vec<Segment>,
2892 parent_scope: &ParentScope<'ra>,
2893 ) -> Option<(Vec<Segment>, Option<String>)> {
2894 if path[1].ident.span.is_rust_2015() {
2895 return None;
2896 }
2897
2898 let mut extern_crate_names =
2902 self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
2903 extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
2904
2905 for name in extern_crate_names.into_iter() {
2906 path[0].ident.name = name;
2908 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
2909 debug!(?path, ?name, ?result);
2910 if let PathResult::Module(..) = result {
2911 return Some((path, None));
2912 }
2913 }
2914
2915 None
2916 }
2917
2918 pub(crate) fn check_for_module_export_macro(
2931 &mut self,
2932 import: Import<'ra>,
2933 module: ModuleOrUniformRoot<'ra>,
2934 ident: Ident,
2935 ) -> Option<(Option<Suggestion>, Option<String>)> {
2936 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2937 return None;
2938 };
2939
2940 while let Some(parent) = crate_module.parent {
2941 crate_module = parent;
2942 }
2943
2944 if module == ModuleOrUniformRoot::Module(crate_module) {
2945 return None;
2947 }
2948
2949 let binding_key = BindingKey::new(IdentKey::new(ident), MacroNS);
2950 let binding = self.resolution(crate_module, binding_key)?.binding()?;
2951 let Res::Def(DefKind::Macro(kinds), _) = binding.res() else {
2952 return None;
2953 };
2954 if !kinds.contains(MacroKinds::BANG) {
2955 return None;
2956 }
2957 let module_name = crate_module.kind.name().unwrap_or(kw::Crate);
2958 let import_snippet = match import.kind {
2959 ImportKind::Single { source, target, .. } if source != target => {
2960 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} as {1}", source, target))
})format!("{source} as {target}")
2961 }
2962 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", ident))
})format!("{ident}"),
2963 };
2964
2965 let mut corrections: Vec<(Span, String)> = Vec::new();
2966 if !import.is_nested() {
2967 corrections.push((import.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}", module_name,
import_snippet))
})format!("{module_name}::{import_snippet}")));
2970 } else {
2971 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2975 self.tcx.sess,
2976 import.span,
2977 import.use_span,
2978 );
2979 {
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:2979",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2979u32),
::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);
2980
2981 let mut removal_span = binding_span;
2982
2983 if found_closing_brace
2991 && let Some(previous_span) =
2992 extend_span_to_previous_binding(self.tcx.sess, binding_span)
2993 {
2994 {
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:2994",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2994u32),
::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);
2995 removal_span = removal_span.with_lo(previous_span.lo());
2996 }
2997 {
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:2997",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2997u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::diagnostics"),
::tracing_core::field::FieldSet::new(&["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);
2998
2999 corrections.push((removal_span, "".to_string()));
3001
3002 let (has_nested, after_crate_name) =
3009 find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
3010 {
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:3010",
"rustc_resolve::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3010u32),
::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);
3011
3012 let source_map = self.tcx.sess.source_map();
3013
3014 let is_definitely_crate = import
3016 .module_path
3017 .first()
3018 .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
3019
3020 let start_point = source_map.start_point(after_crate_name);
3022 if is_definitely_crate
3023 && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
3024 {
3025 corrections.push((
3026 start_point,
3027 if has_nested {
3028 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}, ", start_snippet,
import_snippet))
})format!("{start_snippet}{import_snippet}, ")
3030 } else {
3031 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{{0}, {1}", import_snippet,
start_snippet))
})format!("{{{import_snippet}, {start_snippet}")
3034 },
3035 ));
3036
3037 if !has_nested {
3039 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
3040 }
3041 } else {
3042 corrections.push((
3044 import.use_span.shrink_to_lo(),
3045 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use {0}::{1};\n", module_name,
import_snippet))
})format!("use {module_name}::{import_snippet};\n"),
3046 ));
3047 }
3048 }
3049
3050 let suggestion = Some((
3051 corrections,
3052 String::from("a macro with this name exists at the root of the crate"),
3053 Applicability::MaybeIncorrect,
3054 ));
3055 Some((
3056 suggestion,
3057 Some(
3058 "this could be because a macro annotated with `#[macro_export]` will be exported \
3059 at the root of the crate instead of the module where it is defined"
3060 .to_string(),
3061 ),
3062 ))
3063 }
3064
3065 pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
3067 let local_items;
3068 let symbols = if module.is_local() {
3069 local_items = self
3070 .stripped_cfg_items
3071 .iter()
3072 .filter_map(|item| {
3073 let parent_module = self.opt_local_def_id(item.parent_module)?.to_def_id();
3074 Some(StrippedCfgItem {
3075 parent_module,
3076 ident: item.ident,
3077 cfg: item.cfg.clone(),
3078 })
3079 })
3080 .collect::<Vec<_>>();
3081 local_items.as_slice()
3082 } else {
3083 self.tcx.stripped_cfg_items(module.krate)
3084 };
3085
3086 for &StrippedCfgItem { parent_module, ident, ref cfg } in symbols {
3087 if ident.name != *segment {
3088 continue;
3089 }
3090
3091 fn comes_from_same_module_for_glob(
3092 r: &Resolver<'_, '_>,
3093 parent_module: DefId,
3094 module: DefId,
3095 visited: &mut FxHashMap<DefId, bool>,
3096 ) -> bool {
3097 if let Some(&cached) = visited.get(&parent_module) {
3098 return cached;
3102 }
3103 visited.insert(parent_module, false);
3104 let m = r.expect_module(parent_module);
3105 let mut res = false;
3106 for importer in m.glob_importers.borrow().iter() {
3107 if let Some(next_parent_module) = importer.parent_scope.module.opt_def_id() {
3108 if next_parent_module == module
3109 || comes_from_same_module_for_glob(
3110 r,
3111 next_parent_module,
3112 module,
3113 visited,
3114 )
3115 {
3116 res = true;
3117 break;
3118 }
3119 }
3120 }
3121 visited.insert(parent_module, res);
3122 res
3123 }
3124
3125 let comes_from_same_module = parent_module == module
3126 || comes_from_same_module_for_glob(
3127 self,
3128 parent_module,
3129 module,
3130 &mut Default::default(),
3131 );
3132 if !comes_from_same_module {
3133 continue;
3134 }
3135
3136 let item_was = if let CfgEntry::NameValue { value: Some(feature), .. } = cfg.0 {
3137 errors::ItemWas::BehindFeature { feature, span: cfg.1 }
3138 } else {
3139 errors::ItemWas::CfgOut { span: cfg.1 }
3140 };
3141 let note = errors::FoundItemConfigureOut { span: ident.span, item_was };
3142 err.subdiagnostic(note);
3143 }
3144 }
3145}
3146
3147fn find_span_of_binding_until_next_binding(
3161 sess: &Session,
3162 binding_span: Span,
3163 use_span: Span,
3164) -> (bool, Span) {
3165 let source_map = sess.source_map();
3166
3167 let binding_until_end = binding_span.with_hi(use_span.hi());
3170
3171 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
3174
3175 let mut found_closing_brace = false;
3182 let after_binding_until_next_binding =
3183 source_map.span_take_while(after_binding_until_end, |&ch| {
3184 if ch == '}' {
3185 found_closing_brace = true;
3186 }
3187 ch == ' ' || ch == ','
3188 });
3189
3190 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
3195
3196 (found_closing_brace, span)
3197}
3198
3199fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
3212 let source_map = sess.source_map();
3213
3214 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
3218
3219 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
3220 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
3221 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
3222 return None;
3223 }
3224
3225 let prev_comma = prev_comma.first().unwrap();
3226 let prev_starting_brace = prev_starting_brace.first().unwrap();
3227
3228 if prev_comma.len() > prev_starting_brace.len() {
3232 return None;
3233 }
3234
3235 Some(binding_span.with_lo(BytePos(
3236 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
3239 )))
3240}
3241
3242#[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(3255u32),
::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))]
3256fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
3257 let source_map = sess.source_map();
3258
3259 let mut num_colons = 0;
3261 let until_second_colon = source_map.span_take_while(use_span, |c| {
3263 if *c == ':' {
3264 num_colons += 1;
3265 }
3266 !matches!(c, ':' if num_colons == 2)
3267 });
3268 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
3270
3271 let mut found_a_non_whitespace_character = false;
3272 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
3274 if found_a_non_whitespace_character {
3275 return false;
3276 }
3277 if !c.is_whitespace() {
3278 found_a_non_whitespace_character = true;
3279 }
3280 true
3281 });
3282
3283 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
3285
3286 (next_left_bracket == after_second_colon, from_second_colon)
3287}
3288
3289enum Instead {
3292 Yes,
3293 No,
3294}
3295
3296enum FoundUse {
3298 Yes,
3299 No,
3300}
3301
3302pub(crate) enum DiagMode {
3304 Normal,
3305 Pattern,
3307 Import {
3309 unresolved_import: bool,
3311 append: bool,
3314 },
3315}
3316
3317pub(crate) fn import_candidates(
3318 tcx: TyCtxt<'_>,
3319 err: &mut Diag<'_>,
3320 use_placement_span: Option<Span>,
3322 candidates: &[ImportSuggestion],
3323 mode: DiagMode,
3324 append: &str,
3325) {
3326 show_candidates(
3327 tcx,
3328 err,
3329 use_placement_span,
3330 candidates,
3331 Instead::Yes,
3332 FoundUse::Yes,
3333 mode,
3334 ::alloc::vec::Vec::new()vec![],
3335 append,
3336 );
3337}
3338
3339type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
3340
3341fn show_candidates(
3346 tcx: TyCtxt<'_>,
3347 err: &mut Diag<'_>,
3348 use_placement_span: Option<Span>,
3350 candidates: &[ImportSuggestion],
3351 instead: Instead,
3352 found_use: FoundUse,
3353 mode: DiagMode,
3354 path: Vec<Segment>,
3355 append: &str,
3356) -> bool {
3357 if candidates.is_empty() {
3358 return false;
3359 }
3360
3361 let mut showed = false;
3362 let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
3363 let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
3364
3365 candidates.iter().for_each(|c| {
3366 if c.accessible {
3367 if c.doc_visible {
3369 accessible_path_strings.push((
3370 pprust::path_to_string(&c.path),
3371 c.descr,
3372 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3373 &c.note,
3374 c.via_import,
3375 ))
3376 }
3377 } else {
3378 inaccessible_path_strings.push((
3379 pprust::path_to_string(&c.path),
3380 c.descr,
3381 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3382 &c.note,
3383 c.via_import,
3384 ))
3385 }
3386 });
3387
3388 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
3391 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
3392 path_strings.dedup_by(|a, b| a.0 == b.0);
3393 let core_path_strings =
3394 path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
3395 let std_path_strings =
3396 path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
3397 let foreign_crate_path_strings =
3398 path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
3399
3400 if std_path_strings.len() == core_path_strings.len() {
3403 path_strings.extend(std_path_strings);
3405 } else {
3406 path_strings.extend(std_path_strings);
3407 path_strings.extend(core_path_strings);
3408 }
3409 path_strings.extend(foreign_crate_path_strings);
3411 }
3412
3413 if !accessible_path_strings.is_empty() {
3414 let (determiner, kind, s, name, through) =
3415 if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
3416 (
3417 "this",
3418 *descr,
3419 "",
3420 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}`", name))
})format!(" `{name}`"),
3421 if *via_import { " through its public re-export" } else { "" },
3422 )
3423 } else {
3424 let kinds = accessible_path_strings
3427 .iter()
3428 .map(|(_, descr, _, _, _)| *descr)
3429 .collect::<UnordSet<&str>>();
3430 let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
3431 let s = if kind.ends_with('s') { "es" } else { "s" };
3432
3433 ("one of these", kind, s, String::new(), "")
3434 };
3435
3436 let instead = if let Instead::Yes = instead { " instead" } else { "" };
3437 let mut msg = if let DiagMode::Pattern = mode {
3438 ::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!(
3439 "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
3440 pattern",
3441 )
3442 } else {
3443 ::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}")
3444 };
3445
3446 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3447 err.note(note.clone());
3448 }
3449
3450 let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
3451 msg.push(':');
3452
3453 for candidate in accessible_path_strings {
3454 msg.push('\n');
3455 msg.push_str(&candidate.0);
3456 }
3457 };
3458
3459 if let Some(span) = use_placement_span {
3460 let (add_use, trailing) = match mode {
3461 DiagMode::Pattern => {
3462 err.span_suggestions(
3463 span,
3464 msg,
3465 accessible_path_strings.into_iter().map(|a| a.0),
3466 Applicability::MaybeIncorrect,
3467 );
3468 return true;
3469 }
3470 DiagMode::Import { .. } => ("", ""),
3471 DiagMode::Normal => ("use ", ";\n"),
3472 };
3473 for candidate in &mut accessible_path_strings {
3474 let additional_newline = if let FoundUse::No = found_use
3477 && let DiagMode::Normal = mode
3478 {
3479 "\n"
3480 } else {
3481 ""
3482 };
3483 candidate.0 =
3484 ::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);
3485 }
3486
3487 match mode {
3488 DiagMode::Import { append: true, .. } => {
3489 append_candidates(&mut msg, accessible_path_strings);
3490 err.span_help(span, msg);
3491 }
3492 _ => {
3493 err.span_suggestions_with_style(
3494 span,
3495 msg,
3496 accessible_path_strings.into_iter().map(|a| a.0),
3497 Applicability::MaybeIncorrect,
3498 SuggestionStyle::ShowAlways,
3499 );
3500 }
3501 }
3502
3503 if let [first, .., last] = &path[..] {
3504 let sp = first.ident.span.until(last.ident.span);
3505 if sp.can_be_used_for_suggestions() && !sp.is_empty() {
3508 err.span_suggestion_verbose(
3509 sp,
3510 ::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),
3511 "",
3512 Applicability::Unspecified,
3513 );
3514 }
3515 }
3516 } else {
3517 append_candidates(&mut msg, accessible_path_strings);
3518 err.help(msg);
3519 }
3520 showed = true;
3521 }
3522 if !inaccessible_path_strings.is_empty()
3523 && (!#[allow(non_exhaustive_omitted_patterns)] match mode {
DiagMode::Import { unresolved_import: false, .. } => true,
_ => false,
}matches!(mode, DiagMode::Import { unresolved_import: false, .. }))
3524 {
3525 let prefix =
3526 if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
3527 if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
3528 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!(
3529 "{prefix}{descr} `{name}`{} exists but is inaccessible",
3530 if let DiagMode::Pattern = mode { ", which" } else { "" }
3531 );
3532
3533 if let Some(source_span) = source_span {
3534 let span = tcx.sess.source_map().guess_head_span(*source_span);
3535 let mut multi_span = MultiSpan::from_span(span);
3536 multi_span.push_span_label(span, "not accessible");
3537 err.span_note(multi_span, msg);
3538 } else {
3539 err.note(msg);
3540 }
3541 if let Some(note) = (*note).as_deref() {
3542 err.note(note.to_string());
3543 }
3544 } else {
3545 let descr = inaccessible_path_strings
3546 .iter()
3547 .map(|&(_, descr, _, _, _)| descr)
3548 .all_equal_value()
3549 .unwrap_or("item");
3550 let plural_descr =
3551 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") };
3552
3553 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");
3554 let mut has_colon = false;
3555
3556 let mut spans = Vec::new();
3557 for (name, _, source_span, _, _) in &inaccessible_path_strings {
3558 if let Some(source_span) = source_span {
3559 let span = tcx.sess.source_map().guess_head_span(*source_span);
3560 spans.push((name, span));
3561 } else {
3562 if !has_colon {
3563 msg.push(':');
3564 has_colon = true;
3565 }
3566 msg.push('\n');
3567 msg.push_str(name);
3568 }
3569 }
3570
3571 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
3572 for (name, span) in spans {
3573 multi_span.push_span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`: not accessible", name))
})format!("`{name}`: not accessible"));
3574 }
3575
3576 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3577 err.note(note.clone());
3578 }
3579
3580 err.span_note(multi_span, msg);
3581 }
3582 showed = true;
3583 }
3584 showed
3585}
3586
3587#[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)]
3588struct UsePlacementFinder {
3589 target_module: NodeId,
3590 first_legal_span: Option<Span>,
3591 first_use_span: Option<Span>,
3592}
3593
3594impl UsePlacementFinder {
3595 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
3596 let mut finder =
3597 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
3598 finder.visit_crate(krate);
3599 if let Some(use_span) = finder.first_use_span {
3600 (Some(use_span), FoundUse::Yes)
3601 } else {
3602 (finder.first_legal_span, FoundUse::No)
3603 }
3604 }
3605}
3606
3607impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
3608 fn visit_crate(&mut self, c: &Crate) {
3609 if self.target_module == CRATE_NODE_ID {
3610 let inject = c.spans.inject_use_span;
3611 if is_span_suitable_for_use_injection(inject) {
3612 self.first_legal_span = Some(inject);
3613 }
3614 self.first_use_span = search_for_any_use_in_items(&c.items);
3615 } else {
3616 visit::walk_crate(self, c);
3617 }
3618 }
3619
3620 fn visit_item(&mut self, item: &'tcx ast::Item) {
3621 if self.target_module == item.id {
3622 if let ItemKind::Mod(_, _, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
3623 let inject = mod_spans.inject_use_span;
3624 if is_span_suitable_for_use_injection(inject) {
3625 self.first_legal_span = Some(inject);
3626 }
3627 self.first_use_span = search_for_any_use_in_items(items);
3628 }
3629 } else {
3630 visit::walk_item(self, item);
3631 }
3632 }
3633}
3634
3635#[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)]
3636struct BindingVisitor {
3637 identifiers: Vec<Symbol>,
3638 spans: FxHashMap<Symbol, Vec<Span>>,
3639}
3640
3641impl<'tcx> Visitor<'tcx> for BindingVisitor {
3642 fn visit_pat(&mut self, pat: &ast::Pat) {
3643 if let ast::PatKind::Ident(_, ident, _) = pat.kind {
3644 self.identifiers.push(ident.name);
3645 self.spans.entry(ident.name).or_default().push(ident.span);
3646 }
3647 visit::walk_pat(self, pat);
3648 }
3649}
3650
3651fn search_for_any_use_in_items(items: &[Box<ast::Item>]) -> Option<Span> {
3652 for item in items {
3653 if let ItemKind::Use(..) = item.kind
3654 && is_span_suitable_for_use_injection(item.span)
3655 {
3656 let mut lo = item.span.lo();
3657 for attr in &item.attrs {
3658 if attr.span.eq_ctxt(item.span) {
3659 lo = std::cmp::min(lo, attr.span.lo());
3660 }
3661 }
3662 return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
3663 }
3664 }
3665 None
3666}
3667
3668fn is_span_suitable_for_use_injection(s: Span) -> bool {
3669 !s.from_expansion()
3672}