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