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