1use std::mem;
3use std::ops::ControlFlow;
4
5use itertools::Itertools as _;
6use rustc_ast::visit::{self, Visitor};
7use rustc_ast::{
8 self as ast, CRATE_NODE_ID, Crate, DUMMY_NODE_ID, ItemKind, ModKind, NodeId, Path,
9 join_path_idents,
10};
11use rustc_ast_pretty::pprust;
12use rustc_attr_parsing::AttributeParser;
13use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14use rustc_data_structures::unord::{UnordMap, UnordSet};
15use rustc_errors::codes::*;
16use rustc_errors::{
17 Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, MultiSpan, SuggestionStyle,
18 pluralize, struct_span_code_err,
19};
20use rustc_feature::BUILTIN_ATTRIBUTES;
21use rustc_hir::attrs::diagnostic::{CustomDiagnostic, Directive, FormatArgs};
22use rustc_hir::attrs::{AttributeKind, CfgEntry, StrippedCfgItem};
23use rustc_hir::def::Namespace::{self, *};
24use rustc_hir::def::{CtorKind, CtorOf, DefKind, MacroKinds, NonMacroAttrKind, PerNS};
25use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
26use rustc_hir::{Attribute, PrimTy, Stability, StabilityLevel, find_attr};
27use rustc_middle::bug;
28use rustc_middle::ty::{TyCtxt, Visibility};
29use rustc_session::Session;
30use rustc_session::lint::builtin::{
31 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS, AMBIGUOUS_IMPORT_VISIBILITIES,
32 AMBIGUOUS_PANIC_IMPORTS, MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
33};
34use rustc_session::utils::was_invoked_from_cargo;
35use rustc_span::edit_distance::find_best_match_for_name;
36use rustc_span::edition::Edition;
37use rustc_span::hygiene::MacroKind;
38use rustc_span::source_map::SourceMap;
39use rustc_span::{
40 BytePos, Ident, RemapPathScopeComponents, Span, Spanned, Symbol, SyntaxContext, kw, sym,
41};
42use thin_vec::{ThinVec, thin_vec};
43use tracing::{debug, instrument};
44
45use crate::diagnostics::{
46 self, AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion, ConsiderAddingADerive,
47 ExplicitUnsafeTraits, MacroDefinedLater, MacroRulesNot, MacroSuggMovePosition,
48 MaybeMissingMacroRulesName,
49};
50use crate::hygiene::Macros20NormalizedSyntaxContext;
51use crate::imports::{Import, ImportKind, UnresolvedImportError, import_path_to_string};
52use crate::late::{DiagMetadata, PatternSource, Rib};
53use crate::{
54 AmbiguityError, AmbiguityKind, AmbiguityWarning, BindingError, BindingKey, Decl, DeclKind,
55 DelayedVisResolutionError, Finalize, ForwardGenericParamBanReason, HasGenericParams, IdentKey,
56 LateDecl, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult,
57 PrivacyError, Res, ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used,
58 VisResolutionError, path_names_to_string,
59};
60
61pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
63
64pub(crate) type LabelSuggestion = (Ident, bool);
67
68#[derive(#[automatically_derived]
impl ::core::clone::Clone for StructCtor {
#[inline]
fn clone(&self) -> StructCtor {
StructCtor {
res: ::core::clone::Clone::clone(&self.res),
vis: ::core::clone::Clone::clone(&self.vis),
field_visibilities: ::core::clone::Clone::clone(&self.field_visibilities),
}
}
}Clone)]
69pub(crate) struct StructCtor {
70 pub res: Res,
71 pub vis: Visibility<DefId>,
72 pub field_visibilities: Vec<Visibility<DefId>>,
73}
74
75impl StructCtor {
76 pub(crate) fn has_private_fields<'ra>(&self, m: Module<'ra>, r: &Resolver<'ra, '_>) -> bool {
77 self.field_visibilities.iter().any(|&vis| !r.is_accessible_from(vis, m))
78 }
79}
80
81#[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)]
82pub(crate) enum SuggestionTarget {
83 SimilarlyNamed,
85 SingleItem,
87}
88
89#[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)]
90pub(crate) struct TypoSuggestion {
91 pub candidate: Symbol,
92 pub span: Option<Span>,
95 pub res: Res,
96 pub target: SuggestionTarget,
97}
98
99impl TypoSuggestion {
100 pub(crate) fn new(candidate: Symbol, span: Span, res: Res) -> TypoSuggestion {
101 Self { candidate, span: Some(span), res, target: SuggestionTarget::SimilarlyNamed }
102 }
103 pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
104 Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
105 }
106 pub(crate) fn single_item(candidate: Symbol, span: Span, res: Res) -> TypoSuggestion {
107 Self { candidate, span: Some(span), res, target: SuggestionTarget::SingleItem }
108 }
109}
110
111#[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)]
113pub(crate) struct ImportSuggestion {
114 pub did: Option<DefId>,
115 pub descr: &'static str,
116 pub path: Path,
117 pub accessible: bool,
118 pub doc_visible: bool,
120 pub via_import: bool,
121 pub note: Option<String>,
123 pub is_stable: bool,
124}
125
126fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
134 let impl_span = sm.span_until_char(impl_span, '<');
135 sm.span_until_whitespace(impl_span)
136}
137
138impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
139 pub(crate) fn throw_unresolved_import_error(
144 &mut self,
145 mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
146 glob_error: bool,
147 ) {
148 errors.retain(|(_import, err)| match err.module {
149 Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
151 _ => err.segment.map(|s| s.name) != Some(kw::Underscore),
154 });
155 if errors.is_empty() {
156 self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
157 return;
158 }
159
160 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
161
162 let paths = errors
163 .iter()
164 .map(|(import, err)| {
165 let path = import_path_to_string(
166 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
167 &import.kind,
168 err.span,
169 );
170 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", path))
})format!("`{path}`")
171 })
172 .collect::<Vec<_>>();
173 let default_message =
174 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unresolved import{0} {1}",
if paths.len() == 1 { "" } else { "s" }, paths.join(", ")))
})format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
175
176 let (mut message, label, mut notes) =
181 if let Some(directive) = errors[0].1.on_unknown_attr.as_ref().map(|a| &a.directive) {
182 let this = errors
183 .iter()
184 .map(|(_import, err)| {
185 err.segment.map(|s| s.name).unwrap_or(kw::Underscore)
187 })
188 .join(", ");
189
190 let args = FormatArgs { unresolved: this.clone(), this, .. };
191
192 let CustomDiagnostic { message, label, notes, parent_label: _dead } =
193 directive.eval(None, &args);
194
195 (message, label, notes)
196 } else {
197 (None, None, Vec::new())
198 };
199
200 let mut mod_diagnostics: Vec<CustomDiagnostic> = errors
204 .iter()
205 .map(|(import, import_error)| {
206 if let Some(ModuleOrUniformRoot::Module(module_data)) = import.imported_module.get()
207 && let ModuleKind::Def(DefKind::Mod, def_id, _, name) = module_data.kind
208 {
209 let Some(directive) = self.on_unknown_data(def_id) else {
210 return CustomDiagnostic::default();
211 };
212
213 let this = if let Some(name) = name {
214 name.to_string()
215 } else if let Some(crate_name) = &self.tcx.sess.opts.crate_name {
216 crate_name.to_string()
217 } else {
218 "<unnamed crate>".to_string()
219 };
220 let unresolved = import_error.segment.map(|s| s.name).unwrap_or(kw::Underscore);
221 let args = FormatArgs { this, unresolved: unresolved.to_string(), .. };
222
223 directive.eval(None, &args)
224 } else {
225 CustomDiagnostic::default()
226 }
227 })
228 .collect();
229
230 let mod_message =
233 mod_diagnostics.iter_mut().flat_map(|d| d.message.take()).all_equal_value();
234 if message.is_none()
235 && let Ok(mod_msg) = mod_message
236 {
237 message = Some(mod_msg);
238 }
239
240 let mut diag = if let Some(message) = message {
241 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", message))
})).with_code(E0432)
}struct_span_code_err!(self.dcx(), span, E0432, "{message}").with_note(default_message)
242 } else {
243 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", default_message))
})).with_code(E0432)
}struct_span_code_err!(self.dcx(), span, E0432, "{default_message}")
244 };
245
246 for mod_diag in mod_diagnostics.iter_mut() {
247 for mod_note in mod_diag.notes.drain(..) {
248 if !notes.contains(&mod_note) {
249 notes.push(mod_note);
250 }
251 }
252 }
253
254 if !notes.is_empty() {
255 for note in notes {
256 diag.note(note);
257 }
258 } else if let Some((_, UnresolvedImportError { note: Some(note), .. })) =
259 errors.iter().last()
260 {
261 diag.note(note.clone());
262 }
263
264 const MAX_LABEL_COUNT: usize = 10;
266 let mod_labels = mod_diagnostics.into_iter().map(|cd| cd.label);
267
268 for ((import, err), mod_label) in errors.into_iter().zip(mod_labels).take(MAX_LABEL_COUNT) {
269 let label_span = match err.segment {
270 Some(segment) => segment.span,
271 None => err.span,
272 };
273 if let Some(label) = &label {
274 diag.span_label(label_span, label.clone());
275 } else if let Some(label) = mod_label {
276 diag.span_label(label_span, label);
277 } else if let Some(label) = &err.label {
278 diag.span_label(label_span, label.clone());
279 }
280
281 if let Some((suggestions, msg, applicability)) = err.suggestion {
282 if suggestions.is_empty() {
283 diag.help(msg);
284 continue;
285 }
286 diag.multipart_suggestion(msg, suggestions, applicability);
287 }
288
289 if let Some(candidates) = &err.candidates {
290 match &import.kind {
291 ImportKind::Single { nested: false, source, target, .. } => import_candidates(
292 self.tcx,
293 &mut diag,
294 Some(err.span),
295 candidates,
296 DiagMode::Import { append: false, unresolved_import: true },
297 (source != target)
298 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
299 .as_deref()
300 .unwrap_or(""),
301 ),
302 ImportKind::Single { nested: true, source, target, .. } => {
303 import_candidates(
304 self.tcx,
305 &mut diag,
306 None,
307 candidates,
308 DiagMode::Normal,
309 (source != target)
310 .then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", target))
})format!(" as {target}"))
311 .as_deref()
312 .unwrap_or(""),
313 );
314 }
315 _ => {}
316 }
317 }
318
319 if #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::Single { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::Single { .. })
320 && let Some(segment) = err.segment
321 && let Some(module) = err.module
322 {
323 self.find_cfg_stripped(&mut diag, &segment.name, module)
324 }
325 }
326
327 let guar = diag.emit();
328 if glob_error {
329 self.glob_error = Some(guar);
330 }
331 }
332
333 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
334 self.tcx.dcx()
335 }
336
337 pub(crate) fn report_errors(&mut self, krate: &Crate) {
338 self.report_delayed_vis_resolution_errors();
339 self.report_with_use_injections(krate);
340
341 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
342 self.lint_buffer.buffer_lint(
343 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
344 CRATE_NODE_ID,
345 span_use,
346 diagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths {
347 definition: span_def,
348 },
349 );
350 }
351
352 for ambiguity_error in &self.ambiguity_errors {
353 let mut diag = self.ambiguity_diagnostic(ambiguity_error);
354
355 if let Some(ambiguity_warning) = ambiguity_error.warning {
356 let node_id = match ambiguity_error.b1.0.kind {
357 DeclKind::Import { import, .. } => import.root_id,
358 DeclKind::Def(_) => CRATE_NODE_ID,
359 };
360
361 let lint = match ambiguity_warning {
362 _ if ambiguity_error.ambig_vis.is_some() => AMBIGUOUS_IMPORT_VISIBILITIES,
363 AmbiguityWarning::GlobImport => AMBIGUOUS_GLOB_IMPORTS,
364 AmbiguityWarning::PanicImport => AMBIGUOUS_PANIC_IMPORTS,
365 };
366
367 self.lint_buffer.buffer_lint(lint, node_id, diag.ident.span, diag);
368 } else {
369 diag.is_error = true;
370 self.dcx().emit_err(diag);
371 }
372 }
373
374 let mut reported_spans = FxHashSet::default();
375 for error in mem::take(&mut self.privacy_errors) {
376 if reported_spans.insert(error.dedup_span) {
377 self.report_privacy_error(&error);
378 }
379 }
380 }
381
382 fn report_delayed_vis_resolution_errors(&mut self) {
383 for DelayedVisResolutionError { vis, parent_scope, error } in
384 mem::take(&mut self.delayed_vis_resolution_errors)
385 {
386 match self.try_resolve_visibility(&parent_scope, &vis, true) {
387 Ok(_) => self.report_vis_error(error),
388 Err(error) => self.report_vis_error(error),
389 };
390 }
391 }
392
393 fn report_with_use_injections(&mut self, krate: &Crate) {
394 for UseError { mut err, candidates, node_id, instead, suggestion, path, is_call } in
395 mem::take(&mut self.use_injections)
396 {
397 let (span, found_use) = if node_id != DUMMY_NODE_ID {
398 UsePlacementFinder::check(krate, node_id)
399 } else {
400 (None, FoundUse::No)
401 };
402
403 if !candidates.is_empty() {
404 show_candidates(
405 self.tcx,
406 &mut err,
407 span,
408 &candidates,
409 if instead { Instead::Yes } else { Instead::No },
410 found_use,
411 DiagMode::Normal,
412 path,
413 "",
414 );
415 err.emit();
416 } else if let Some((span, msg, sugg, appl)) = suggestion {
417 err.span_suggestion_verbose(span, msg, sugg, appl);
418 err.emit();
419 } else if let [segment] = path.as_slice()
420 && is_call
421 {
422 err.stash(segment.ident.span, rustc_errors::StashKey::CallIntoMethod);
423 } else {
424 err.emit();
425 }
426 }
427 }
428
429 pub(crate) fn report_conflict(
430 &mut self,
431 ident: IdentKey,
432 ns: Namespace,
433 old_binding: Decl<'ra>,
434 new_binding: Decl<'ra>,
435 ) {
436 if old_binding.span.lo() > new_binding.span.lo() {
438 return self.report_conflict(ident, ns, new_binding, old_binding);
439 }
440
441 let container = match old_binding.parent_module.unwrap().expect_local().kind {
442 ModuleKind::Def(kind, def_id, _, _) => kind.descr(def_id),
445 ModuleKind::Block => "block",
446 };
447
448 let (name, span) =
449 (ident.name, self.tcx.sess.source_map().guess_head_span(new_binding.span));
450
451 if self.name_already_seen.get(&name) == Some(&span) {
452 return;
453 }
454
455 let old_kind = match (ns, old_binding.res()) {
456 (ValueNS, _) => "value",
457 (MacroNS, _) => "macro",
458 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
459 (TypeNS, Res::Def(DefKind::Mod, _)) => "module",
460 (TypeNS, Res::Def(DefKind::Trait, _)) => "trait",
461 (TypeNS, _) => "type",
462 };
463
464 let code = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
465 (true, true) => E0259,
466 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
467 true => E0254,
468 false => E0260,
469 },
470 _ => match (old_binding.is_import_user_facing(), new_binding.is_import_user_facing()) {
471 (false, false) => E0428,
472 (true, true) => E0252,
473 _ => E0255,
474 },
475 };
476
477 let label = match new_binding.is_import_user_facing() {
478 true => diagnostics::NameDefinedMultipleTimeLabel::Reimported { span, name },
479 false => diagnostics::NameDefinedMultipleTimeLabel::Redefined { span, name },
480 };
481
482 let old_binding_label =
483 (!old_binding.span.is_dummy() && old_binding.span != span).then(|| {
484 let span = self.tcx.sess.source_map().guess_head_span(old_binding.span);
485 match old_binding.is_import_user_facing() {
486 true => diagnostics::NameDefinedMultipleTimeOldBindingLabel::Import {
487 span,
488 old_kind,
489 name,
490 },
491 false => diagnostics::NameDefinedMultipleTimeOldBindingLabel::Definition {
492 span,
493 old_kind,
494 name,
495 },
496 }
497 });
498
499 let mut err = self
500 .dcx()
501 .create_err(diagnostics::NameDefinedMultipleTime {
502 span,
503 name,
504 descr: ns.descr(),
505 container,
506 label,
507 old_binding_label,
508 })
509 .with_code(code);
510
511 use DeclKind::Import;
513 let can_suggest = |binding: Decl<'_>, import: self::Import<'_>| {
514 !binding.span.is_dummy()
515 && !#[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::MacroUse { .. } | ImportKind::MacroExport => true,
_ => false,
}matches!(import.kind, ImportKind::MacroUse { .. } | ImportKind::MacroExport)
516 };
517 let import = match (&new_binding.kind, &old_binding.kind) {
518 (Import { import: new, .. }, Import { import: old, .. })
521 if {
522 (new.has_attributes || old.has_attributes)
523 && can_suggest(old_binding, *old)
524 && can_suggest(new_binding, *new)
525 } =>
526 {
527 if old.has_attributes {
528 Some((*new, new_binding.span, true))
529 } else {
530 Some((*old, old_binding.span, true))
531 }
532 }
533 (Import { import, .. }, other) if can_suggest(new_binding, *import) => {
535 Some((*import, new_binding.span, other.is_import()))
536 }
537 (other, Import { import, .. }) if can_suggest(old_binding, *import) => {
538 Some((*import, old_binding.span, other.is_import()))
539 }
540 _ => None,
541 };
542
543 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
545 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
546 let from_item =
547 self.extern_prelude.get(&ident).is_none_or(|entry| entry.introduced_by_item());
548 let should_remove_import = duplicate
552 && !has_dummy_span
553 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
554
555 match import {
556 Some((import, span, true)) if should_remove_import && import.is_nested() => {
557 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span);
558 }
559 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
560 err.subdiagnostic(diagnostics::ToolOnlyRemoveUnnecessaryImport {
563 span: import.use_span_with_attributes,
564 });
565 }
566 Some((import, span, _)) => {
567 self.add_suggestion_for_rename_of_use(&mut err, name, import, span);
568 }
569 _ => {}
570 }
571
572 err.emit();
573 self.name_already_seen.insert(name, span);
574 }
575
576 fn add_suggestion_for_rename_of_use(
586 &self,
587 err: &mut Diag<'_>,
588 name: Symbol,
589 import: Import<'_>,
590 binding_span: Span,
591 ) {
592 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
593 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Other{0}", name))
})format!("Other{name}")
594 } else {
595 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("other_{0}", name))
})format!("other_{name}")
596 };
597
598 let mut suggestion = None;
599 let mut span = binding_span;
600 match import.kind {
601 ImportKind::Single { source, .. } => {
602 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
603 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(binding_span)
604 && pos as usize <= snippet.len()
605 {
606 span = binding_span.with_lo(binding_span.lo() + BytePos(pos)).with_hi(
607 binding_span.hi() - BytePos(if snippet.ends_with(';') { 1 } else { 0 }),
608 );
609 suggestion = Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}", suggested_name))
})format!(" as {suggested_name}"));
610 }
611 }
612 ImportKind::ExternCrate { source, target, .. } => {
613 suggestion = Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern crate {0} as {1};",
source.unwrap_or(target.name), suggested_name))
})format!(
614 "extern crate {} as {};",
615 source.unwrap_or(target.name),
616 suggested_name,
617 ))
618 }
619 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
620 }
621
622 if let Some(suggestion) = suggestion {
623 err.subdiagnostic(ChangeImportBindingSuggestion { span, suggestion });
624 } else {
625 err.subdiagnostic(ChangeImportBinding { span });
626 }
627 }
628
629 fn add_suggestion_for_duplicate_nested_use(
652 &self,
653 err: &mut Diag<'_>,
654 import: Import<'_>,
655 binding_span: Span,
656 ) {
657 if !import.is_nested() {
::core::panicking::panic("assertion failed: import.is_nested()")
};assert!(import.is_nested());
658
659 let (found_closing_brace, span) =
667 find_span_of_binding_until_next_binding(self.tcx.sess, binding_span, import.use_span);
668
669 if found_closing_brace {
672 if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) {
673 err.subdiagnostic(diagnostics::ToolOnlyRemoveUnnecessaryImport { span });
674 } else {
675 err.subdiagnostic(diagnostics::RemoveUnnecessaryImport {
678 span: import.use_span_with_attributes,
679 });
680 }
681
682 return;
683 }
684
685 err.subdiagnostic(diagnostics::RemoveUnnecessaryImport { span });
686 }
687
688 pub(crate) fn lint_if_path_starts_with_module(
689 &mut self,
690 finalize: Finalize,
691 path: &[Segment],
692 second_binding: Option<Decl<'_>>,
693 ) {
694 let Finalize { node_id, root_span, .. } = finalize;
695
696 let first_name = match path.get(0) {
697 Some(seg) if seg.ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015() => {
699 seg.ident.name
700 }
701 _ => return,
702 };
703
704 if first_name != kw::PathRoot {
707 return;
708 }
709
710 match path.get(1) {
711 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
713 Some(_) => {}
715 None => return,
719 }
720
721 if let Some(binding) = second_binding
725 && let DeclKind::Import { import, .. } = binding.kind
726 && let ImportKind::ExternCrate { source: None, .. } = import.kind
728 {
729 return;
730 }
731
732 self.lint_buffer.dyn_buffer_lint_any(
733 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
734 node_id,
735 root_span,
736 move |dcx, level, sess| {
737 let (replacement, applicability) = match sess
738 .downcast_ref::<Session>()
739 .expect("expected a `Session`")
740 .source_map()
741 .span_to_snippet(root_span)
742 {
743 Ok(ref s) => {
744 let opt_colon = if s.trim_start().starts_with("::") { "" } else { "::" };
747
748 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}{1}", opt_colon, s))
})format!("crate{opt_colon}{s}"), Applicability::MachineApplicable)
749 }
750 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
751 };
752 diagnostics::AbsPathWithModule {
753 sugg: diagnostics::AbsPathWithModuleSugg {
754 span: root_span,
755 applicability,
756 replacement,
757 },
758 }
759 .into_diag(dcx, level)
760 },
761 );
762 }
763
764 pub(crate) fn add_module_candidates(
765 &self,
766 module: Module<'ra>,
767 names: &mut Vec<TypoSuggestion>,
768 filter_fn: &impl Fn(Res) -> bool,
769 ctxt: Option<SyntaxContext>,
770 ) {
771 module.for_each_child(self, |_this, ident, orig_ident_span, _ns, binding| {
772 let res = binding.res();
773 if filter_fn(res) && ctxt.is_none_or(|ctxt| ctxt == *ident.ctxt) {
774 names.push(TypoSuggestion::new(ident.name, orig_ident_span, res));
775 }
776 });
777 }
778
779 pub(crate) fn report_error(
784 &mut self,
785 span: Span,
786 resolution_error: ResolutionError<'ra>,
787 ) -> ErrorGuaranteed {
788 self.into_struct_error(span, resolution_error).emit()
789 }
790
791 pub(crate) fn into_struct_error(
792 &mut self,
793 span: Span,
794 resolution_error: ResolutionError<'ra>,
795 ) -> Diag<'_> {
796 match resolution_error {
797 ResolutionError::GenericParamsFromOuterItem {
798 outer_res,
799 has_generic_params,
800 def_kind,
801 inner_item,
802 current_self_ty,
803 } => {
804 use diagnostics::GenericParamsFromOuterItemLabel as Label;
805 let static_or_const = match def_kind {
806 DefKind::Static { .. } => {
807 Some(diagnostics::GenericParamsFromOuterItemStaticOrConst::Static)
808 }
809 DefKind::Const { .. } => {
810 Some(diagnostics::GenericParamsFromOuterItemStaticOrConst::Const)
811 }
812 _ => None,
813 };
814 let is_self =
815 #[allow(non_exhaustive_omitted_patterns)] match outer_res {
Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => true,
_ => false,
}matches!(outer_res, Res::SelfTyParam { .. } | Res::SelfTyAlias { .. });
816 let mut err = diagnostics::GenericParamsFromOuterItem {
817 span,
818 label: None,
819 refer_to_type_directly: None,
820 use_let: None,
821 sugg: None,
822 static_or_const,
823 is_self,
824 item: inner_item.as_ref().map(|(label_span, _, kind)| {
825 diagnostics::GenericParamsFromOuterItemInnerItem {
826 span: *label_span,
827 descr: kind.descr().to_string(),
828 is_self,
829 }
830 }),
831 };
832
833 let sm = self.tcx.sess.source_map();
834 let def_id = match outer_res {
837 Res::SelfTyParam { .. } => {
838 err.label = Some(Label::SelfTyParam(span));
839 None
840 }
841 Res::SelfTyAlias { alias_to: def_id, .. } => {
842 err.label = Some(Label::SelfTyAlias(reduce_impl_span_to_impl_keyword(
843 sm,
844 self.def_span(def_id),
845 )));
846 err.refer_to_type_directly = current_self_ty
847 .map(|snippet| diagnostics::UseTypeDirectly { span, snippet });
848 None
849 }
850 Res::Def(DefKind::TyParam, def_id) => {
851 err.label = Some(Label::TyParam(self.def_span(def_id)));
852 Some(def_id)
853 }
854 Res::Def(DefKind::ConstParam, def_id) => {
855 err.label = Some(Label::ConstParam(self.def_span(def_id)));
856 Some(def_id)
857 }
858 _ => {
859 ::rustc_middle::util::bug::bug_fmt(format_args!("GenericParamsFromOuterItem should only be used with Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or DefKind::ConstParam"));bug!(
860 "GenericParamsFromOuterItem should only be used with \
861 Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
862 DefKind::ConstParam"
863 );
864 }
865 };
866
867 if let Some((_, item_span, ItemKind::Const(_))) = inner_item.as_ref() {
868 err.use_let = Some(diagnostics::GenericParamsFromOuterItemUseLet {
869 span: sm.span_until_whitespace(*item_span),
870 });
871 }
872
873 if let Some(def_id) = def_id
874 && let HasGenericParams::Yes(span) = has_generic_params
875 && !#[allow(non_exhaustive_omitted_patterns)] match inner_item {
Some((_, _, ItemKind::Delegation(..))) => true,
_ => false,
}matches!(inner_item, Some((_, _, ItemKind::Delegation(..))))
876 {
877 let name = self.tcx.item_name(def_id);
878 let (span, snippet) = if span.is_empty() {
879 let snippet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", name))
})format!("<{name}>");
880 (span, snippet)
881 } else {
882 let span = sm.span_through_char(span, '<').shrink_to_hi();
883 let snippet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", name))
})format!("{name}, ");
884 (span, snippet)
885 };
886 err.sugg = Some(diagnostics::GenericParamsFromOuterItemSugg { span, snippet });
887 }
888
889 self.dcx().create_err(err)
890 }
891 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
892 self.dcx().create_err(diagnostics::NameAlreadyUsedInParameterList {
893 span,
894 first_use_span,
895 name,
896 })
897 }
898 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
899 self.dcx().create_err(diagnostics::MethodNotMemberOfTrait {
900 span,
901 method,
902 trait_,
903 sub: candidate.map(|c| diagnostics::AssociatedFnWithSimilarNameExists {
904 span: method.span,
905 candidate: c,
906 }),
907 })
908 }
909 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
910 self.dcx().create_err(diagnostics::TypeNotMemberOfTrait {
911 span,
912 type_,
913 trait_,
914 sub: candidate.map(|c| diagnostics::AssociatedTypeWithSimilarNameExists {
915 span: type_.span,
916 candidate: c,
917 }),
918 })
919 }
920 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
921 self.dcx().create_err(diagnostics::ConstNotMemberOfTrait {
922 span,
923 const_,
924 trait_,
925 sub: candidate.map(|c| diagnostics::AssociatedConstWithSimilarNameExists {
926 span: const_.span,
927 candidate: c,
928 }),
929 })
930 }
931 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
932 let BindingError { name, target, origin, could_be_path } = binding_error;
933
934 let mut target_sp = target.iter().map(|pat| pat.span).collect::<Vec<_>>();
935 target_sp.sort();
936 target_sp.dedup();
937 let mut origin_sp = origin.iter().map(|(span, _)| *span).collect::<Vec<_>>();
938 origin_sp.sort();
939 origin_sp.dedup();
940
941 let msp = MultiSpan::from_spans(target_sp.clone());
942 let mut err = self.dcx().create_err(diagnostics::VariableIsNotBoundInAllPatterns {
943 multispan: msp,
944 name,
945 });
946 for sp in target_sp {
947 err.subdiagnostic(diagnostics::PatternDoesntBindName { span: sp, name });
948 }
949 for sp in &origin_sp {
950 err.subdiagnostic(diagnostics::VariableNotInAllPatterns { span: *sp });
951 }
952 let mut suggested_typo = false;
953 if !target.iter().all(|pat| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
ast::PatKind::Ident(..) => true,
_ => false,
}matches!(pat.kind, ast::PatKind::Ident(..)))
954 && !origin.iter().all(|(_, pat)| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
ast::PatKind::Ident(..) => true,
_ => false,
}matches!(pat.kind, ast::PatKind::Ident(..)))
955 {
956 let mut target_visitor = BindingVisitor::default();
959 for pat in &target {
960 target_visitor.visit_pat(pat);
961 }
962 target_visitor.identifiers.sort();
963 target_visitor.identifiers.dedup();
964 let mut origin_visitor = BindingVisitor::default();
965 for (_, pat) in &origin {
966 origin_visitor.visit_pat(pat);
967 }
968 origin_visitor.identifiers.sort();
969 origin_visitor.identifiers.dedup();
970 if let Some(typo) =
972 find_best_match_for_name(&target_visitor.identifiers, name.name, None)
973 && !origin_visitor.identifiers.contains(&typo)
974 {
975 err.subdiagnostic(diagnostics::PatternBindingTypo {
976 spans: origin_sp,
977 typo,
978 });
979 suggested_typo = true;
980 }
981 }
982 if could_be_path {
983 let import_suggestions = self.lookup_import_candidates(
984 name,
985 Namespace::ValueNS,
986 &parent_scope,
987 &|res: Res| {
988 #[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!(
989 res,
990 Res::Def(
991 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
992 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
993 | DefKind::Const { .. }
994 | DefKind::AssocConst { .. },
995 _,
996 )
997 )
998 },
999 );
1000
1001 if import_suggestions.is_empty() && !suggested_typo {
1002 let kind_matches: [fn(DefKind) -> bool; 4] = [
1003 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => true,
_ => false,
}matches!(kind, DefKind::Ctor(CtorOf::Variant, CtorKind::Const)),
1004 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => true,
_ => false,
}matches!(kind, DefKind::Ctor(CtorOf::Struct, CtorKind::Const)),
1005 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Const { .. } => true,
_ => false,
}matches!(kind, DefKind::Const { .. }),
1006 |kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::AssocConst { .. } => true,
_ => false,
}matches!(kind, DefKind::AssocConst { .. }),
1007 ];
1008 let mut local_names = ::alloc::vec::Vec::new()vec![];
1009 self.add_module_candidates(
1010 parent_scope.module,
1011 &mut local_names,
1012 &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(_, _) => true,
_ => false,
}matches!(res, Res::Def(_, _)),
1013 None,
1014 );
1015 let local_names: FxHashSet<_> = local_names
1016 .into_iter()
1017 .filter_map(|s| match s.res {
1018 Res::Def(_, def_id) => Some(def_id),
1019 _ => None,
1020 })
1021 .collect();
1022
1023 let mut local_suggestions = ::alloc::vec::Vec::new()vec![];
1024 let mut suggestions = ::alloc::vec::Vec::new()vec![];
1025 for matches_kind in kind_matches {
1026 if let Some(suggestion) = self.early_lookup_typo_candidate(
1027 ScopeSet::All(Namespace::ValueNS),
1028 &parent_scope,
1029 name,
1030 &|res: Res| match res {
1031 Res::Def(k, _) => matches_kind(k),
1032 _ => false,
1033 },
1034 ) && let Res::Def(kind, mut def_id) = suggestion.res
1035 {
1036 if let DefKind::Ctor(_, _) = kind {
1037 def_id = self.tcx.parent(def_id);
1038 }
1039 let kind = kind.descr(def_id);
1040 if local_names.contains(&def_id) {
1041 local_suggestions.push((
1044 suggestion.candidate,
1045 suggestion.candidate.to_string(),
1046 kind,
1047 ));
1048 } else {
1049 suggestions.push((
1050 suggestion.candidate,
1051 self.def_path_str(def_id),
1052 kind,
1053 ));
1054 }
1055 }
1056 }
1057 let suggestions = if !local_suggestions.is_empty() {
1058 local_suggestions
1061 } else {
1062 suggestions
1063 };
1064 for (name, sugg, kind) in suggestions {
1065 err.span_suggestion_verbose(
1066 span,
1067 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use the similarly named {0} `{1}`",
kind, name))
})format!(
1068 "you might have meant to use the similarly named {kind} `{name}`",
1069 ),
1070 sugg,
1071 Applicability::MaybeIncorrect,
1072 );
1073 suggested_typo = true;
1074 }
1075 }
1076 if import_suggestions.is_empty() && !suggested_typo {
1077 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!(
1078 "if you meant to match on a unit struct, unit variant or a `const` \
1079 item, consider making the path in the pattern qualified: \
1080 `path::to::ModOrType::{name}`",
1081 );
1082 err.span_help(span, help_msg);
1083 }
1084 show_candidates(
1085 self.tcx,
1086 &mut err,
1087 Some(span),
1088 &import_suggestions,
1089 Instead::No,
1090 FoundUse::Yes,
1091 DiagMode::Pattern,
1092 ::alloc::vec::Vec::new()vec![],
1093 "",
1094 );
1095 }
1096 err
1097 }
1098 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
1099 self.dcx().create_err(diagnostics::VariableBoundWithDifferentMode {
1100 span,
1101 first_binding_span,
1102 variable_name,
1103 })
1104 }
1105 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
1106 self.dcx().create_err(diagnostics::IdentifierBoundMoreThanOnceInParameterList {
1107 span,
1108 identifier,
1109 })
1110 }
1111 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
1112 self.dcx().create_err(diagnostics::IdentifierBoundMoreThanOnceInSamePattern {
1113 span,
1114 identifier,
1115 })
1116 }
1117 ResolutionError::UndeclaredLabel { name, suggestion } => {
1118 let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
1119 {
1120 Some((ident, true)) => (
1122 (
1123 Some(diagnostics::LabelWithSimilarNameReachable(ident.span)),
1124 Some(diagnostics::TryUsingSimilarlyNamedLabel {
1125 span,
1126 ident_name: ident.name,
1127 }),
1128 ),
1129 None,
1130 ),
1131 Some((ident, false)) => (
1133 (None, None),
1134 Some(diagnostics::UnreachableLabelWithSimilarNameExists {
1135 ident_span: ident.span,
1136 }),
1137 ),
1138 None => ((None, None), None),
1140 };
1141 self.dcx().create_err(diagnostics::UndeclaredLabel {
1142 span,
1143 name,
1144 sub_reachable,
1145 sub_reachable_suggestion,
1146 sub_unreachable,
1147 })
1148 }
1149 ResolutionError::FailedToResolve { segment, label, suggestion, module, message } => {
1150 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", message))
})).with_code(E0433)
}struct_span_code_err!(self.dcx(), span, E0433, "{message}");
1151 err.span_label(span, label);
1152
1153 if let Some((suggestions, msg, applicability)) = suggestion {
1154 if suggestions.is_empty() {
1155 err.help(msg);
1156 return err;
1157 }
1158 err.multipart_suggestion(msg, suggestions, applicability);
1159 }
1160
1161 let module = match module {
1162 Some(ModuleOrUniformRoot::Module(m)) if let Some(id) = m.opt_def_id() => id,
1163 _ => CRATE_DEF_ID.to_def_id(),
1164 };
1165 self.find_cfg_stripped(&mut err, &segment, module);
1166
1167 err
1168 }
1169 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
1170 self.dcx().create_err(diagnostics::CannotCaptureDynamicEnvironmentInFnItem { span })
1171 }
1172 ResolutionError::AttemptToUseNonConstantValueInConstant {
1173 ident,
1174 suggestion,
1175 current,
1176 type_span,
1177 } => {
1178 let sp = self
1187 .tcx
1188 .sess
1189 .source_map()
1190 .span_extend_to_prev_str(ident.span, current, true, false);
1191
1192 let (with, with_label, without) = match sp {
1193 Some(sp) if !self.tcx.sess.source_map().is_multiline(sp) => {
1194 let sp = sp
1195 .with_lo(BytePos(sp.lo().0 - (current.len() as u32)))
1196 .until(ident.span);
1197
1198 let is_simple_binding =
1206 self.tcx.sess.source_map().span_to_snippet(sp).is_ok_and(|snippet| {
1207 let after_keyword = snippet[current.len()..].trim();
1208 after_keyword.is_empty() || after_keyword == "mut"
1209 });
1210
1211 if is_simple_binding {
1212 (
1213 Some(diagnostics::AttemptToUseNonConstantValueInConstantWithSuggestion {
1214 span: sp,
1215 suggestion,
1216 current,
1217 type_span,
1218 }),
1219 Some(diagnostics::AttemptToUseNonConstantValueInConstantLabelWithSuggestion { span }),
1220 None,
1221 )
1222 } else {
1223 (
1224 None,
1225 Some(diagnostics::AttemptToUseNonConstantValueInConstantLabelWithSuggestion { span }),
1226 None,
1227 )
1228 }
1229 }
1230 _ => (
1231 None,
1232 None,
1233 Some(
1234 diagnostics::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
1235 ident_span: ident.span,
1236 suggestion,
1237 },
1238 ),
1239 ),
1240 };
1241
1242 self.dcx().create_err(diagnostics::AttemptToUseNonConstantValueInConstant {
1243 span,
1244 with,
1245 with_label,
1246 without,
1247 })
1248 }
1249 ResolutionError::BindingShadowsSomethingUnacceptable {
1250 shadowing_binding,
1251 name,
1252 participle,
1253 article,
1254 shadowed_binding,
1255 shadowed_binding_span,
1256 } => self.dcx().create_err(diagnostics::BindingShadowsSomethingUnacceptable {
1257 span,
1258 shadowing_binding,
1259 shadowed_binding,
1260 article,
1261 sub_suggestion: match (shadowing_binding, shadowed_binding) {
1262 (
1263 PatternSource::Match,
1264 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
1265 ) => Some(diagnostics::BindingShadowsSomethingUnacceptableSuggestion {
1266 span,
1267 name,
1268 }),
1269 _ => None,
1270 },
1271 shadowed_binding_span,
1272 participle,
1273 name,
1274 }),
1275 ResolutionError::ForwardDeclaredGenericParam(param, reason) => match reason {
1276 ForwardGenericParamBanReason::Default => {
1277 self.dcx().create_err(diagnostics::ForwardDeclaredGenericParam { param, span })
1278 }
1279 ForwardGenericParamBanReason::ConstParamTy => self
1280 .dcx()
1281 .create_err(diagnostics::ForwardDeclaredGenericInConstParamTy { param, span }),
1282 },
1283 ResolutionError::ParamInTyOfConstParam { name } => {
1284 self.dcx().create_err(diagnostics::ParamInTyOfConstParam { span, name })
1285 }
1286 ResolutionError::ParamInNonTrivialAnonConst { is_gca, name, param_kind: is_type } => {
1287 self.dcx().create_err(diagnostics::ParamInNonTrivialAnonConst {
1288 span,
1289 name,
1290 param_kind: is_type,
1291 help: self.tcx.sess.is_nightly_build(),
1292 is_gca,
1293 help_gca: is_gca,
1294 })
1295 }
1296 ResolutionError::ParamInEnumDiscriminant { name, param_kind: is_type } => {
1297 self.dcx().create_err(diagnostics::ParamInEnumDiscriminant {
1298 span,
1299 name,
1300 param_kind: is_type,
1301 })
1302 }
1303 ResolutionError::ForwardDeclaredSelf(reason) => match reason {
1304 ForwardGenericParamBanReason::Default => {
1305 self.dcx().create_err(diagnostics::SelfInGenericParamDefault { span })
1306 }
1307 ForwardGenericParamBanReason::ConstParamTy => {
1308 self.dcx().create_err(diagnostics::SelfInConstGenericTy { span })
1309 }
1310 },
1311 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
1312 let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
1313 match suggestion {
1314 Some((ident, true)) => (
1316 (
1317 Some(diagnostics::UnreachableLabelSubLabel {
1318 ident_span: ident.span,
1319 }),
1320 Some(diagnostics::UnreachableLabelSubSuggestion {
1321 span,
1322 ident_name: ident.name,
1325 }),
1326 ),
1327 None,
1328 ),
1329 Some((ident, false)) => (
1331 (None, None),
1332 Some(diagnostics::UnreachableLabelSubLabelUnreachable {
1333 ident_span: ident.span,
1334 }),
1335 ),
1336 None => ((None, None), None),
1338 };
1339 self.dcx().create_err(diagnostics::UnreachableLabel {
1340 span,
1341 name,
1342 definition_span,
1343 sub_suggestion,
1344 sub_suggestion_label,
1345 sub_unreachable_label,
1346 })
1347 }
1348 ResolutionError::TraitImplMismatch {
1349 name,
1350 kind,
1351 code,
1352 trait_item_span,
1353 trait_path,
1354 } => self
1355 .dcx()
1356 .create_err(diagnostics::TraitImplMismatch {
1357 span,
1358 name,
1359 kind,
1360 trait_path,
1361 trait_item_span,
1362 })
1363 .with_code(code),
1364 ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => {
1365 self.dcx().create_err(diagnostics::TraitImplDuplicate {
1366 span,
1367 name,
1368 trait_item_span,
1369 old_span,
1370 })
1371 }
1372 ResolutionError::InvalidAsmSym => {
1373 self.dcx().create_err(diagnostics::InvalidAsmSym { span })
1374 }
1375 ResolutionError::LowercaseSelf => {
1376 self.dcx().create_err(diagnostics::LowercaseSelf { span })
1377 }
1378 ResolutionError::BindingInNeverPattern => {
1379 self.dcx().create_err(diagnostics::BindingInNeverPattern { span })
1380 }
1381 }
1382 }
1383
1384 pub(crate) fn report_vis_error(
1385 &mut self,
1386 vis_resolution_error: VisResolutionError,
1387 ) -> ErrorGuaranteed {
1388 match vis_resolution_error {
1389 VisResolutionError::Relative2018(span, path) => {
1390 self.dcx().create_err(diagnostics::Relative2018 {
1391 span,
1392 path_span: path.span,
1393 path_str: pprust::path_to_string(&path),
1396 })
1397 }
1398 VisResolutionError::AncestorOnly(span) => {
1399 self.dcx().create_err(diagnostics::AncestorOnly(span))
1400 }
1401 VisResolutionError::FailedToResolve(span, segment, label, suggestion, message) => self
1402 .into_struct_error(
1403 span,
1404 ResolutionError::FailedToResolve {
1405 segment,
1406 label,
1407 suggestion,
1408 module: None,
1409 message,
1410 },
1411 ),
1412 VisResolutionError::ExpectedFound(span, path_str, res) => {
1413 self.dcx().create_err(diagnostics::ExpectedModuleFound { span, res, path_str })
1414 }
1415 VisResolutionError::Indeterminate(span) => {
1416 self.dcx().create_err(diagnostics::Indeterminate(span))
1417 }
1418 VisResolutionError::ModuleOnly(span) => {
1419 self.dcx().create_err(diagnostics::ModuleOnly(span))
1420 }
1421 }
1422 .emit()
1423 }
1424
1425 pub(crate) fn def_path_str(&self, mut def_id: DefId) -> String {
1426 let mut path = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[def_id]))vec![def_id];
1428 while let Some(parent) = self.tcx.opt_parent(def_id) {
1429 def_id = parent;
1430 path.push(def_id);
1431 if def_id.is_top_level_module() {
1432 break;
1433 }
1434 }
1435 path.into_iter()
1437 .rev()
1438 .map(|def_id| {
1439 self.tcx
1440 .opt_item_name(def_id)
1441 .map(|name| {
1442 match (
1443 def_id.is_top_level_module(),
1444 def_id.is_local(),
1445 self.tcx.sess.edition(),
1446 ) {
1447 (true, true, Edition::Edition2015) => String::new(),
1448 (true, true, _) => kw::Crate.to_string(),
1449 (true, false, _) | (false, _, _) => name.to_string(),
1450 }
1451 })
1452 .unwrap_or_else(|| "_".to_string())
1453 })
1454 .collect::<Vec<String>>()
1455 .join("::")
1456 }
1457
1458 pub(crate) fn add_scope_set_candidates(
1459 &mut self,
1460 suggestions: &mut Vec<TypoSuggestion>,
1461 scope_set: ScopeSet<'ra>,
1462 ps: &ParentScope<'ra>,
1463 sp: Span,
1464 filter_fn: &impl Fn(Res) -> bool,
1465 ) {
1466 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
1467 self.cm().visit_scopes(scope_set, ps, ctxt, sp, None, |this, scope, use_prelude, _| {
1468 match scope {
1469 Scope::DeriveHelpers(expn_id) => {
1470 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1471 if filter_fn(res) {
1472 suggestions.extend(this.helper_attrs.get(&expn_id).into_flat_iter().map(
1473 |&(ident, orig_ident_span, _)| {
1474 TypoSuggestion::new(ident.name, orig_ident_span, res)
1475 },
1476 ));
1477 }
1478 }
1479 Scope::DeriveHelpersCompat => {
1480 }
1482 Scope::MacroRules(macro_rules_scope) => {
1483 if let MacroRulesScope::Def(macro_rules_def) = macro_rules_scope.get() {
1484 let res = macro_rules_def.decl.res();
1485 if filter_fn(res) {
1486 suggestions.push(TypoSuggestion::new(
1487 macro_rules_def.ident.name,
1488 macro_rules_def.orig_ident_span,
1489 res,
1490 ))
1491 }
1492 }
1493 }
1494 Scope::ModuleNonGlobs(module, _) => {
1495 this.add_module_candidates(module, suggestions, filter_fn, None);
1496 }
1497 Scope::ModuleGlobs(..) => {
1498 }
1500 Scope::MacroUsePrelude => {
1501 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1502 |(name, binding)| {
1503 let res = binding.res();
1504 filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1505 },
1506 ));
1507 }
1508 Scope::BuiltinAttrs => {
1509 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(sym::dummy));
1510 if filter_fn(res) {
1511 suggestions.extend(
1512 BUILTIN_ATTRIBUTES
1513 .iter()
1514 .filter(|attr| {
1517 !#[allow(non_exhaustive_omitted_patterns)] match **attr {
sym::cfg_trace | sym::cfg_attr_trace => true,
_ => false,
}matches!(**attr, sym::cfg_trace | sym::cfg_attr_trace)
1518 })
1519 .map(|attr| TypoSuggestion::typo_from_name(*attr, res)),
1520 );
1521 }
1522 }
1523 Scope::ExternPreludeItems => {
1524 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, entry)| {
1526 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1527 filter_fn(res).then_some(TypoSuggestion::new(ident.name, entry.span(), res))
1528 }));
1529 }
1530 Scope::ExternPreludeFlags => {}
1531 Scope::ToolPrelude => {
1532 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1533 suggestions.extend(
1534 this.registered_tools
1535 .iter()
1536 .map(|ident| TypoSuggestion::new(ident.name, ident.span, res)),
1537 );
1538 }
1539 Scope::StdLibPrelude => {
1540 if let Some(prelude) = this.prelude {
1541 let mut tmp_suggestions = Vec::new();
1542 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1543 suggestions.extend(
1544 tmp_suggestions
1545 .into_iter()
1546 .filter(|s| use_prelude.into() || this.is_builtin_macro(s.res)),
1547 );
1548 }
1549 }
1550 Scope::BuiltinTypes => {
1551 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1552 let res = Res::PrimTy(*prim_ty);
1553 filter_fn(res)
1554 .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1555 }))
1556 }
1557 }
1558
1559 ControlFlow::<()>::Continue(())
1560 });
1561 }
1562
1563 fn early_lookup_typo_candidate(
1565 &mut self,
1566 scope_set: ScopeSet<'ra>,
1567 parent_scope: &ParentScope<'ra>,
1568 ident: Ident,
1569 filter_fn: &impl Fn(Res) -> bool,
1570 ) -> Option<TypoSuggestion> {
1571 let mut suggestions = Vec::new();
1572 self.add_scope_set_candidates(
1573 &mut suggestions,
1574 scope_set,
1575 parent_scope,
1576 ident.span,
1577 filter_fn,
1578 );
1579
1580 suggestions.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
1582
1583 match find_best_match_for_name(
1584 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1585 ident.name,
1586 None,
1587 ) {
1588 Some(found) if found != ident.name => {
1589 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1590 }
1591 _ => None,
1592 }
1593 }
1594
1595 fn lookup_import_candidates_from_module<FilterFn>(
1596 &self,
1597 lookup_ident: Ident,
1598 namespace: Namespace,
1599 parent_scope: &ParentScope<'ra>,
1600 start_module: Module<'ra>,
1601 crate_path: ThinVec<ast::PathSegment>,
1602 filter_fn: FilterFn,
1603 ) -> Vec<ImportSuggestion>
1604 where
1605 FilterFn: Fn(Res) -> bool,
1606 {
1607 let mut candidates = Vec::new();
1608 let mut seen_modules = FxHashSet::default();
1609 let start_did = start_module.def_id();
1610 let mut worklist = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(start_module, ThinVec::<ast::PathSegment>::new(), true,
start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
true)]))vec![(
1611 start_module,
1612 ThinVec::<ast::PathSegment>::new(),
1613 true,
1614 start_did.is_local() || !self.tcx.is_doc_hidden(start_did),
1615 true,
1616 )];
1617 let mut worklist_via_import = ::alloc::vec::Vec::new()vec![];
1618
1619 while let Some((in_module, path_segments, accessible, doc_visible, is_stable)) =
1620 match worklist.pop() {
1621 None => worklist_via_import.pop(),
1622 Some(x) => Some(x),
1623 }
1624 {
1625 let in_module_is_extern = !in_module.def_id().is_local();
1626 in_module.for_each_child(self, |this, ident, orig_ident_span, ns, name_binding| {
1627 if name_binding.is_assoc_item()
1629 && !this.features.import_trait_associated_functions()
1630 {
1631 return;
1632 }
1633
1634 if ident.name == kw::Underscore {
1635 return;
1636 }
1637
1638 let child_accessible =
1639 accessible && this.is_accessible_from(name_binding.vis(), parent_scope.module);
1640
1641 if in_module_is_extern && !child_accessible {
1643 return;
1644 }
1645
1646 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1647
1648 if via_import && name_binding.is_possibly_imported_variant() {
1654 return;
1655 }
1656
1657 if let DeclKind::Import { source_decl, .. } = name_binding.kind
1659 && this.is_accessible_from(source_decl.vis(), parent_scope.module)
1660 && !this.is_accessible_from(name_binding.vis(), parent_scope.module)
1661 {
1662 return;
1663 }
1664
1665 let res = name_binding.res();
1666 let did = match res {
1667 Res::Def(DefKind::Ctor(..), did) => this.tcx.opt_parent(did),
1668 _ => res.opt_def_id(),
1669 };
1670 let child_doc_visible = doc_visible
1671 && did.is_none_or(|did| did.is_local() || !this.tcx.is_doc_hidden(did));
1672
1673 if ident.name == lookup_ident.name
1677 && ns == namespace
1678 && in_module != parent_scope.module
1679 && ident.ctxt.is_root()
1680 && filter_fn(res)
1681 {
1682 let mut segms = if lookup_ident.span.at_least_rust_2018() {
1684 crate_path.clone()
1687 } else {
1688 ThinVec::new()
1689 };
1690 segms.append(&mut path_segments.clone());
1691
1692 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
1693 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1694
1695 if child_accessible
1696 && let Some(idx) = candidates
1698 .iter()
1699 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1700 {
1701 candidates.remove(idx);
1702 }
1703
1704 let is_stable = if is_stable
1705 && let Some(did) = did
1706 && this.is_stable(did, path.span)
1707 {
1708 true
1709 } else {
1710 false
1711 };
1712
1713 if is_stable
1718 && let Some(idx) = candidates
1719 .iter()
1720 .position(|v: &ImportSuggestion| v.did == did && !v.is_stable)
1721 {
1722 candidates.remove(idx);
1723 }
1724
1725 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1726 let note = if let Some(did) = did {
1729 let requires_note = !did.is_local()
1730 && {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(did, &this.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcDiagnosticItem(sym::TryInto
| sym::TryFrom | sym::FromIterator)) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(
1731 this.tcx,
1732 did,
1733 RustcDiagnosticItem(
1734 sym::TryInto | sym::TryFrom | sym::FromIterator
1735 )
1736 );
1737 requires_note.then(|| {
1738 ::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!(
1739 "'{}' is included in the prelude starting in Edition 2021",
1740 path_names_to_string(&path)
1741 )
1742 })
1743 } else {
1744 None
1745 };
1746
1747 candidates.push(ImportSuggestion {
1748 did,
1749 descr: res.descr(),
1750 path,
1751 accessible: child_accessible,
1752 doc_visible: child_doc_visible,
1753 note,
1754 via_import,
1755 is_stable,
1756 });
1757 }
1758 }
1759
1760 if let Some(def_id) = name_binding.res().module_like_def_id() {
1762 let mut path_segments = path_segments.clone();
1764 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
1765
1766 let alias_import = if let DeclKind::Import { import, .. } = name_binding.kind
1767 && let ImportKind::ExternCrate { source: Some(_), .. } = import.kind
1768 && import.parent_scope.expansion == parent_scope.expansion
1769 {
1770 true
1771 } else {
1772 false
1773 };
1774
1775 let is_extern_crate_that_also_appears_in_prelude =
1776 name_binding.is_extern_crate() && lookup_ident.span.at_least_rust_2018();
1777
1778 if !is_extern_crate_that_also_appears_in_prelude || alias_import {
1779 if seen_modules.insert(def_id) {
1781 if via_import { &mut worklist_via_import } else { &mut worklist }.push(
1782 (
1783 this.expect_module(def_id),
1784 path_segments,
1785 child_accessible,
1786 child_doc_visible,
1787 is_stable && this.is_stable(def_id, name_binding.span),
1788 ),
1789 );
1790 }
1791 }
1792 }
1793 })
1794 }
1795
1796 candidates
1797 }
1798
1799 fn is_stable(&self, did: DefId, span: Span) -> bool {
1800 if did.is_local() {
1801 return true;
1802 }
1803
1804 match self.tcx.lookup_stability(did) {
1805 Some(Stability {
1806 level: StabilityLevel::Unstable { implied_by, .. }, feature, ..
1807 }) => {
1808 if span.allows_unstable(feature) {
1809 true
1810 } else if self.features.enabled(feature) {
1811 true
1812 } else if let Some(implied_by) = implied_by
1813 && self.features.enabled(implied_by)
1814 {
1815 true
1816 } else {
1817 false
1818 }
1819 }
1820 Some(_) => true,
1821 None => false,
1822 }
1823 }
1824
1825 pub(crate) fn lookup_import_candidates<FilterFn>(
1833 &mut self,
1834 lookup_ident: Ident,
1835 namespace: Namespace,
1836 parent_scope: &ParentScope<'ra>,
1837 filter_fn: FilterFn,
1838 ) -> Vec<ImportSuggestion>
1839 where
1840 FilterFn: Fn(Res) -> bool,
1841 {
1842 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))];
1843 let mut suggestions = self.lookup_import_candidates_from_module(
1844 lookup_ident,
1845 namespace,
1846 parent_scope,
1847 self.graph_root.to_module(),
1848 crate_path,
1849 &filter_fn,
1850 );
1851
1852 if lookup_ident.span.at_least_rust_2018() {
1853 for (ident, entry) in &self.extern_prelude {
1854 if entry.span().from_expansion() {
1855 continue;
1861 }
1862 let Some(crate_id) =
1863 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
1864 else {
1865 continue;
1866 };
1867
1868 let crate_def_id = crate_id.as_def_id();
1869 let crate_root = self.expect_module(crate_def_id);
1870
1871 let needs_disambiguation =
1875 self.resolutions(parent_scope.module).borrow().iter().any(
1876 |(key, name_resolution)| {
1877 if key.ns == TypeNS
1878 && key.ident == *ident
1879 && let Some(decl) = name_resolution.borrow().best_decl()
1880 {
1881 match decl.res() {
1882 Res::Def(_, def_id) => def_id != crate_def_id,
1885 Res::PrimTy(_) => true,
1886 _ => false,
1887 }
1888 } else {
1889 false
1890 }
1891 },
1892 );
1893 let mut crate_path = ThinVec::new();
1894 if needs_disambiguation {
1895 crate_path.push(ast::PathSegment::path_root(rustc_span::DUMMY_SP));
1896 }
1897 crate_path.push(ast::PathSegment::from_ident(ident.orig(entry.span())));
1898
1899 suggestions.extend(self.lookup_import_candidates_from_module(
1900 lookup_ident,
1901 namespace,
1902 parent_scope,
1903 crate_root,
1904 crate_path,
1905 &filter_fn,
1906 ));
1907 }
1908 }
1909
1910 suggestions.retain(|suggestion| suggestion.is_stable || self.tcx.sess.is_nightly_build());
1911 suggestions
1912 }
1913
1914 pub(crate) fn unresolved_macro_suggestions(
1915 &mut self,
1916 err: &mut Diag<'_>,
1917 macro_kind: MacroKind,
1918 parent_scope: &ParentScope<'ra>,
1919 ident: Ident,
1920 krate: &Crate,
1921 sugg_span: Option<Span>,
1922 ) {
1923 self.register_macros_for_all_crates();
1926
1927 let is_expected =
1928 &|res: Res| res.macro_kinds().is_some_and(|k| k.contains(macro_kind.into()));
1929 let suggestion = self.early_lookup_typo_candidate(
1930 ScopeSet::Macro(macro_kind),
1931 parent_scope,
1932 ident,
1933 is_expected,
1934 );
1935 if !self.add_typo_suggestion(err, suggestion, ident.span) {
1936 self.detect_derive_attribute(err, ident, parent_scope, sugg_span);
1937 }
1938
1939 let import_suggestions =
1940 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1941 let (span, found_use) = match parent_scope.module.nearest_parent_mod_node_id() {
1942 DUMMY_NODE_ID => (None, FoundUse::No),
1943 node_id => UsePlacementFinder::check(krate, node_id),
1944 };
1945 show_candidates(
1946 self.tcx,
1947 err,
1948 span,
1949 &import_suggestions,
1950 Instead::No,
1951 found_use,
1952 DiagMode::Normal,
1953 ::alloc::vec::Vec::new()vec![],
1954 "",
1955 );
1956
1957 if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1958 let label_span = ident.span.shrink_to_hi();
1959 let mut spans = MultiSpan::from_span(label_span);
1960 spans.push_span_label(label_span, "put a macro name here");
1961 err.subdiagnostic(MaybeMissingMacroRulesName { spans });
1962 return;
1963 }
1964
1965 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1966 err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
1967 return;
1968 }
1969
1970 let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| {
1971 if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None }
1972 });
1973
1974 if let Some((def_id, unused_ident)) = unused_macro {
1975 let scope = self.local_macro_def_scopes[&def_id];
1976 let parent_nearest = parent_scope.module.nearest_parent_mod();
1977 let unused_macro_kinds = self.local_macro_map[def_id].macro_kinds();
1978 if !unused_macro_kinds.contains(macro_kind.into()) {
1979 match macro_kind {
1980 MacroKind::Bang => {
1981 err.subdiagnostic(MacroRulesNot::Func { span: unused_ident.span, ident });
1982 }
1983 MacroKind::Attr => {
1984 err.subdiagnostic(MacroRulesNot::Attr { span: unused_ident.span, ident });
1985 }
1986 MacroKind::Derive => {
1987 err.subdiagnostic(MacroRulesNot::Derive { span: unused_ident.span, ident });
1988 }
1989 }
1990 return;
1991 }
1992 if Some(parent_nearest) == scope.opt_def_id() {
1993 err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1994 err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
1995 return;
1996 }
1997 }
1998
1999 if ident.name == kw::Default
2000 && let ModuleKind::Def(DefKind::Enum, def_id, _, _) = parent_scope.module.kind
2001 {
2002 let span = self.def_span(def_id);
2003 let source_map = self.tcx.sess.source_map();
2004 let head_span = source_map.guess_head_span(span);
2005 err.subdiagnostic(ConsiderAddingADerive {
2006 span: head_span.shrink_to_lo(),
2007 suggestion: "#[derive(Default)]\n".to_string(),
2008 });
2009 }
2010 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
2011 let Ok(binding) = self.cm().resolve_ident_in_scope_set(
2012 ident,
2013 ScopeSet::All(ns),
2014 parent_scope,
2015 None,
2016 None,
2017 None,
2018 ) else {
2019 continue;
2020 };
2021
2022 let desc = match binding.res() {
2023 Res::Def(DefKind::Macro(MacroKinds::BANG), _) => {
2024 "a function-like macro".to_string()
2025 }
2026 Res::Def(DefKind::Macro(MacroKinds::ATTR), _) | Res::NonMacroAttr(..) => {
2027 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("an attribute: `#[{0}]`", ident))
})format!("an attribute: `#[{ident}]`")
2028 }
2029 Res::Def(DefKind::Macro(MacroKinds::DERIVE), _) => {
2030 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a derive macro: `#[derive({0})]`",
ident))
})format!("a derive macro: `#[derive({ident})]`")
2031 }
2032 Res::Def(DefKind::Macro(kinds), _) => {
2033 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", kinds.article(),
kinds.descr()))
})format!("{} {}", kinds.article(), kinds.descr())
2034 }
2035 Res::ToolMod | Res::OpenMod(..) => {
2036 continue;
2038 }
2039 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
2040 "only a trait, without a derive macro".to_string()
2041 }
2042 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!(
2043 "{} {}, not {} {}",
2044 res.article(),
2045 res.descr(),
2046 macro_kind.article(),
2047 macro_kind.descr_expected(),
2048 ),
2049 };
2050 if let crate::DeclKind::Import { import, .. } = binding.kind
2051 && !import.span.is_dummy()
2052 {
2053 let note = diagnostics::IdentImporterHereButItIsDesc {
2054 span: import.span,
2055 imported_ident: ident,
2056 imported_ident_desc: &desc,
2057 };
2058 err.subdiagnostic(note);
2059 self.record_use(ident, binding, Used::Other);
2062 return;
2063 }
2064 let note = diagnostics::IdentInScopeButItIsDesc {
2065 imported_ident: ident,
2066 imported_ident_desc: &desc,
2067 };
2068 err.subdiagnostic(note);
2069 return;
2070 }
2071
2072 if self.macro_names.contains(&IdentKey::new(ident)) {
2073 err.subdiagnostic(AddedMacroUse);
2074 return;
2075 }
2076 }
2077
2078 fn detect_derive_attribute(
2081 &self,
2082 err: &mut Diag<'_>,
2083 ident: Ident,
2084 parent_scope: &ParentScope<'ra>,
2085 sugg_span: Option<Span>,
2086 ) {
2087 let mut derives = ::alloc::vec::Vec::new()vec![];
2092 let mut all_attrs: UnordMap<Symbol, Vec<_>> = UnordMap::default();
2093 #[allow(rustc::potential_query_instability)]
2095 for (def_id, ext) in self
2096 .local_macro_map
2097 .iter()
2098 .map(|(local_id, ext)| (local_id.to_def_id(), ext))
2099 .chain(self.extern_macro_map.borrow().iter().map(|(id, d)| (*id, d)))
2100 {
2101 for helper_attr in &ext.helper_attrs {
2102 let item_name = self.tcx.item_name(def_id);
2103 all_attrs.entry(*helper_attr).or_default().push(item_name);
2104 if helper_attr == &ident.name {
2105 derives.push(item_name);
2106 }
2107 }
2108 }
2109 let kind = MacroKind::Derive.descr();
2110 if !derives.is_empty() {
2111 let mut derives: Vec<String> = derives.into_iter().map(|d| d.to_string()).collect();
2113 derives.sort();
2114 derives.dedup();
2115 let msg = match &derives[..] {
2116 [derive] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}`", derive))
})format!(" `{derive}`"),
2117 [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!(
2118 "s {} and `{last}`",
2119 start.iter().map(|d| format!("`{d}`")).collect::<Vec<_>>().join(", ")
2120 ),
2121 [] => {
::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!?"),
2122 };
2123 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!(
2124 "`{}` is an attribute that can be used by the {kind}{msg}, you might be \
2125 missing a `derive` attribute",
2126 ident.name,
2127 );
2128 let sugg_span =
2129 if let ModuleKind::Def(DefKind::Enum, id, _, _) = parent_scope.module.kind {
2130 let span = self.def_span(id);
2131 if span.from_expansion() {
2132 None
2133 } else {
2134 Some(span.shrink_to_lo())
2136 }
2137 } else {
2138 sugg_span
2140 };
2141 match sugg_span {
2142 Some(span) => {
2143 err.span_suggestion_verbose(
2144 span,
2145 msg,
2146 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n",
derives.join(", ")))
})format!("#[derive({})]\n", derives.join(", ")),
2147 Applicability::MaybeIncorrect,
2148 );
2149 }
2150 None => {
2151 err.note(msg);
2152 }
2153 }
2154 } else {
2155 let all_attr_names = all_attrs.keys().map(|s| *s).into_sorted_stable_ord();
2157 if let Some(best_match) = find_best_match_for_name(&all_attr_names, ident.name, None)
2158 && let Some(macros) = all_attrs.get(&best_match)
2159 {
2160 let mut macros: Vec<String> = macros.into_iter().map(|d| d.to_string()).collect();
2161 macros.sort();
2162 macros.dedup();
2163 let msg = match ¯os[..] {
2164 [] => return,
2165 [name] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}` accepts", name))
})format!(" `{name}` accepts"),
2166 [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!(
2167 "s {} and `{end}` accept",
2168 start.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", "),
2169 ),
2170 };
2171 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");
2172 err.span_suggestion_verbose(
2173 ident.span,
2174 msg,
2175 best_match,
2176 Applicability::MaybeIncorrect,
2177 );
2178 }
2179 }
2180 }
2181
2182 pub(crate) fn add_typo_suggestion(
2183 &self,
2184 err: &mut Diag<'_>,
2185 suggestion: Option<TypoSuggestion>,
2186 span: Span,
2187 ) -> bool {
2188 let suggestion = match suggestion {
2189 None => return false,
2190 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
2192 Some(suggestion) => suggestion,
2193 };
2194
2195 let mut did_label_def_span = false;
2196
2197 if let Some(def_span) = suggestion.res.opt_def_id().map(|def_id| self.def_span(def_id)) {
2198 if span.overlaps(def_span) {
2199 return false;
2218 }
2219 let span = self.tcx.sess.source_map().guess_head_span(def_span);
2220 let candidate_descr = suggestion.res.descr();
2221 let candidate = suggestion.candidate;
2222 let label = match suggestion.target {
2223 SuggestionTarget::SimilarlyNamed => {
2224 diagnostics::DefinedHere::SimilarlyNamed { span, candidate_descr, candidate }
2225 }
2226 SuggestionTarget::SingleItem => {
2227 diagnostics::DefinedHere::SingleItem { span, candidate_descr, candidate }
2228 }
2229 };
2230 did_label_def_span = true;
2231 err.subdiagnostic(label);
2232 }
2233
2234 let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
2235 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2236 && let Some(span) = suggestion.span
2237 && let Some(candidate) = suggestion.candidate.as_str().strip_prefix('_')
2238 && snippet == candidate
2239 {
2240 let candidate = suggestion.candidate;
2241 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!(
2244 "the leading underscore in `{candidate}` marks it as unused, consider renaming it to `{snippet}`"
2245 );
2246 if !did_label_def_span {
2247 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", candidate))
})format!("`{candidate}` defined here"));
2248 }
2249 (span, msg, snippet)
2250 } else {
2251 let msg = match suggestion.target {
2252 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!(
2253 "{} {} with a similar name exists",
2254 suggestion.res.article(),
2255 suggestion.res.descr()
2256 ),
2257 SuggestionTarget::SingleItem => {
2258 ::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())
2259 }
2260 };
2261 (span, msg, suggestion.candidate.to_ident_string())
2262 };
2263 err.span_suggestion_verbose(span, msg, sugg, Applicability::MaybeIncorrect);
2264 true
2265 }
2266
2267 fn decl_description(&self, b: Decl<'_>, ident: Ident, scope: Scope<'_>) -> String {
2268 let res = b.res();
2269 if b.span.is_dummy() || !self.tcx.sess.source_map().is_span_accessible(b.span) {
2270 let (built_in, from) = match scope {
2271 Scope::StdLibPrelude | Scope::MacroUsePrelude => ("", " from prelude"),
2272 Scope::ExternPreludeFlags
2273 if self.tcx.sess.opts.externs.get(ident.as_str()).is_some()
2274 || #[allow(non_exhaustive_omitted_patterns)] match res {
Res::OpenMod(..) => true,
_ => false,
}matches!(res, Res::OpenMod(..)) =>
2275 {
2276 ("", " passed with `--extern`")
2277 }
2278 _ => {
2279 if #[allow(non_exhaustive_omitted_patterns)] match res {
Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => true,
_ => false,
}matches!(res, Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod) {
2280 ("", "")
2282 } else {
2283 (" built-in", "")
2284 }
2285 }
2286 };
2287
2288 let a = if built_in.is_empty() { res.article() } else { "a" };
2289 ::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())
2290 } else {
2291 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
2292 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} {1} here", res.descr(),
introduced))
})format!("the {thing} {introduced} here", thing = res.descr())
2293 }
2294 }
2295
2296 fn ambiguity_diagnostic(
2297 &self,
2298 ambiguity_error: &AmbiguityError<'ra>,
2299 ) -> diagnostics::Ambiguity {
2300 let AmbiguityError { kind, ambig_vis, ident, b1, b2, scope1, scope2, .. } =
2301 *ambiguity_error;
2302 let extern_prelude_ambiguity = || {
2303 #[allow(non_exhaustive_omitted_patterns)] match scope2 {
Scope::ExternPreludeFlags => true,
_ => false,
}matches!(scope2, Scope::ExternPreludeFlags)
2305 && self
2306 .extern_prelude
2307 .get(&IdentKey::new(ident))
2308 .is_some_and(|entry| entry.item_decl.map(|(b, ..)| b) == Some(b1))
2309 };
2310 let (b1, b2, scope1, scope2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
2311 (b2, b1, scope2, scope1, true)
2313 } else {
2314 (b1, b2, scope1, scope2, false)
2315 };
2316
2317 let could_refer_to = |b: Decl<'_>, scope: Scope<'ra>, also: &str| {
2318 let what = self.decl_description(b, ident, scope);
2319 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}");
2320
2321 let thing = b.res().descr();
2322 let mut help_msgs = Vec::new();
2323 if b.is_glob_import()
2324 && (kind == AmbiguityKind::GlobVsGlob
2325 || kind == AmbiguityKind::GlobVsExpanded
2326 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
2327 {
2328 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider adding an explicit import of `{0}` to disambiguate",
ident))
})format!(
2329 "consider adding an explicit import of `{ident}` to disambiguate"
2330 ))
2331 }
2332 if b.is_extern_crate() && ident.span.at_least_rust_2018() && !extern_prelude_ambiguity()
2333 {
2334 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"))
2335 }
2336
2337 if kind != AmbiguityKind::GlobVsGlob {
2338 if let Scope::ModuleNonGlobs(module, _) | Scope::ModuleGlobs(module, _) = scope {
2339 if module == self.graph_root.to_module() {
2340 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `crate::{0}` to refer to this {1} unambiguously",
ident, thing))
})format!(
2341 "use `crate::{ident}` to refer to this {thing} unambiguously"
2342 ));
2343 } else if module.is_normal() {
2344 help_msgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `self::{0}` to refer to this {1} unambiguously",
ident, thing))
})format!(
2345 "use `self::{ident}` to refer to this {thing} unambiguously"
2346 ));
2347 }
2348 }
2349 }
2350
2351 (
2352 Spanned { node: note_msg, span: b.span },
2353 help_msgs
2354 .iter()
2355 .enumerate()
2356 .map(|(i, help_msg)| {
2357 let or = if i == 0 { "" } else { "or " };
2358 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", or, help_msg))
})format!("{or}{help_msg}")
2359 })
2360 .collect::<Vec<_>>(),
2361 )
2362 };
2363 let (b1_note, b1_help_msgs) = could_refer_to(b1, scope1, "");
2364 let (b2_note, b2_help_msgs) = could_refer_to(b2, scope2, " also");
2365 let help = if kind == AmbiguityKind::GlobVsGlob
2366 && b1
2367 .parent_module
2368 .and_then(|m| m.opt_def_id())
2369 .map(|d| !d.is_local())
2370 .unwrap_or_default()
2371 {
2372 Some(&[
2373 "consider updating this dependency to resolve this error",
2374 "if updating the dependency does not resolve the problem report the problem to the author of the relevant crate",
2375 ] as &[_])
2376 } else {
2377 None
2378 };
2379
2380 let ambig_vis = ambig_vis.map(|(vis1, vis2)| {
2381 ::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!(
2382 "{} or {}",
2383 vis1.to_string(CRATE_DEF_ID, self.tcx),
2384 vis2.to_string(CRATE_DEF_ID, self.tcx)
2385 )
2386 });
2387
2388 diagnostics::Ambiguity {
2389 ident,
2390 help,
2391 ambig_vis,
2392 kind: kind.descr(),
2393 b1_note,
2394 b1_help_msgs,
2395 b2_note,
2396 b2_help_msgs,
2397 is_error: false,
2398 }
2399 }
2400
2401 fn ctor_fields_span(&self, decl: Decl<'_>) -> Option<Span> {
2404 let DeclKind::Def(Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id)) =
2405 decl.kind
2406 else {
2407 return None;
2408 };
2409
2410 let def_id = self.tcx.parent(ctor_def_id);
2411 self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) }
2413
2414 fn module_path_names(&self, module: Module<'ra>) -> Option<Vec<Symbol>> {
2418 let mut path = Vec::new();
2419 let mut def_id = module.opt_def_id()?;
2420 while let Some(parent) = self.tcx.opt_parent(def_id) {
2421 if let Some(name) = self.tcx.opt_item_name(def_id) {
2422 path.push(name);
2423 }
2424 if parent.is_top_level_module() {
2425 break;
2426 }
2427 def_id = parent;
2428 }
2429 path.reverse();
2430 path.insert(0, kw::Crate);
2431 Some(path)
2432 }
2433
2434 fn shorten_candidate_path(
2438 &self,
2439 suggestion: &mut ImportSuggestion,
2440 current_module: Module<'ra>,
2441 ) {
2442 const MAX_SUPER_PATH_ITEMS_IN_SUGGESTION: usize = 1;
2443
2444 if suggestion.did.is_none_or(|did| !did.is_local()) {
2446 return;
2447 }
2448
2449 let Some(current_mod_path) = self.module_path_names(current_module) else {
2451 return;
2452 };
2453
2454 let candidate_names = {
2458 let filtered_segments: Vec<_> = suggestion
2459 .path
2460 .segments
2461 .iter()
2462 .filter(|segment| segment.ident.name != kw::PathRoot)
2463 .collect();
2464
2465 let mut candidate_names: Vec<Symbol> =
2466 filtered_segments.iter().map(|segment| segment.ident.name).collect();
2467 if candidate_names.first() != Some(&kw::Crate) {
2468 candidate_names.insert(0, kw::Crate);
2469 }
2470 if candidate_names.len() < 2 {
2471 return;
2472 }
2473 candidate_names
2474 };
2475
2476 let candidate_mod_names = &candidate_names[..candidate_names.len() - 1];
2478
2479 let common_prefix_length = current_mod_path
2481 .iter()
2482 .zip(candidate_mod_names.iter())
2483 .take_while(|(current, candidate)| current == candidate)
2484 .count();
2485
2486 if common_prefix_length == 0 {
2488 return;
2489 }
2490
2491 let super_count = current_mod_path.len() - common_prefix_length;
2492
2493 let at_crate_root = current_mod_path.len() == 1;
2496
2497 let mut new_segments = if super_count == 0 && at_crate_root {
2498 ThinVec::new()
2499 } else {
2500 let prefix_keyword = match super_count {
2501 0 => kw::SelfLower,
2502 1..=MAX_SUPER_PATH_ITEMS_IN_SUGGESTION => kw::Super,
2503 _ => return, };
2505 {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(ast::PathSegment::from_ident(Ident::with_dummy_span(prefix_keyword)));
vec
}thin_vec![ast::PathSegment::from_ident(Ident::with_dummy_span(prefix_keyword),)]
2506 };
2507 for &name in &candidate_names[common_prefix_length..] {
2508 new_segments.push(ast::PathSegment::from_ident(Ident::with_dummy_span(name)));
2509 }
2510
2511 if new_segments.len() >= suggestion.path.segments.len() {
2513 return;
2514 }
2515
2516 suggestion.path = Path { span: suggestion.path.span, segments: new_segments, tokens: None };
2517 }
2518
2519 fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
2520 let PrivacyError {
2521 ident,
2522 decl,
2523 outermost_res,
2524 parent_scope,
2525 single_nested,
2526 dedup_span,
2527 ref source,
2528 } = *privacy_error;
2529
2530 let res = decl.res();
2531 let ctor_fields_span = self.ctor_fields_span(decl);
2532 let plain_descr = res.descr().to_string();
2533 let nonimport_descr =
2534 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
2535 let import_descr = nonimport_descr.clone() + " import";
2536 let get_descr = |b: Decl<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
2537
2538 let ident_descr = get_descr(decl);
2540 let mut err =
2541 self.dcx().create_err(diagnostics::IsPrivate { span: ident.span, ident_descr, ident });
2542
2543 self.mention_default_field_values(source, ident, &mut err);
2544
2545 let shown_candidates = if let Some((this_res, outer_ident)) = outermost_res {
2546 let mut import_suggestions = self.lookup_import_candidates(
2547 outer_ident,
2548 this_res.ns().unwrap_or(Namespace::TypeNS),
2549 &parent_scope,
2550 &|res: Res| res == this_res,
2551 );
2552 for suggestion in &mut import_suggestions {
2554 self.shorten_candidate_path(suggestion, parent_scope.module);
2555 }
2556 let point_to_def = !show_candidates(
2557 self.tcx,
2558 &mut err,
2559 Some(dedup_span.until(outer_ident.span.shrink_to_hi())),
2560 &import_suggestions,
2561 Instead::Yes,
2562 FoundUse::Yes,
2563 DiagMode::Import { append: single_nested, unresolved_import: false },
2564 ::alloc::vec::Vec::new()vec![],
2565 "",
2566 );
2567 if point_to_def && ident.span != outer_ident.span {
2569 let label = diagnostics::OuterIdentIsNotPubliclyReexported {
2570 span: outer_ident.span,
2571 outer_ident_descr: this_res.descr(),
2572 outer_ident,
2573 };
2574 err.subdiagnostic(label);
2575 }
2576 !point_to_def
2577 } else {
2578 false
2579 };
2580
2581 let mut non_exhaustive = None;
2582 if let Some(def_id) = res.opt_def_id()
2586 && !def_id.is_local()
2587 && let Some(attr_span) = {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(NonExhaustive(span)) => {
break 'done Some(*span);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, def_id, NonExhaustive(span) => *span)
2588 {
2589 non_exhaustive = Some(attr_span);
2590 } else if let Some(span) = ctor_fields_span {
2591 let label = diagnostics::ConstructorPrivateIfAnyFieldPrivate { span };
2592 err.subdiagnostic(label);
2593 if let Res::Def(_, d) = res
2594 && let Some(fields) = self.field_visibility_spans.get(&d)
2595 {
2596 let spans = fields.iter().map(|span| *span).collect();
2597 let sugg = diagnostics::ConsiderMakingTheFieldPublic {
2598 spans,
2599 number_of_fields: fields.len(),
2600 };
2601 err.subdiagnostic(sugg);
2602 }
2603 }
2604
2605 let mut sugg_paths: Vec<(Vec<Ident>, bool)> = ::alloc::vec::Vec::new()vec![];
2606 if let Some(mut def_id) = res.opt_def_id() {
2607 let mut path = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[def_id]))vec![def_id];
2609 while let Some(parent) = self.tcx.opt_parent(def_id) {
2610 def_id = parent;
2611 if !def_id.is_top_level_module() {
2612 path.push(def_id);
2613 } else {
2614 break;
2615 }
2616 }
2617 let path_names: Option<Vec<Ident>> = path
2619 .iter()
2620 .rev()
2621 .map(|def_id| {
2622 self.tcx.opt_item_name(*def_id).map(|name| {
2623 Ident::with_dummy_span(if def_id.is_top_level_module() {
2624 kw::Crate
2625 } else {
2626 name
2627 })
2628 })
2629 })
2630 .collect();
2631 if let Some(&def_id) = path.get(0)
2632 && let Some(path) = path_names
2633 {
2634 if let Some(def_id) = def_id.as_local() {
2635 if self.effective_visibilities.is_directly_public(def_id) {
2636 sugg_paths.push((path, false));
2637 }
2638 } else if self.is_accessible_from(self.tcx.visibility(def_id), parent_scope.module)
2639 {
2640 sugg_paths.push((path, false));
2641 }
2642 }
2643 }
2644
2645 let first_binding = decl;
2647 let mut next_binding = Some(decl);
2648 let mut next_ident = ident;
2649 while let Some(binding) = next_binding {
2650 let name = next_ident;
2651 next_binding = match binding.kind {
2652 _ if res == Res::Err => None,
2653 DeclKind::Import { source_decl, import, .. } => match import.kind {
2654 _ if source_decl.span.is_dummy() => None,
2655 ImportKind::Single { source, .. } => {
2656 next_ident = source;
2657 Some(source_decl)
2658 }
2659 ImportKind::Glob { .. }
2660 | ImportKind::MacroUse { .. }
2661 | ImportKind::MacroExport => Some(source_decl),
2662 ImportKind::ExternCrate { .. } => None,
2663 },
2664 _ => None,
2665 };
2666
2667 match binding.kind {
2668 DeclKind::Import { source_decl, import, .. } => {
2669 let path = import
2672 .module_path
2673 .iter()
2674 .filter(|seg| seg.ident.name != kw::PathRoot)
2675 .map(|seg| seg.ident.clone())
2676 .chain(std::iter::once(ident))
2677 .collect::<Vec<_>>();
2678 let through_reexport = !#[allow(non_exhaustive_omitted_patterns)] match source_decl.kind {
DeclKind::Def(_) => true,
_ => false,
}matches!(source_decl.kind, DeclKind::Def(_));
2679 sugg_paths.push((path, through_reexport));
2680 }
2681 DeclKind::Def(_) => {}
2682 }
2683 let first = binding == first_binding;
2684 let def_span = self.tcx.sess.source_map().guess_head_span(binding.span);
2685 let mut note_span = MultiSpan::from_span(def_span);
2686 if !first && binding.vis().is_public() {
2687 let desc = match binding.kind {
2688 DeclKind::Import { .. } => "re-export",
2689 _ => "directly",
2690 };
2691 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}"));
2692 }
2693 if next_binding.is_none()
2696 && let Some(span) = non_exhaustive
2697 {
2698 note_span.push_span_label(
2699 span,
2700 "cannot be constructed because it is `#[non_exhaustive]`",
2701 );
2702 }
2703 let note = diagnostics::NoteAndRefersToTheItemDefinedHere {
2704 span: note_span,
2705 binding_descr: get_descr(binding),
2706 binding_name: name,
2707 first,
2708 dots: next_binding.is_some(),
2709 };
2710 err.subdiagnostic(note);
2711 }
2712 let can_replace_use = !shown_candidates
2720 && !single_nested
2721 && !outermost_res.is_some_and(|(_, outer)| outer.span != ident.span);
2722 if can_replace_use {
2723 sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0].name == sym::core, *reexport));
2726 for (sugg, reexport) in sugg_paths {
2727 if sugg.len() <= 1 {
2728 continue;
2731 }
2732 let path = join_path_idents(sugg);
2733 let sugg = if reexport {
2734 diagnostics::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
2735 } else {
2736 diagnostics::ImportIdent::Directly { span: dedup_span, ident, path }
2737 };
2738 err.subdiagnostic(sugg);
2739 break;
2740 }
2741 }
2742
2743 err.emit();
2744 }
2745
2746 fn mention_default_field_values(
2766 &self,
2767 source: &Option<ast::Expr>,
2768 ident: Ident,
2769 err: &mut Diag<'_>,
2770 ) {
2771 let Some(expr) = source else { return };
2772 let ast::ExprKind::Struct(struct_expr) = &expr.kind else { return };
2773 let Some(segment) = struct_expr.path.segments.last() else { return };
2776 let Some(partial_res) = self.partial_res_map.get(&segment.id) else { return };
2777 let Some(Res::Def(_, def_id)) = partial_res.full_res() else {
2778 return;
2779 };
2780 let Some(default_fields) = self.field_defaults(def_id) else { return };
2781 if struct_expr.fields.is_empty() {
2782 return;
2783 }
2784 let last_span = struct_expr.fields.iter().last().unwrap().span;
2785 let mut iter = struct_expr.fields.iter().peekable();
2786 let mut prev: Option<Span> = None;
2787 while let Some(field) = iter.next() {
2788 if field.expr.span.overlaps(ident.span) {
2789 err.span_label(field.ident.span, "while setting this field");
2790 if default_fields.contains(&field.ident.name) {
2791 let sugg = if last_span == field.span {
2792 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(field.span, "..".to_string())]))vec![(field.span, "..".to_string())]
2793 } else {
2794 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(match (prev, iter.peek()) {
(_, Some(next)) => field.span.with_hi(next.span.lo()),
(Some(prev), _) => field.span.with_lo(prev.hi()),
(None, None) => field.span,
}, String::new()),
(last_span.shrink_to_hi(), ", ..".to_string())]))vec![
2795 (
2796 match (prev, iter.peek()) {
2798 (_, Some(next)) => field.span.with_hi(next.span.lo()),
2799 (Some(prev), _) => field.span.with_lo(prev.hi()),
2800 (None, None) => field.span,
2801 },
2802 String::new(),
2803 ),
2804 (last_span.shrink_to_hi(), ", ..".to_string()),
2805 ]
2806 };
2807 err.multipart_suggestion(
2808 ::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!(
2809 "the type `{ident}` of field `{}` is private, but you can construct \
2810 the default value defined for it in `{}` using `..` in the struct \
2811 initializer expression",
2812 field.ident,
2813 self.tcx.item_name(def_id),
2814 ),
2815 sugg,
2816 Applicability::MachineApplicable,
2817 );
2818 break;
2819 }
2820 }
2821 prev = Some(field.span);
2822 }
2823 }
2824
2825 pub(crate) fn find_similarly_named_module_or_crate(
2826 &self,
2827 ident: Symbol,
2828 current_module: Module<'ra>,
2829 ) -> Option<Symbol> {
2830 let mut candidates = self
2831 .extern_prelude
2832 .keys()
2833 .map(|ident| ident.name)
2834 .chain(
2835 self.local_module_map
2836 .iter()
2837 .filter(|(_, module)| {
2838 let module = module.to_module();
2839 current_module.is_ancestor_of(module) && current_module != module
2840 })
2841 .flat_map(|(_, module)| module.name()),
2842 )
2843 .chain(
2844 self.extern_module_map
2845 .borrow()
2846 .iter()
2847 .filter(|(_, module)| {
2848 let module = module.to_module();
2849 current_module.is_ancestor_of(module) && current_module != module
2850 })
2851 .flat_map(|(_, module)| module.name()),
2852 )
2853 .filter(|c| !c.to_string().is_empty())
2854 .collect::<Vec<_>>();
2855 candidates.sort();
2856 candidates.dedup();
2857 find_best_match_for_name(&candidates, ident, None).filter(|sugg| *sugg != ident)
2858 }
2859
2860 pub(crate) fn report_path_resolution_error(
2861 &mut self,
2862 path: &[Segment],
2863 opt_ns: Option<Namespace>, parent_scope: &ParentScope<'ra>,
2865 ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
2866 ignore_decl: Option<Decl<'ra>>,
2867 ignore_import: Option<Import<'ra>>,
2868 module: Option<ModuleOrUniformRoot<'ra>>,
2869 failed_segment_idx: usize,
2870 ident: Ident,
2871 diag_metadata: Option<&DiagMetadata<'_>>,
2872 ) -> (String, String, Option<Suggestion>) {
2873 let is_last = failed_segment_idx == path.len() - 1;
2874 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
2875 let module_def_id = match module {
2876 Some(ModuleOrUniformRoot::Module(module)) => module.opt_def_id(),
2877 _ => None,
2878 };
2879 let scope = match &path[..failed_segment_idx] {
2880 [.., prev] => {
2881 if prev.ident.name == kw::PathRoot {
2882 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the crate root"))
})format!("the crate root")
2883 } else {
2884 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", prev.ident))
})format!("`{}`", prev.ident)
2885 }
2886 }
2887 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this scope"))
})format!("this scope"),
2888 };
2889 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find `{0}` in {1}", ident,
scope))
})format!("cannot find `{ident}` in {scope}");
2890
2891 if module_def_id == Some(CRATE_DEF_ID.to_def_id()) {
2892 let is_mod = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _));
2893 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
2894 candidates
2895 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
2896 if let Some(candidate) = candidates.get(0) {
2897 let path = {
2898 let len = candidate.path.segments.len();
2900 let start_index = (0..=failed_segment_idx.min(len - 1))
2901 .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name)
2902 .unwrap_or_default();
2903 let segments =
2904 (start_index..len).map(|s| candidate.path.segments[s].clone()).collect();
2905 Path { segments, span: Span::default(), tokens: None }
2906 };
2907 (
2908 message,
2909 String::from("unresolved import"),
2910 Some((
2911 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, pprust::path_to_string(&path))]))vec![(ident.span, pprust::path_to_string(&path))],
2912 String::from("a similar path exists"),
2913 Applicability::MaybeIncorrect,
2914 )),
2915 )
2916 } else if ident.name == sym::core {
2917 (
2918 message,
2919 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might be missing crate `{0}`",
ident))
})format!("you might be missing crate `{ident}`"),
2920 Some((
2921 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, "std".to_string())]))vec![(ident.span, "std".to_string())],
2922 "try using `std` instead of `core`".to_string(),
2923 Applicability::MaybeIncorrect,
2924 )),
2925 )
2926 } else if ident.name == kw::Underscore {
2927 (
2928 "invalid crate or module name `_`".to_string(),
2929 "`_` is not a valid crate or module name".to_string(),
2930 None,
2931 )
2932 } else if self.tcx.sess.is_rust_2015() {
2933 (
2934 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
ident, scope))
})format!("cannot find module or crate `{ident}` in {scope}"),
2935 ::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}`"),
2936 Some((
2937 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.current_crate_outer_attr_insert_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern crate {0};\n",
ident))
}))]))vec![(
2938 self.current_crate_outer_attr_insert_span,
2939 format!("extern crate {ident};\n"),
2940 )],
2941 if was_invoked_from_cargo() {
2942 ::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!(
2943 "if you wanted to use a crate named `{ident}`, use `cargo add \
2944 {ident}` to add it to your `Cargo.toml` and import it in your \
2945 code",
2946 )
2947 } else {
2948 ::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!(
2949 "you might be missing a crate named `{ident}`, add it to your \
2950 project and import it in your code",
2951 )
2952 },
2953 Applicability::MaybeIncorrect,
2954 )),
2955 )
2956 } else {
2957 (message, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not find `{0}` in the crate root",
ident))
})format!("could not find `{ident}` in the crate root"), None)
2958 }
2959 } else if failed_segment_idx > 0 {
2960 let parent = path[failed_segment_idx - 1].ident.name;
2961 let parent = match parent {
2962 kw::PathRoot if self.tcx.sess.edition() > Edition::Edition2015 => {
2965 "the list of imported crates".to_owned()
2966 }
2967 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
2968 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", parent))
})format!("`{parent}`"),
2969 };
2970
2971 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}");
2972 if ns == TypeNS || ns == ValueNS {
2973 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
2974 let binding = if let Some(module) = module {
2975 self.cm()
2976 .resolve_ident_in_module(
2977 module,
2978 ident,
2979 ns_to_try,
2980 parent_scope,
2981 None,
2982 ignore_decl,
2983 ignore_import,
2984 )
2985 .ok()
2986 } else if let Some(ribs) = ribs
2987 && let Some(TypeNS | ValueNS) = opt_ns
2988 {
2989 if !ignore_import.is_none() {
::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
2990 match self.resolve_ident_in_lexical_scope(
2991 ident,
2992 ns_to_try,
2993 parent_scope,
2994 None,
2995 &ribs[ns_to_try],
2996 ignore_decl,
2997 diag_metadata,
2998 ) {
2999 Some(LateDecl::Decl(binding)) => Some(binding),
3001 _ => None,
3002 }
3003 } else {
3004 self.cm()
3005 .resolve_ident_in_scope_set(
3006 ident,
3007 ScopeSet::All(ns_to_try),
3008 parent_scope,
3009 None,
3010 ignore_decl,
3011 ignore_import,
3012 )
3013 .ok()
3014 };
3015 if let Some(binding) = binding {
3016 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!(
3017 "expected {}, found {} `{ident}` in {parent}",
3018 ns.descr(),
3019 binding.res().descr(),
3020 );
3021 };
3022 }
3023 (message, msg, None)
3024 } else if ident.name == kw::SelfUpper {
3025 if opt_ns.is_none() {
3029 (message, "`Self` cannot be used in imports".to_string(), None)
3030 } else {
3031 (
3032 message,
3033 "`Self` is only available in impls, traits, and type definitions".to_string(),
3034 None,
3035 )
3036 }
3037 } else if ident.name.as_str().chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
3038 let binding = if let Some(ribs) = ribs {
3040 if !ignore_import.is_none() {
::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
3041 self.resolve_ident_in_lexical_scope(
3042 ident,
3043 ValueNS,
3044 parent_scope,
3045 None,
3046 &ribs[ValueNS],
3047 ignore_decl,
3048 diag_metadata,
3049 )
3050 } else {
3051 None
3052 };
3053 let match_span = match binding {
3054 Some(LateDecl::RibDef(Res::Local(id))) => {
3063 Some((*self.pat_span_map.get(&id).unwrap(), "a", "local binding"))
3064 }
3065 Some(LateDecl::Decl(name_binding)) => Some((
3077 name_binding.span,
3078 name_binding.res().article(),
3079 name_binding.res().descr(),
3080 )),
3081 _ => None,
3082 };
3083
3084 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find type `{0}` in {1}",
ident, scope))
})format!("cannot find type `{ident}` in {scope}");
3085 let label = if let Some((span, article, descr)) = match_span {
3086 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{1}` is declared as {2} {3} at `{0}`, not a type",
self.tcx.sess.source_map().span_to_short_string(span,
RemapPathScopeComponents::DIAGNOSTICS), ident, article,
descr))
})format!(
3087 "`{ident}` is declared as {article} {descr} at `{}`, not a type",
3088 self.tcx
3089 .sess
3090 .source_map()
3091 .span_to_short_string(span, RemapPathScopeComponents::DIAGNOSTICS)
3092 )
3093 } else {
3094 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use of undeclared type `{0}`",
ident))
})format!("use of undeclared type `{ident}`")
3095 };
3096 (message, label, None)
3097 } else {
3098 let mut suggestion = None;
3099 if ident.name == sym::alloc {
3100 suggestion = Some((
3101 ::alloc::vec::Vec::new()vec![],
3102 String::from("add `extern crate alloc` to use the `alloc` crate"),
3103 Applicability::MaybeIncorrect,
3104 ))
3105 }
3106
3107 suggestion = suggestion.or_else(|| {
3108 self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
3109 |sugg| {
3110 (
3111 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, sugg.to_string())]))vec![(ident.span, sugg.to_string())],
3112 String::from("there is a crate or module with a similar name"),
3113 Applicability::MaybeIncorrect,
3114 )
3115 },
3116 )
3117 });
3118 if let Ok(binding) = self.cm().resolve_ident_in_scope_set(
3119 ident,
3120 ScopeSet::All(ValueNS),
3121 parent_scope,
3122 None,
3123 ignore_decl,
3124 ignore_import,
3125 ) {
3126 let descr = binding.res().descr();
3127 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
ident, scope))
})format!("cannot find module or crate `{ident}` in {scope}");
3128 (message, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` is not a crate or module",
descr, ident))
})format!("{descr} `{ident}` is not a crate or module"), suggestion)
3129 } else {
3130 let suggestion = if suggestion.is_some() {
3131 suggestion
3132 } else if let Some(m) = self.undeclared_module_exists(ident) {
3133 self.undeclared_module_suggest_declare(ident, m)
3134 } else if was_invoked_from_cargo() {
3135 Some((
3136 ::alloc::vec::Vec::new()vec![],
3137 ::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!(
3138 "if you wanted to use a crate named `{ident}`, use `cargo add {ident}` \
3139 to add it to your `Cargo.toml`",
3140 ),
3141 Applicability::MaybeIncorrect,
3142 ))
3143 } else {
3144 Some((
3145 ::alloc::vec::Vec::new()vec![],
3146 ::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}`",),
3147 Applicability::MaybeIncorrect,
3148 ))
3149 };
3150 let message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find module or crate `{0}` in {1}",
ident, scope))
})format!("cannot find module or crate `{ident}` in {scope}");
3151 (
3152 message,
3153 ::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}`"),
3154 suggestion,
3155 )
3156 }
3157 }
3158 }
3159
3160 fn undeclared_module_suggest_declare(
3161 &self,
3162 ident: Ident,
3163 path: std::path::PathBuf,
3164 ) -> Option<(Vec<(Span, String)>, String, Applicability)> {
3165 Some((
3166 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.current_crate_outer_attr_insert_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("mod {0};\n", ident))
}))]))vec![(self.current_crate_outer_attr_insert_span, format!("mod {ident};\n"))],
3167 ::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!(
3168 "to make use of source file {}, use `mod {ident}` \
3169 in this file to declare the module",
3170 path.display()
3171 ),
3172 Applicability::MaybeIncorrect,
3173 ))
3174 }
3175
3176 fn undeclared_module_exists(&self, ident: Ident) -> Option<std::path::PathBuf> {
3177 let map = self.tcx.sess.source_map();
3178
3179 let src = map.span_to_filename(ident.span).into_local_path()?;
3180 let i = ident.as_str();
3181 let dir = src.parent()?;
3183 let src = src.file_stem()?.to_str()?;
3184 for file in [
3185 dir.join(i).with_extension("rs"),
3187 dir.join(i).join("mod.rs"),
3189 ] {
3190 if file.exists() {
3191 return Some(file);
3192 }
3193 }
3194 if !#[allow(non_exhaustive_omitted_patterns)] match src {
"main" | "lib" | "mod" => true,
_ => false,
}matches!(src, "main" | "lib" | "mod") {
3195 for file in [
3196 dir.join(src).join(i).with_extension("rs"),
3198 dir.join(src).join(i).join("mod.rs"),
3200 ] {
3201 if file.exists() {
3202 return Some(file);
3203 }
3204 }
3205 }
3206 None
3207 }
3208
3209 #[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::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3210u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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))]
3211 pub(crate) fn make_path_suggestion(
3212 &mut self,
3213 mut path: Vec<Segment>,
3214 parent_scope: &ParentScope<'ra>,
3215 ) -> Option<(Vec<Segment>, Option<String>)> {
3216 match path[..] {
3217 [first, second, ..]
3220 if first.ident.name == kw::PathRoot && !second.ident.is_path_segment_keyword() => {}
3221 [first, ..]
3223 if first.ident.span.at_least_rust_2018()
3224 && !first.ident.is_path_segment_keyword() =>
3225 {
3226 path.insert(0, Segment::from_ident(Ident::dummy()));
3228 }
3229 _ => return None,
3230 }
3231
3232 self.make_missing_self_suggestion(path.clone(), parent_scope)
3233 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
3234 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
3235 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
3236 }
3237
3238 #[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::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3245u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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/error_helper.rs:3254",
"rustc_resolve::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3254u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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))]
3246 fn make_missing_self_suggestion(
3247 &mut self,
3248 mut path: Vec<Segment>,
3249 parent_scope: &ParentScope<'ra>,
3250 ) -> Option<(Vec<Segment>, Option<String>)> {
3251 path[0].ident.name = kw::SelfLower;
3253 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
3254 debug!(?path, ?result);
3255 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
3256 }
3257
3258 #[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::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3265u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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/error_helper.rs:3274",
"rustc_resolve::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3274u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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))]
3266 fn make_missing_crate_suggestion(
3267 &mut self,
3268 mut path: Vec<Segment>,
3269 parent_scope: &ParentScope<'ra>,
3270 ) -> Option<(Vec<Segment>, Option<String>)> {
3271 path[0].ident.name = kw::Crate;
3273 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
3274 debug!(?path, ?result);
3275 if let PathResult::Module(..) = result {
3276 Some((
3277 path,
3278 Some(
3279 "`use` statements changed in Rust 2018; read more at \
3280 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
3281 clarity.html>"
3282 .to_string(),
3283 ),
3284 ))
3285 } else {
3286 None
3287 }
3288 }
3289
3290 #[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::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3297u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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/error_helper.rs:3306",
"rustc_resolve::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3306u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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))]
3298 fn make_missing_super_suggestion(
3299 &mut self,
3300 mut path: Vec<Segment>,
3301 parent_scope: &ParentScope<'ra>,
3302 ) -> Option<(Vec<Segment>, Option<String>)> {
3303 path[0].ident.name = kw::Super;
3305 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
3306 debug!(?path, ?result);
3307 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
3308 }
3309
3310 #[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::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3320u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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/error_helper.rs:3341",
"rustc_resolve::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3341u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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))]
3321 fn make_external_crate_suggestion(
3322 &mut self,
3323 mut path: Vec<Segment>,
3324 parent_scope: &ParentScope<'ra>,
3325 ) -> Option<(Vec<Segment>, Option<String>)> {
3326 if path[1].ident.span.is_rust_2015() {
3327 return None;
3328 }
3329
3330 let mut extern_crate_names =
3334 self.extern_prelude.keys().map(|ident| ident.name).collect::<Vec<_>>();
3335 extern_crate_names.sort_by(|a, b| b.as_str().cmp(a.as_str()));
3336
3337 for name in extern_crate_names.into_iter() {
3338 path[0].ident.name = name;
3340 let result = self.cm().maybe_resolve_path(&path, None, parent_scope, None);
3341 debug!(?path, ?name, ?result);
3342 if let PathResult::Module(..) = result {
3343 return Some((path, None));
3344 }
3345 }
3346
3347 None
3348 }
3349
3350 pub(crate) fn check_for_module_export_macro(
3363 &mut self,
3364 import: Import<'ra>,
3365 module: ModuleOrUniformRoot<'ra>,
3366 ident: Ident,
3367 ) -> Option<(Option<Suggestion>, Option<String>)> {
3368 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
3369 return None;
3370 };
3371
3372 while let Some(parent) = crate_module.parent {
3373 crate_module = parent;
3374 }
3375
3376 if module == ModuleOrUniformRoot::Module(crate_module) {
3377 return None;
3379 }
3380
3381 let binding_key = BindingKey::new(IdentKey::new(ident), MacroNS);
3382 let binding = self.resolution(crate_module, binding_key)?.best_decl()?;
3383 let Res::Def(DefKind::Macro(kinds), _) = binding.res() else {
3384 return None;
3385 };
3386 if !kinds.contains(MacroKinds::BANG) {
3387 return None;
3388 }
3389 let module_name = crate_module.name().unwrap_or(kw::Crate);
3390 let import_snippet = match import.kind {
3391 ImportKind::Single { source, target, .. } if source != target => {
3392 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} as {1}", source, target))
})format!("{source} as {target}")
3393 }
3394 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", ident))
})format!("{ident}"),
3395 };
3396
3397 let mut corrections: Vec<(Span, String)> = Vec::new();
3398 if !import.is_nested() {
3399 corrections.push((import.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}", module_name,
import_snippet))
})format!("{module_name}::{import_snippet}")));
3402 } else {
3403 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
3407 self.tcx.sess,
3408 import.span,
3409 import.use_span,
3410 );
3411 {
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/error_helper.rs:3411",
"rustc_resolve::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3411u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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);
3412
3413 let mut removal_span = binding_span;
3414
3415 if found_closing_brace
3423 && let Some(previous_span) =
3424 extend_span_to_previous_binding(self.tcx.sess, binding_span)
3425 {
3426 {
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/error_helper.rs:3426",
"rustc_resolve::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3426u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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);
3427 removal_span = removal_span.with_lo(previous_span.lo());
3428 }
3429 {
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/error_helper.rs:3429",
"rustc_resolve::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3429u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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);
3430
3431 corrections.push((removal_span, "".to_string()));
3433
3434 let (has_nested, after_crate_name) =
3441 find_span_immediately_after_crate_name(self.tcx.sess, import.use_span);
3442 {
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/error_helper.rs:3442",
"rustc_resolve::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3442u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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);
3443
3444 let source_map = self.tcx.sess.source_map();
3445
3446 let is_definitely_crate = import
3448 .module_path
3449 .first()
3450 .is_some_and(|f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
3451
3452 let start_point = source_map.start_point(after_crate_name);
3454 if is_definitely_crate
3455 && let Ok(start_snippet) = source_map.span_to_snippet(start_point)
3456 {
3457 corrections.push((
3458 start_point,
3459 if has_nested {
3460 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}, ", start_snippet,
import_snippet))
})format!("{start_snippet}{import_snippet}, ")
3462 } else {
3463 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{{0}, {1}", import_snippet,
start_snippet))
})format!("{{{import_snippet}, {start_snippet}")
3466 },
3467 ));
3468
3469 if !has_nested {
3471 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
3472 }
3473 } else {
3474 corrections.push((
3476 import.use_span.shrink_to_lo(),
3477 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use {0}::{1};\n", module_name,
import_snippet))
})format!("use {module_name}::{import_snippet};\n"),
3478 ));
3479 }
3480 }
3481
3482 let suggestion = Some((
3483 corrections,
3484 String::from("a macro with this name exists at the root of the crate"),
3485 Applicability::MaybeIncorrect,
3486 ));
3487 Some((
3488 suggestion,
3489 Some(
3490 "this could be because a macro annotated with `#[macro_export]` will be exported \
3491 at the root of the crate instead of the module where it is defined"
3492 .to_string(),
3493 ),
3494 ))
3495 }
3496
3497 pub(crate) fn find_cfg_stripped(&self, err: &mut Diag<'_>, segment: &Symbol, module: DefId) {
3499 let local_items;
3500 let symbols = if module.is_local() {
3501 local_items = self
3502 .stripped_cfg_items
3503 .iter()
3504 .filter_map(|item| {
3505 let parent_scope = self.local_modules.iter().find_map(|m| match m.kind {
3506 ModuleKind::Def(_, def_id, node_id, _) if node_id == item.parent_scope => {
3507 Some(def_id)
3508 }
3509 _ => None,
3510 })?;
3511 Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg.clone() })
3512 })
3513 .collect::<Vec<_>>();
3514 local_items.as_slice()
3515 } else {
3516 self.tcx.stripped_cfg_items(module.krate)
3517 };
3518
3519 for &StrippedCfgItem { parent_scope, ident, ref cfg } in symbols {
3520 if ident.name != *segment {
3521 continue;
3522 }
3523
3524 let parent_module = self.get_nearest_non_block_module(parent_scope).def_id();
3525
3526 fn comes_from_same_module_for_glob(
3527 r: &Resolver<'_, '_>,
3528 parent_module: DefId,
3529 module: DefId,
3530 visited: &mut FxHashMap<DefId, bool>,
3531 ) -> bool {
3532 if let Some(&cached) = visited.get(&parent_module) {
3533 return cached;
3537 }
3538 visited.insert(parent_module, false);
3539 let mut res = false;
3540 let m = r.expect_module(parent_module);
3541 if m.is_local() {
3542 for importer in m.glob_importers.borrow().iter() {
3543 if let Some(next_parent_module) = importer.parent_scope.module.opt_def_id()
3544 {
3545 if next_parent_module == module
3546 || comes_from_same_module_for_glob(
3547 r,
3548 next_parent_module,
3549 module,
3550 visited,
3551 )
3552 {
3553 res = true;
3554 break;
3555 }
3556 }
3557 }
3558 }
3559 visited.insert(parent_module, res);
3560 res
3561 }
3562
3563 let comes_from_same_module = parent_module == module
3564 || comes_from_same_module_for_glob(
3565 self,
3566 parent_module,
3567 module,
3568 &mut Default::default(),
3569 );
3570 if !comes_from_same_module {
3571 continue;
3572 }
3573
3574 let item_was = if let CfgEntry::NameValue { value: Some(feature), .. } = cfg.0 {
3575 diagnostics::ItemWas::BehindFeature { feature, span: cfg.1 }
3576 } else {
3577 diagnostics::ItemWas::CfgOut { span: cfg.1 }
3578 };
3579 let note = diagnostics::FoundItemConfigureOut { span: ident.span, item_was };
3580 err.subdiagnostic(note);
3581 }
3582 }
3583
3584 pub(crate) fn struct_ctor(&self, def_id: DefId) -> Option<StructCtor> {
3585 match def_id.as_local() {
3586 Some(def_id) => self.struct_ctors.get(&def_id).cloned(),
3587 None => {
3588 self.cstore().ctor_untracked(self.tcx, def_id).map(|(ctor_kind, ctor_def_id)| {
3589 let res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
3590 let vis = self.tcx.visibility(ctor_def_id);
3591 let field_visibilities = self
3592 .tcx
3593 .associated_item_def_ids(def_id)
3594 .iter()
3595 .map(|&field_id| self.tcx.visibility(field_id))
3596 .collect();
3597 StructCtor { res, vis, field_visibilities }
3598 })
3599 }
3600 }
3601 }
3602
3603 fn on_unknown_data(&self, def_id: DefId) -> Option<&Directive> {
3605 match def_id.as_local() {
3606 Some(local) => Some(self.on_unknown_data.get(&local)?.directive.as_ref()),
3607 None => {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(OnUnknown { directive }) => {
break 'done Some(directive);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, def_id, OnUnknown{ directive } => directive)?.as_deref(),
3608 }
3609 }
3610}
3611
3612fn find_span_of_binding_until_next_binding(
3626 sess: &Session,
3627 binding_span: Span,
3628 use_span: Span,
3629) -> (bool, Span) {
3630 let source_map = sess.source_map();
3631
3632 let binding_until_end = binding_span.with_hi(use_span.hi());
3635
3636 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
3639
3640 let mut found_closing_brace = false;
3647 let after_binding_until_next_binding =
3648 source_map.span_take_while(after_binding_until_end, |&ch| {
3649 if ch == '}' {
3650 found_closing_brace = true;
3651 }
3652 ch == ' ' || ch == ','
3653 });
3654
3655 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
3660
3661 (found_closing_brace, span)
3662}
3663
3664fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
3677 let source_map = sess.source_map();
3678
3679 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
3683
3684 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
3685 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
3686 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
3687 return None;
3688 }
3689
3690 let prev_comma = prev_comma.first().unwrap();
3691 let prev_starting_brace = prev_starting_brace.first().unwrap();
3692
3693 if prev_comma.len() > prev_starting_brace.len() {
3697 return None;
3698 }
3699
3700 Some(binding_span.with_lo(BytePos(
3701 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
3704 )))
3705}
3706
3707#[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::error_helper", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/error_helper.rs"),
::tracing_core::__macro_support::Option::Some(3720u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::error_helper"),
::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))]
3721fn find_span_immediately_after_crate_name(sess: &Session, use_span: Span) -> (bool, Span) {
3722 let source_map = sess.source_map();
3723
3724 let mut num_colons = 0;
3726 let until_second_colon = source_map.span_take_while(use_span, |c| {
3728 if *c == ':' {
3729 num_colons += 1;
3730 }
3731 !matches!(c, ':' if num_colons == 2)
3732 });
3733 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
3735
3736 let mut found_a_non_whitespace_character = false;
3737 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
3739 if found_a_non_whitespace_character {
3740 return false;
3741 }
3742 if !c.is_whitespace() {
3743 found_a_non_whitespace_character = true;
3744 }
3745 true
3746 });
3747
3748 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
3750
3751 (next_left_bracket == after_second_colon, from_second_colon)
3752}
3753
3754enum Instead {
3757 Yes,
3758 No,
3759}
3760
3761enum FoundUse {
3763 Yes,
3764 No,
3765}
3766
3767pub(crate) enum DiagMode {
3769 Normal,
3770 Pattern,
3772 Import {
3774 unresolved_import: bool,
3776 append: bool,
3779 },
3780}
3781
3782pub(crate) fn import_candidates(
3783 tcx: TyCtxt<'_>,
3784 err: &mut Diag<'_>,
3785 use_placement_span: Option<Span>,
3787 candidates: &[ImportSuggestion],
3788 mode: DiagMode,
3789 append: &str,
3790) {
3791 show_candidates(
3792 tcx,
3793 err,
3794 use_placement_span,
3795 candidates,
3796 Instead::Yes,
3797 FoundUse::Yes,
3798 mode,
3799 ::alloc::vec::Vec::new()vec![],
3800 append,
3801 );
3802}
3803
3804type PathString<'a> = (String, &'a str, Option<Span>, &'a Option<String>, bool);
3805
3806fn show_candidates(
3811 tcx: TyCtxt<'_>,
3812 err: &mut Diag<'_>,
3813 use_placement_span: Option<Span>,
3815 candidates: &[ImportSuggestion],
3816 instead: Instead,
3817 found_use: FoundUse,
3818 mode: DiagMode,
3819 path: Vec<Segment>,
3820 append: &str,
3821) -> bool {
3822 if candidates.is_empty() {
3823 return false;
3824 }
3825
3826 let mut showed = false;
3827 let mut accessible_path_strings: Vec<PathString<'_>> = Vec::new();
3828 let mut inaccessible_path_strings: Vec<PathString<'_>> = Vec::new();
3829
3830 candidates.iter().for_each(|c| {
3831 if c.accessible {
3832 if c.doc_visible {
3834 accessible_path_strings.push((
3835 pprust::path_to_string(&c.path),
3836 c.descr,
3837 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3838 &c.note,
3839 c.via_import,
3840 ))
3841 }
3842 } else {
3843 inaccessible_path_strings.push((
3844 pprust::path_to_string(&c.path),
3845 c.descr,
3846 c.did.and_then(|did| Some(tcx.source_span(did.as_local()?))),
3847 &c.note,
3848 c.via_import,
3849 ))
3850 }
3851 });
3852
3853 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
3856 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
3857 path_strings.dedup_by(|a, b| a.0 == b.0);
3858 let core_path_strings =
3859 path_strings.extract_if(.., |p| p.0.starts_with("core::")).collect::<Vec<_>>();
3860 let std_path_strings =
3861 path_strings.extract_if(.., |p| p.0.starts_with("std::")).collect::<Vec<_>>();
3862 let foreign_crate_path_strings =
3863 path_strings.extract_if(.., |p| !p.0.starts_with("crate::")).collect::<Vec<_>>();
3864
3865 if std_path_strings.len() == core_path_strings.len() {
3868 path_strings.extend(std_path_strings);
3870 } else {
3871 path_strings.extend(std_path_strings);
3872 path_strings.extend(core_path_strings);
3873 }
3874 path_strings.extend(foreign_crate_path_strings);
3876 }
3877
3878 if !accessible_path_strings.is_empty() {
3879 let (determiner, kind, s, name, through) =
3880 if let [(name, descr, _, _, via_import)] = &accessible_path_strings[..] {
3881 (
3882 "this",
3883 *descr,
3884 "",
3885 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}`", name))
})format!(" `{name}`"),
3886 if *via_import { " through its public re-export" } else { "" },
3887 )
3888 } else {
3889 let kinds = accessible_path_strings
3892 .iter()
3893 .map(|(_, descr, _, _, _)| *descr)
3894 .collect::<UnordSet<&str>>();
3895 let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" };
3896 let s = if kind.ends_with('s') { "es" } else { "s" };
3897
3898 ("one of these", kind, s, String::new(), "")
3899 };
3900
3901 let instead = if let Instead::Yes = instead { " instead" } else { "" };
3902 let mut msg = if let DiagMode::Pattern = mode {
3903 ::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!(
3904 "if you meant to match on {kind}{s}{instead}{name}, use the full path in the \
3905 pattern",
3906 )
3907 } else {
3908 ::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}")
3909 };
3910
3911 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
3912 err.note(note.clone());
3913 }
3914
3915 let append_candidates = |msg: &mut String, accessible_path_strings: Vec<PathString<'_>>| {
3916 msg.push(':');
3917
3918 for candidate in accessible_path_strings {
3919 msg.push('\n');
3920 msg.push_str(&candidate.0);
3921 }
3922 };
3923
3924 if let Some(span) = use_placement_span {
3925 let (add_use, trailing) = match mode {
3926 DiagMode::Pattern => {
3927 err.span_suggestions(
3928 span,
3929 msg,
3930 accessible_path_strings.into_iter().map(|a| a.0),
3931 Applicability::MaybeIncorrect,
3932 );
3933 return true;
3934 }
3935 DiagMode::Import { .. } => ("", ""),
3936 DiagMode::Normal => ("use ", ";\n"),
3937 };
3938 for candidate in &mut accessible_path_strings {
3939 let additional_newline = if let FoundUse::No = found_use
3942 && let DiagMode::Normal = mode
3943 {
3944 "\n"
3945 } else {
3946 ""
3947 };
3948 candidate.0 =
3949 ::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);
3950 }
3951
3952 match mode {
3953 DiagMode::Import { append: true, .. } => {
3954 append_candidates(&mut msg, accessible_path_strings);
3955 err.span_help(span, msg);
3956 }
3957 _ => {
3958 err.span_suggestions_with_style(
3959 span,
3960 msg,
3961 accessible_path_strings.into_iter().map(|a| a.0),
3962 Applicability::MaybeIncorrect,
3963 SuggestionStyle::ShowAlways,
3964 );
3965 }
3966 }
3967
3968 if let [first, .., last] = &path[..] {
3969 let sp = first.ident.span.until(last.ident.span);
3970 if sp.can_be_used_for_suggestions() && !sp.is_empty() {
3973 err.span_suggestion_verbose(
3974 sp,
3975 ::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),
3976 "",
3977 Applicability::Unspecified,
3978 );
3979 }
3980 }
3981 } else {
3982 append_candidates(&mut msg, accessible_path_strings);
3983 err.help(msg);
3984 }
3985 showed = true;
3986 }
3987 if !inaccessible_path_strings.is_empty()
3988 && (!#[allow(non_exhaustive_omitted_patterns)] match mode {
DiagMode::Import { unresolved_import: false, .. } => true,
_ => false,
}matches!(mode, DiagMode::Import { unresolved_import: false, .. }))
3989 {
3990 let prefix =
3991 if let DiagMode::Pattern = mode { "you might have meant to match on " } else { "" };
3992 if let [(name, descr, source_span, note, _)] = &inaccessible_path_strings[..] {
3993 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!(
3994 "{prefix}{descr} `{name}`{} exists but is inaccessible",
3995 if let DiagMode::Pattern = mode { ", which" } else { "" }
3996 );
3997
3998 if let Some(source_span) = source_span {
3999 let span = tcx.sess.source_map().guess_head_span(*source_span);
4000 let mut multi_span = MultiSpan::from_span(span);
4001 multi_span.push_span_label(span, "not accessible");
4002 err.span_note(multi_span, msg);
4003 } else {
4004 err.note(msg);
4005 }
4006 if let Some(note) = (*note).as_deref() {
4007 err.note(note.to_string());
4008 }
4009 } else {
4010 let descr = inaccessible_path_strings
4011 .iter()
4012 .map(|&(_, descr, _, _, _)| descr)
4013 .all_equal_value()
4014 .unwrap_or("item");
4015 let plural_descr =
4016 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") };
4017
4018 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");
4019 let mut has_colon = false;
4020
4021 let mut spans = Vec::new();
4022 for (name, _, source_span, _, _) in &inaccessible_path_strings {
4023 if let Some(source_span) = source_span {
4024 let span = tcx.sess.source_map().guess_head_span(*source_span);
4025 spans.push((name, span));
4026 } else {
4027 if !has_colon {
4028 msg.push(':');
4029 has_colon = true;
4030 }
4031 msg.push('\n');
4032 msg.push_str(name);
4033 }
4034 }
4035
4036 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
4037 for (name, span) in spans {
4038 multi_span.push_span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`: not accessible", name))
})format!("`{name}`: not accessible"));
4039 }
4040
4041 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
4042 err.note(note.clone());
4043 }
4044
4045 err.span_note(multi_span, msg);
4046 }
4047 showed = true;
4048 }
4049 showed
4050}
4051
4052#[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)]
4053struct UsePlacementFinder {
4054 target_module: NodeId,
4055 first_legal_span: Option<Span>,
4056 first_use_span: Option<Span>,
4057}
4058
4059impl UsePlacementFinder {
4060 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
4061 let mut finder =
4062 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
4063 finder.visit_crate(krate);
4064 if let Some(use_span) = finder.first_use_span {
4065 (Some(use_span), FoundUse::Yes)
4066 } else {
4067 (finder.first_legal_span, FoundUse::No)
4068 }
4069 }
4070}
4071
4072impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
4073 fn visit_crate(&mut self, c: &Crate) {
4074 if self.target_module == CRATE_NODE_ID {
4075 let inject = c.spans.inject_use_span;
4076 if is_span_suitable_for_use_injection(inject) {
4077 self.first_legal_span = Some(inject);
4078 }
4079 self.first_use_span = search_for_any_use_in_items(&c.items);
4080 } else {
4081 visit::walk_crate(self, c);
4082 }
4083 }
4084
4085 fn visit_item(&mut self, item: &'tcx ast::Item) {
4086 if self.target_module == item.id {
4087 if let ItemKind::Mod(_, _, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
4088 let inject = mod_spans.inject_use_span;
4089 if is_span_suitable_for_use_injection(inject) {
4090 self.first_legal_span = Some(inject);
4091 }
4092 self.first_use_span = search_for_any_use_in_items(items);
4093 }
4094 } else {
4095 visit::walk_item(self, item);
4096 }
4097 }
4098}
4099
4100#[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)]
4101struct BindingVisitor {
4102 identifiers: Vec<Symbol>,
4103 spans: FxHashMap<Symbol, Vec<Span>>,
4104}
4105
4106impl<'tcx> Visitor<'tcx> for BindingVisitor {
4107 fn visit_pat(&mut self, pat: &ast::Pat) {
4108 if let ast::PatKind::Ident(_, ident, _) = pat.kind {
4109 self.identifiers.push(ident.name);
4110 self.spans.entry(ident.name).or_default().push(ident.span);
4111 }
4112 visit::walk_pat(self, pat);
4113 }
4114}
4115
4116fn search_for_any_use_in_items(items: &[Box<ast::Item>]) -> Option<Span> {
4117 for item in items {
4118 if let ItemKind::Use(..) = item.kind
4119 && is_span_suitable_for_use_injection(item.span)
4120 {
4121 let mut lo = item.span.lo();
4122 for attr in &item.attrs {
4123 if attr.span.eq_ctxt(item.span) {
4124 lo = std::cmp::min(lo, attr.span.lo());
4125 }
4126 }
4127 return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
4128 }
4129 }
4130 None
4131}
4132
4133fn is_span_suitable_for_use_injection(s: Span) -> bool {
4134 !s.from_expansion()
4137}
4138
4139#[derive(#[automatically_derived]
impl ::core::fmt::Debug for OnUnknownData {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "OnUnknownData",
"directive", &&self.directive)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for OnUnknownData {
#[inline]
fn clone(&self) -> OnUnknownData {
OnUnknownData {
directive: ::core::clone::Clone::clone(&self.directive),
}
}
}Clone, #[automatically_derived]
impl ::core::default::Default for OnUnknownData {
#[inline]
fn default() -> OnUnknownData {
OnUnknownData { directive: ::core::default::Default::default() }
}
}Default)]
4140pub(crate) struct OnUnknownData {
4141 pub(crate) directive: Box<Directive>,
4142}
4143
4144impl OnUnknownData {
4145 pub(crate) fn from_attrs(
4146 r: &Resolver<'_, '_>,
4147 attrs: &[ast::Attribute],
4148 ) -> Option<OnUnknownData> {
4149 if r.features.diagnostic_on_unknown()
4150 && let Some(Attribute::Parsed(AttributeKind::OnUnknown { directive, .. })) =
4151 AttributeParser::parse_limited(
4152 r.tcx.sess,
4153 attrs,
4154 &[sym::diagnostic, sym::on_unknown],
4155 )
4156 {
4157 Some(Self { directive: directive? })
4158 } else {
4159 None
4160 }
4161 }
4162}