1use std::borrow::Cow;
4use std::iter;
5use std::ops::Deref;
6
7use rustc_ast::ptr::P;
8use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt, Visitor, walk_ty};
9use rustc_ast::{
10 self as ast, AssocItemKind, DUMMY_NODE_ID, Expr, ExprKind, GenericParam, GenericParamKind,
11 Item, ItemKind, MethodCall, NodeId, Path, PathSegment, Ty, TyKind,
12};
13use rustc_ast_pretty::pprust::where_bound_predicate_to_string;
14use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
15use rustc_errors::codes::*;
16use rustc_errors::{
17 Applicability, Diag, ErrorGuaranteed, MultiSpan, SuggestionStyle, pluralize,
18 struct_span_code_err,
19};
20use rustc_hir as hir;
21use rustc_hir::def::Namespace::{self, *};
22use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
23use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
24use rustc_hir::{MissingLifetimeKind, PrimTy};
25use rustc_middle::ty;
26use rustc_session::{Session, lint};
27use rustc_span::edit_distance::{edit_distance, find_best_match_for_name};
28use rustc_span::edition::Edition;
29use rustc_span::hygiene::MacroKind;
30use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
31use thin_vec::ThinVec;
32use tracing::debug;
33
34use super::NoConstantGenericsReason;
35use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
36use crate::late::{
37 AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind,
38 LifetimeUseSet, QSelf, RibKind,
39};
40use crate::ty::fast_reject::SimplifiedType;
41use crate::{
42 Module, ModuleKind, ModuleOrUniformRoot, PathResult, PathSource, Segment, errors,
43 path_names_to_string,
44};
45
46type Res = def::Res<ast::NodeId>;
47
48enum AssocSuggestion {
50 Field(Span),
51 MethodWithSelf { called: bool },
52 AssocFn { called: bool },
53 AssocType,
54 AssocConst,
55}
56
57impl AssocSuggestion {
58 fn action(&self) -> &'static str {
59 match self {
60 AssocSuggestion::Field(_) => "use the available field",
61 AssocSuggestion::MethodWithSelf { called: true } => {
62 "call the method with the fully-qualified path"
63 }
64 AssocSuggestion::MethodWithSelf { called: false } => {
65 "refer to the method with the fully-qualified path"
66 }
67 AssocSuggestion::AssocFn { called: true } => "call the associated function",
68 AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
69 AssocSuggestion::AssocConst => "use the associated `const`",
70 AssocSuggestion::AssocType => "use the associated type",
71 }
72 }
73}
74
75fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
76 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
77}
78
79fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
80 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
81}
82
83fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
85 let variant_path = &suggestion.path;
86 let variant_path_string = path_names_to_string(variant_path);
87
88 let path_len = suggestion.path.segments.len();
89 let enum_path = ast::Path {
90 span: suggestion.path.span,
91 segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
92 tokens: None,
93 };
94 let enum_path_string = path_names_to_string(&enum_path);
95
96 (variant_path_string, enum_path_string)
97}
98
99#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
101pub(super) struct MissingLifetime {
102 pub id: NodeId,
104 pub id_for_lint: NodeId,
111 pub span: Span,
113 pub kind: MissingLifetimeKind,
115 pub count: usize,
117}
118
119#[derive(Clone, Debug)]
122pub(super) struct ElisionFnParameter {
123 pub index: usize,
125 pub ident: Option<Ident>,
127 pub lifetime_count: usize,
129 pub span: Span,
131}
132
133#[derive(Debug)]
136pub(super) enum LifetimeElisionCandidate {
137 Ignore,
139 Named,
141 Missing(MissingLifetime),
142}
143
144#[derive(Debug)]
146struct BaseError {
147 msg: String,
148 fallback_label: String,
149 span: Span,
150 span_label: Option<(Span, &'static str)>,
151 could_be_expr: bool,
152 suggestion: Option<(Span, &'static str, String)>,
153 module: Option<DefId>,
154}
155
156#[derive(Debug)]
157enum TypoCandidate {
158 Typo(TypoSuggestion),
159 Shadowed(Res, Option<Span>),
160 None,
161}
162
163impl TypoCandidate {
164 fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
165 match self {
166 TypoCandidate::Typo(sugg) => Some(sugg),
167 TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
168 }
169 }
170}
171
172impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
173 fn make_base_error(
174 &mut self,
175 path: &[Segment],
176 span: Span,
177 source: PathSource<'_>,
178 res: Option<Res>,
179 ) -> BaseError {
180 let mut expected = source.descr_expected();
182 let path_str = Segment::names_to_string(path);
183 let item_str = path.last().unwrap().ident;
184 if let Some(res) = res {
185 BaseError {
186 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
187 fallback_label: format!("not a {expected}"),
188 span,
189 span_label: match res {
190 Res::Def(DefKind::TyParam, def_id) => {
191 Some((self.r.def_span(def_id), "found this type parameter"))
192 }
193 _ => None,
194 },
195 could_be_expr: match res {
196 Res::Def(DefKind::Fn, _) => {
197 self.r
199 .tcx
200 .sess
201 .source_map()
202 .span_to_snippet(span)
203 .is_ok_and(|snippet| snippet.ends_with(')'))
204 }
205 Res::Def(
206 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
207 _,
208 )
209 | Res::SelfCtor(_)
210 | Res::PrimTy(_)
211 | Res::Local(_) => true,
212 _ => false,
213 },
214 suggestion: None,
215 module: None,
216 }
217 } else {
218 let mut span_label = None;
219 let item_ident = path.last().unwrap().ident;
220 let item_span = item_ident.span;
221 let (mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
222 debug!(?self.diag_metadata.current_impl_items);
223 debug!(?self.diag_metadata.current_function);
224 let suggestion = if self.current_trait_ref.is_none()
225 && let Some((fn_kind, _)) = self.diag_metadata.current_function
226 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
227 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = fn_kind
228 && let Some(items) = self.diag_metadata.current_impl_items
229 && let Some(item) = items.iter().find(|i| {
230 i.kind.ident().is_some_and(|ident| {
231 ident.name == item_str.name && !sig.span.contains(item_span)
233 })
234 }) {
235 let sp = item_span.shrink_to_lo();
236
237 let field = match source {
240 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
241 expr.fields.iter().find(|f| f.ident == item_ident)
242 }
243 _ => None,
244 };
245 let pre = if let Some(field) = field
246 && field.is_shorthand
247 {
248 format!("{item_ident}: ")
249 } else {
250 String::new()
251 };
252 let is_call = match field {
255 Some(ast::ExprField { expr, .. }) => {
256 matches!(expr.kind, ExprKind::Call(..))
257 }
258 _ => matches!(
259 source,
260 PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
261 ),
262 };
263
264 match &item.kind {
265 AssocItemKind::Fn(fn_)
266 if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
267 {
268 span_label = Some((
272 fn_.ident.span,
273 "a method by that name is available on `Self` here",
274 ));
275 None
276 }
277 AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
278 span_label = Some((
279 fn_.ident.span,
280 "an associated function by that name is available on `Self` here",
281 ));
282 None
283 }
284 AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
285 Some((sp, "consider using the method on `Self`", format!("{pre}self.")))
286 }
287 AssocItemKind::Fn(_) => Some((
288 sp,
289 "consider using the associated function on `Self`",
290 format!("{pre}Self::"),
291 )),
292 AssocItemKind::Const(..) => Some((
293 sp,
294 "consider using the associated constant on `Self`",
295 format!("{pre}Self::"),
296 )),
297 _ => None,
298 }
299 } else {
300 None
301 };
302 (String::new(), "this scope".to_string(), None, suggestion)
303 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
304 if self.r.tcx.sess.edition() > Edition::Edition2015 {
305 expected = "crate";
308 (String::new(), "the list of imported crates".to_string(), None, None)
309 } else {
310 (
311 String::new(),
312 "the crate root".to_string(),
313 Some(CRATE_DEF_ID.to_def_id()),
314 None,
315 )
316 }
317 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
318 (String::new(), "the crate root".to_string(), Some(CRATE_DEF_ID.to_def_id()), None)
319 } else {
320 let mod_path = &path[..path.len() - 1];
321 let mod_res = self.resolve_path(mod_path, Some(TypeNS), None);
322 let mod_prefix = match mod_res {
323 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
324 _ => None,
325 };
326
327 let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
328
329 let mod_prefix =
330 mod_prefix.map_or_else(String::new, |res| (format!("{} ", res.descr())));
331
332 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), module_did, None)
333 };
334
335 let (fallback_label, suggestion) = if path_str == "async"
336 && expected.starts_with("struct")
337 {
338 ("`async` blocks are only allowed in Rust 2018 or later".to_string(), suggestion)
339 } else {
340 let override_suggestion =
342 if ["true", "false"].contains(&item_str.to_string().to_lowercase().as_str()) {
343 let item_typo = item_str.to_string().to_lowercase();
344 Some((item_span, "you may want to use a bool value instead", item_typo))
345 } else if item_str.as_str() == "printf" {
348 Some((
349 item_span,
350 "you may have meant to use the `print` macro",
351 "print!".to_owned(),
352 ))
353 } else {
354 suggestion
355 };
356 (format!("not found in {mod_str}"), override_suggestion)
357 };
358
359 BaseError {
360 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
361 fallback_label,
362 span: item_span,
363 span_label,
364 could_be_expr: false,
365 suggestion,
366 module,
367 }
368 }
369 }
370
371 pub(crate) fn smart_resolve_partial_mod_path_errors(
379 &mut self,
380 prefix_path: &[Segment],
381 following_seg: Option<&Segment>,
382 ) -> Vec<ImportSuggestion> {
383 if let Some(segment) = prefix_path.last()
384 && let Some(following_seg) = following_seg
385 {
386 let candidates = self.r.lookup_import_candidates(
387 segment.ident,
388 Namespace::TypeNS,
389 &self.parent_scope,
390 &|res: Res| matches!(res, Res::Def(DefKind::Mod, _)),
391 );
392 candidates
394 .into_iter()
395 .filter(|candidate| {
396 if let Some(def_id) = candidate.did
397 && let Some(module) = self.r.get_module(def_id)
398 {
399 Some(def_id) != self.parent_scope.module.opt_def_id()
400 && self
401 .r
402 .resolutions(module)
403 .borrow()
404 .iter()
405 .any(|(key, _r)| key.ident.name == following_seg.ident.name)
406 } else {
407 false
408 }
409 })
410 .collect::<Vec<_>>()
411 } else {
412 Vec::new()
413 }
414 }
415
416 pub(crate) fn smart_resolve_report_errors(
419 &mut self,
420 path: &[Segment],
421 following_seg: Option<&Segment>,
422 span: Span,
423 source: PathSource<'_>,
424 res: Option<Res>,
425 qself: Option<&QSelf>,
426 ) -> (Diag<'tcx>, Vec<ImportSuggestion>) {
427 debug!(?res, ?source);
428 let base_error = self.make_base_error(path, span, source, res);
429
430 let code = source.error_code(res.is_some());
431 let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
432 err.code(code);
433
434 if let Some(within_macro_span) =
437 base_error.span.within_macro(span, self.r.tcx.sess.source_map())
438 {
439 err.span_label(within_macro_span, "due to this macro variable");
440 }
441
442 self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
443 self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
444 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
445
446 if let Some((span, label)) = base_error.span_label {
447 err.span_label(span, label);
448 }
449
450 if let Some(ref sugg) = base_error.suggestion {
451 err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
452 }
453
454 self.suggest_changing_type_to_const_param(&mut err, res, source, span);
455 self.explain_functions_in_pattern(&mut err, res, source);
456
457 if self.suggest_pattern_match_with_let(&mut err, source, span) {
458 err.span_label(base_error.span, base_error.fallback_label);
460 return (err, Vec::new());
461 }
462
463 self.suggest_self_or_self_ref(&mut err, path, span);
464 self.detect_assoc_type_constraint_meant_as_path(&mut err, &base_error);
465 self.detect_rtn_with_fully_qualified_path(
466 &mut err,
467 path,
468 following_seg,
469 span,
470 source,
471 res,
472 qself,
473 );
474 if self.suggest_self_ty(&mut err, source, path, span)
475 || self.suggest_self_value(&mut err, source, path, span)
476 {
477 return (err, Vec::new());
478 }
479
480 let (found, suggested_candidates, mut candidates) = self.try_lookup_name_relaxed(
481 &mut err,
482 source,
483 path,
484 following_seg,
485 span,
486 res,
487 &base_error,
488 );
489 if found {
490 return (err, candidates);
491 }
492
493 if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
494 candidates.clear();
496 }
497
498 let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
499 fallback |= self.suggest_typo(
500 &mut err,
501 source,
502 path,
503 following_seg,
504 span,
505 &base_error,
506 suggested_candidates,
507 );
508
509 if fallback {
510 err.span_label(base_error.span, base_error.fallback_label);
512 }
513 self.err_code_special_cases(&mut err, source, path, span);
514
515 if let Some(module) = base_error.module {
516 self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
517 }
518
519 (err, candidates)
520 }
521
522 fn detect_rtn_with_fully_qualified_path(
523 &self,
524 err: &mut Diag<'_>,
525 path: &[Segment],
526 following_seg: Option<&Segment>,
527 span: Span,
528 source: PathSource<'_>,
529 res: Option<Res>,
530 qself: Option<&QSelf>,
531 ) {
532 if let Some(Res::Def(DefKind::AssocFn, _)) = res
533 && let PathSource::TraitItem(TypeNS) = source
534 && let None = following_seg
535 && let Some(qself) = qself
536 && let TyKind::Path(None, ty_path) = &qself.ty.kind
537 && ty_path.segments.len() == 1
538 && self.diag_metadata.current_where_predicate.is_some()
539 {
540 err.span_suggestion_verbose(
541 span,
542 "you might have meant to use the return type notation syntax",
543 format!("{}::{}(..)", ty_path.segments[0].ident, path[path.len() - 1].ident),
544 Applicability::MaybeIncorrect,
545 );
546 }
547 }
548
549 fn detect_assoc_type_constraint_meant_as_path(
550 &self,
551 err: &mut Diag<'_>,
552 base_error: &BaseError,
553 ) {
554 let Some(ty) = self.diag_metadata.current_type_path else {
555 return;
556 };
557 let TyKind::Path(_, path) = &ty.kind else {
558 return;
559 };
560 for segment in &path.segments {
561 let Some(params) = &segment.args else {
562 continue;
563 };
564 let ast::GenericArgs::AngleBracketed(params) = params.deref() else {
565 continue;
566 };
567 for param in ¶ms.args {
568 let ast::AngleBracketedArg::Constraint(constraint) = param else {
569 continue;
570 };
571 let ast::AssocItemConstraintKind::Bound { bounds } = &constraint.kind else {
572 continue;
573 };
574 for bound in bounds {
575 let ast::GenericBound::Trait(trait_ref) = bound else {
576 continue;
577 };
578 if trait_ref.modifiers == ast::TraitBoundModifiers::NONE
579 && base_error.span == trait_ref.span
580 {
581 err.span_suggestion_verbose(
582 constraint.ident.span.between(trait_ref.span),
583 "you might have meant to write a path instead of an associated type bound",
584 "::",
585 Applicability::MachineApplicable,
586 );
587 }
588 }
589 }
590 }
591 }
592
593 fn suggest_self_or_self_ref(&mut self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
594 if !self.self_type_is_available() {
595 return;
596 }
597 let Some(path_last_segment) = path.last() else { return };
598 let item_str = path_last_segment.ident;
599 if ["this", "my"].contains(&item_str.as_str()) {
601 err.span_suggestion_short(
602 span,
603 "you might have meant to use `self` here instead",
604 "self",
605 Applicability::MaybeIncorrect,
606 );
607 if !self.self_value_is_available(path[0].ident.span) {
608 if let Some((FnKind::Fn(_, _, ast::Fn { sig, .. }), fn_span)) =
609 &self.diag_metadata.current_function
610 {
611 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
612 (param.span.shrink_to_lo(), "&self, ")
613 } else {
614 (
615 self.r
616 .tcx
617 .sess
618 .source_map()
619 .span_through_char(*fn_span, '(')
620 .shrink_to_hi(),
621 "&self",
622 )
623 };
624 err.span_suggestion_verbose(
625 span,
626 "if you meant to use `self`, you are also missing a `self` receiver \
627 argument",
628 sugg,
629 Applicability::MaybeIncorrect,
630 );
631 }
632 }
633 }
634 }
635
636 fn try_lookup_name_relaxed(
637 &mut self,
638 err: &mut Diag<'_>,
639 source: PathSource<'_>,
640 path: &[Segment],
641 following_seg: Option<&Segment>,
642 span: Span,
643 res: Option<Res>,
644 base_error: &BaseError,
645 ) -> (bool, FxHashSet<String>, Vec<ImportSuggestion>) {
646 let span = match following_seg {
647 Some(_) if path[0].ident.span.eq_ctxt(path[path.len() - 1].ident.span) => {
648 path[0].ident.span.to(path[path.len() - 1].ident.span)
651 }
652 _ => span,
653 };
654 let mut suggested_candidates = FxHashSet::default();
655 let ident = path.last().unwrap().ident;
657 let is_expected = &|res| source.is_expected(res);
658 let ns = source.namespace();
659 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
660 let path_str = Segment::names_to_string(path);
661 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
662 let mut candidates = self
663 .r
664 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
665 .into_iter()
666 .filter(|ImportSuggestion { did, .. }| {
667 match (did, res.and_then(|res| res.opt_def_id())) {
668 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
669 _ => true,
670 }
671 })
672 .collect::<Vec<_>>();
673 let intrinsic_candidates: Vec<_> = candidates
676 .extract_if(.., |sugg| {
677 let path = path_names_to_string(&sugg.path);
678 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
679 })
680 .collect();
681 if candidates.is_empty() {
682 candidates = intrinsic_candidates;
684 }
685 let crate_def_id = CRATE_DEF_ID.to_def_id();
686 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
687 let mut enum_candidates: Vec<_> = self
688 .r
689 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
690 .into_iter()
691 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
692 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
693 .collect();
694 if !enum_candidates.is_empty() {
695 enum_candidates.sort();
696
697 let preamble = if res.is_none() {
700 let others = match enum_candidates.len() {
701 1 => String::new(),
702 2 => " and 1 other".to_owned(),
703 n => format!(" and {n} others"),
704 };
705 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
706 } else {
707 String::new()
708 };
709 let msg = format!("{preamble}try using the variant's enum");
710
711 suggested_candidates.extend(
712 enum_candidates
713 .iter()
714 .map(|(_variant_path, enum_ty_path)| enum_ty_path.clone()),
715 );
716 err.span_suggestions(
717 span,
718 msg,
719 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
720 Applicability::MachineApplicable,
721 );
722 }
723 }
724
725 let typo_sugg = self
727 .lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
728 .to_opt_suggestion()
729 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
730 if let [segment] = path
731 && !matches!(source, PathSource::Delegation)
732 && self.self_type_is_available()
733 {
734 if let Some(candidate) =
735 self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
736 {
737 let self_is_available = self.self_value_is_available(segment.ident.span);
738 let pre = match source {
741 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
742 if expr
743 .fields
744 .iter()
745 .any(|f| f.ident == segment.ident && f.is_shorthand) =>
746 {
747 format!("{path_str}: ")
748 }
749 _ => String::new(),
750 };
751 match candidate {
752 AssocSuggestion::Field(field_span) => {
753 if self_is_available {
754 err.span_suggestion_verbose(
755 span.shrink_to_lo(),
756 "you might have meant to use the available field",
757 format!("{pre}self."),
758 Applicability::MachineApplicable,
759 );
760 } else {
761 err.span_label(field_span, "a field by that name exists in `Self`");
762 }
763 }
764 AssocSuggestion::MethodWithSelf { called } if self_is_available => {
765 let msg = if called {
766 "you might have meant to call the method"
767 } else {
768 "you might have meant to refer to the method"
769 };
770 err.span_suggestion_verbose(
771 span.shrink_to_lo(),
772 msg,
773 "self.",
774 Applicability::MachineApplicable,
775 );
776 }
777 AssocSuggestion::MethodWithSelf { .. }
778 | AssocSuggestion::AssocFn { .. }
779 | AssocSuggestion::AssocConst
780 | AssocSuggestion::AssocType => {
781 err.span_suggestion_verbose(
782 span.shrink_to_lo(),
783 format!("you might have meant to {}", candidate.action()),
784 "Self::",
785 Applicability::MachineApplicable,
786 );
787 }
788 }
789 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
790 return (true, suggested_candidates, candidates);
791 }
792
793 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
795 let mut args_snippet = String::new();
796 if let Some(args_span) = args_span {
797 if let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span) {
798 args_snippet = snippet;
799 }
800 }
801
802 err.span_suggestion(
803 call_span,
804 format!("try calling `{ident}` as a method"),
805 format!("self.{path_str}({args_snippet})"),
806 Applicability::MachineApplicable,
807 );
808 return (true, suggested_candidates, candidates);
809 }
810 }
811
812 if let Some(res) = res {
814 if self.smart_resolve_context_dependent_help(
815 err,
816 span,
817 source,
818 path,
819 res,
820 &path_str,
821 &base_error.fallback_label,
822 ) {
823 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
825 return (true, suggested_candidates, candidates);
826 }
827 }
828
829 if let Some(rib) = &self.last_block_rib
831 && let RibKind::Normal = rib.kind
832 {
833 for (ident, &res) in &rib.bindings {
834 if let Res::Local(_) = res
835 && path.len() == 1
836 && ident.span.eq_ctxt(path[0].ident.span)
837 && ident.name == path[0].ident.name
838 {
839 err.span_help(
840 ident.span,
841 format!("the binding `{path_str}` is available in a different scope in the same function"),
842 );
843 return (true, suggested_candidates, candidates);
844 }
845 }
846 }
847
848 if candidates.is_empty() {
849 candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
850 }
851
852 (false, suggested_candidates, candidates)
853 }
854
855 fn suggest_trait_and_bounds(
856 &mut self,
857 err: &mut Diag<'_>,
858 source: PathSource<'_>,
859 res: Option<Res>,
860 span: Span,
861 base_error: &BaseError,
862 ) -> bool {
863 let is_macro =
864 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
865 let mut fallback = false;
866
867 if let (
868 PathSource::Trait(AliasPossibility::Maybe),
869 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
870 false,
871 ) = (source, res, is_macro)
872 {
873 if let Some(bounds @ [first_bound, .., last_bound]) =
874 self.diag_metadata.current_trait_object
875 {
876 fallback = true;
877 let spans: Vec<Span> = bounds
878 .iter()
879 .map(|bound| bound.span())
880 .filter(|&sp| sp != base_error.span)
881 .collect();
882
883 let start_span = first_bound.span();
884 let end_span = last_bound.span();
886 let last_bound_span = spans.last().cloned().unwrap();
888 let mut multi_span: MultiSpan = spans.clone().into();
889 for sp in spans {
890 let msg = if sp == last_bound_span {
891 format!(
892 "...because of {these} bound{s}",
893 these = pluralize!("this", bounds.len() - 1),
894 s = pluralize!(bounds.len() - 1),
895 )
896 } else {
897 String::new()
898 };
899 multi_span.push_span_label(sp, msg);
900 }
901 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
902 err.span_help(
903 multi_span,
904 "`+` is used to constrain a \"trait object\" type with lifetimes or \
905 auto-traits; structs and enums can't be bound in that way",
906 );
907 if bounds.iter().all(|bound| match bound {
908 ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
909 ast::GenericBound::Trait(tr) => tr.span == base_error.span,
910 }) {
911 let mut sugg = vec![];
912 if base_error.span != start_span {
913 sugg.push((start_span.until(base_error.span), String::new()));
914 }
915 if base_error.span != end_span {
916 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
917 }
918
919 err.multipart_suggestion(
920 "if you meant to use a type and not a trait here, remove the bounds",
921 sugg,
922 Applicability::MaybeIncorrect,
923 );
924 }
925 }
926 }
927
928 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
929 fallback
930 }
931
932 fn suggest_typo(
933 &mut self,
934 err: &mut Diag<'_>,
935 source: PathSource<'_>,
936 path: &[Segment],
937 following_seg: Option<&Segment>,
938 span: Span,
939 base_error: &BaseError,
940 suggested_candidates: FxHashSet<String>,
941 ) -> bool {
942 let is_expected = &|res| source.is_expected(res);
943 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
944 let typo_sugg =
945 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
946 let mut fallback = false;
947 let typo_sugg = typo_sugg
948 .to_opt_suggestion()
949 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
950 if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
951 fallback = true;
952 match self.diag_metadata.current_let_binding {
953 Some((pat_sp, Some(ty_sp), None))
954 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
955 {
956 err.span_suggestion_short(
957 pat_sp.between(ty_sp),
958 "use `=` if you meant to assign",
959 " = ",
960 Applicability::MaybeIncorrect,
961 );
962 }
963 _ => {}
964 }
965
966 let suggestion = self.get_single_associated_item(path, &source, is_expected);
968 self.r.add_typo_suggestion(err, suggestion, ident_span);
969 }
970
971 if self.let_binding_suggestion(err, ident_span) {
972 fallback = false;
973 }
974
975 fallback
976 }
977
978 fn suggest_shadowed(
979 &mut self,
980 err: &mut Diag<'_>,
981 source: PathSource<'_>,
982 path: &[Segment],
983 following_seg: Option<&Segment>,
984 span: Span,
985 ) -> bool {
986 let is_expected = &|res| source.is_expected(res);
987 let typo_sugg =
988 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
989 let is_in_same_file = &|sp1, sp2| {
990 let source_map = self.r.tcx.sess.source_map();
991 let file1 = source_map.span_to_filename(sp1);
992 let file2 = source_map.span_to_filename(sp2);
993 file1 == file2
994 };
995 if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1000 && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1001 {
1002 err.span_label(
1003 sugg_span,
1004 format!("you might have meant to refer to this {}", res.descr()),
1005 );
1006 return true;
1007 }
1008 false
1009 }
1010
1011 fn err_code_special_cases(
1012 &mut self,
1013 err: &mut Diag<'_>,
1014 source: PathSource<'_>,
1015 path: &[Segment],
1016 span: Span,
1017 ) {
1018 if let Some(err_code) = err.code {
1019 if err_code == E0425 {
1020 for label_rib in &self.label_ribs {
1021 for (label_ident, node_id) in &label_rib.bindings {
1022 let ident = path.last().unwrap().ident;
1023 if format!("'{ident}") == label_ident.to_string() {
1024 err.span_label(label_ident.span, "a label with a similar name exists");
1025 if let PathSource::Expr(Some(Expr {
1026 kind: ExprKind::Break(None, Some(_)),
1027 ..
1028 })) = source
1029 {
1030 err.span_suggestion(
1031 span,
1032 "use the similarly named label",
1033 label_ident.name,
1034 Applicability::MaybeIncorrect,
1035 );
1036 self.diag_metadata.unused_labels.swap_remove(node_id);
1038 }
1039 }
1040 }
1041 }
1042 } else if err_code == E0412 {
1043 if let Some(correct) = Self::likely_rust_type(path) {
1044 err.span_suggestion(
1045 span,
1046 "perhaps you intended to use this type",
1047 correct,
1048 Applicability::MaybeIncorrect,
1049 );
1050 }
1051 }
1052 }
1053 }
1054
1055 fn suggest_self_ty(
1057 &mut self,
1058 err: &mut Diag<'_>,
1059 source: PathSource<'_>,
1060 path: &[Segment],
1061 span: Span,
1062 ) -> bool {
1063 if !is_self_type(path, source.namespace()) {
1064 return false;
1065 }
1066 err.code(E0411);
1067 err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1068 if let Some(item) = self.diag_metadata.current_item {
1069 if let Some(ident) = item.kind.ident() {
1070 err.span_label(
1071 ident.span,
1072 format!("`Self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1073 );
1074 }
1075 }
1076 true
1077 }
1078
1079 fn suggest_self_value(
1080 &mut self,
1081 err: &mut Diag<'_>,
1082 source: PathSource<'_>,
1083 path: &[Segment],
1084 span: Span,
1085 ) -> bool {
1086 if !is_self_value(path, source.namespace()) {
1087 return false;
1088 }
1089
1090 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
1091 err.code(E0424);
1092 err.span_label(
1093 span,
1094 match source {
1095 PathSource::Pat => {
1096 "`self` value is a keyword and may not be bound to variables or shadowed"
1097 }
1098 _ => "`self` value is a keyword only available in methods with a `self` parameter",
1099 },
1100 );
1101 let is_assoc_fn = self.self_type_is_available();
1102 let self_from_macro = "a `self` parameter, but a macro invocation can only \
1103 access identifiers it receives from parameters";
1104 if let Some((fn_kind, span)) = &self.diag_metadata.current_function {
1105 if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1109 err.span_label(*span, format!("this function has {self_from_macro}"));
1110 } else {
1111 let doesnt = if is_assoc_fn {
1112 let (span, sugg) = fn_kind
1113 .decl()
1114 .inputs
1115 .get(0)
1116 .map(|p| (p.span.shrink_to_lo(), "&self, "))
1117 .unwrap_or_else(|| {
1118 let span = fn_kind
1121 .ident()
1122 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
1123 (
1124 self.r
1125 .tcx
1126 .sess
1127 .source_map()
1128 .span_through_char(span, '(')
1129 .shrink_to_hi(),
1130 "&self",
1131 )
1132 });
1133 err.span_suggestion_verbose(
1134 span,
1135 "add a `self` receiver parameter to make the associated `fn` a method",
1136 sugg,
1137 Applicability::MaybeIncorrect,
1138 );
1139 "doesn't"
1140 } else {
1141 "can't"
1142 };
1143 if let Some(ident) = fn_kind.ident() {
1144 err.span_label(
1145 ident.span,
1146 format!("this function {doesnt} have a `self` parameter"),
1147 );
1148 }
1149 }
1150 } else if let Some(item) = self.diag_metadata.current_item {
1151 if matches!(item.kind, ItemKind::Delegation(..)) {
1152 err.span_label(item.span, format!("delegation supports {self_from_macro}"));
1153 } else {
1154 let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1155 err.span_label(
1156 span,
1157 format!("`self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1158 );
1159 }
1160 }
1161 true
1162 }
1163
1164 fn detect_missing_binding_available_from_pattern(
1165 &mut self,
1166 err: &mut Diag<'_>,
1167 path: &[Segment],
1168 following_seg: Option<&Segment>,
1169 ) {
1170 let [segment] = path else { return };
1171 let None = following_seg else { return };
1172 for rib in self.ribs[ValueNS].iter().rev() {
1173 let patterns_with_skipped_bindings = self.r.tcx.with_stable_hashing_context(|hcx| {
1174 rib.patterns_with_skipped_bindings.to_sorted(&hcx, true)
1175 });
1176 for (def_id, spans) in patterns_with_skipped_bindings {
1177 if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1178 && let Some(fields) = self.r.field_idents(*def_id)
1179 {
1180 for field in fields {
1181 if field.name == segment.ident.name {
1182 if spans.iter().all(|(_, had_error)| had_error.is_err()) {
1183 let multispan: MultiSpan =
1186 spans.iter().map(|(s, _)| *s).collect::<Vec<_>>().into();
1187 err.span_note(
1188 multispan,
1189 "this pattern had a recovered parse error which likely lost \
1190 the expected fields",
1191 );
1192 err.downgrade_to_delayed_bug();
1193 }
1194 let ty = self.r.tcx.item_name(*def_id);
1195 for (span, _) in spans {
1196 err.span_label(
1197 *span,
1198 format!(
1199 "this pattern doesn't include `{field}`, which is \
1200 available in `{ty}`",
1201 ),
1202 );
1203 }
1204 }
1205 }
1206 }
1207 }
1208 }
1209 }
1210
1211 fn suggest_at_operator_in_slice_pat_with_range(
1212 &mut self,
1213 err: &mut Diag<'_>,
1214 path: &[Segment],
1215 ) {
1216 let Some(pat) = self.diag_metadata.current_pat else { return };
1217 let (bound, side, range) = match &pat.kind {
1218 ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1219 ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1220 _ => return,
1221 };
1222 if let ExprKind::Path(None, range_path) = &bound.kind
1223 && let [segment] = &range_path.segments[..]
1224 && let [s] = path
1225 && segment.ident == s.ident
1226 && segment.ident.span.eq_ctxt(range.span)
1227 {
1228 let (span, snippet) = match side {
1231 Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
1232 Side::End => (range.span.to(segment.ident.span), format!("{} @ ..", segment.ident)),
1233 };
1234 err.subdiagnostic(errors::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1235 span,
1236 ident: segment.ident,
1237 snippet,
1238 });
1239 }
1240
1241 enum Side {
1242 Start,
1243 End,
1244 }
1245 }
1246
1247 fn suggest_swapping_misplaced_self_ty_and_trait(
1248 &mut self,
1249 err: &mut Diag<'_>,
1250 source: PathSource<'_>,
1251 res: Option<Res>,
1252 span: Span,
1253 ) {
1254 if let Some((trait_ref, self_ty)) =
1255 self.diag_metadata.currently_processing_impl_trait.clone()
1256 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
1257 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1258 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
1259 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
1260 && trait_ref.path.span == span
1261 && let PathSource::Trait(_) = source
1262 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
1263 && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
1264 && let Ok(trait_ref_str) =
1265 self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
1266 {
1267 err.multipart_suggestion(
1268 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
1269 vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
1270 Applicability::MaybeIncorrect,
1271 );
1272 }
1273 }
1274
1275 fn explain_functions_in_pattern(
1276 &mut self,
1277 err: &mut Diag<'_>,
1278 res: Option<Res>,
1279 source: PathSource<'_>,
1280 ) {
1281 let PathSource::TupleStruct(_, _) = source else { return };
1282 let Some(Res::Def(DefKind::Fn, _)) = res else { return };
1283 err.primary_message("expected a pattern, found a function call");
1284 err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
1285 }
1286
1287 fn suggest_changing_type_to_const_param(
1288 &mut self,
1289 err: &mut Diag<'_>,
1290 res: Option<Res>,
1291 source: PathSource<'_>,
1292 span: Span,
1293 ) {
1294 let PathSource::Trait(_) = source else { return };
1295
1296 let applicability = match res {
1298 Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
1299 Applicability::MachineApplicable
1300 }
1301 Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
1305 if self.r.tcx.features().adt_const_params() =>
1306 {
1307 Applicability::MaybeIncorrect
1308 }
1309 _ => return,
1310 };
1311
1312 let Some(item) = self.diag_metadata.current_item else { return };
1313 let Some(generics) = item.kind.generics() else { return };
1314
1315 let param = generics.params.iter().find_map(|param| {
1316 if let [bound] = &*param.bounds
1318 && let ast::GenericBound::Trait(tref) = bound
1319 && tref.modifiers == ast::TraitBoundModifiers::NONE
1320 && tref.span == span
1321 && param.ident.span.eq_ctxt(span)
1322 {
1323 Some(param.ident.span)
1324 } else {
1325 None
1326 }
1327 });
1328
1329 if let Some(param) = param {
1330 err.subdiagnostic(errors::UnexpectedResChangeTyToConstParamSugg {
1331 span: param.shrink_to_lo(),
1332 applicability,
1333 });
1334 }
1335 }
1336
1337 fn suggest_pattern_match_with_let(
1338 &mut self,
1339 err: &mut Diag<'_>,
1340 source: PathSource<'_>,
1341 span: Span,
1342 ) -> bool {
1343 if let PathSource::Expr(_) = source
1344 && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
1345 self.diag_metadata.in_if_condition
1346 {
1347 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
1351 err.span_suggestion_verbose(
1352 expr_span.shrink_to_lo(),
1353 "you might have meant to use pattern matching",
1354 "let ",
1355 Applicability::MaybeIncorrect,
1356 );
1357 return true;
1358 }
1359 }
1360 false
1361 }
1362
1363 fn get_single_associated_item(
1364 &mut self,
1365 path: &[Segment],
1366 source: &PathSource<'_>,
1367 filter_fn: &impl Fn(Res) -> bool,
1368 ) -> Option<TypoSuggestion> {
1369 if let crate::PathSource::TraitItem(_) = source {
1370 let mod_path = &path[..path.len() - 1];
1371 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1372 self.resolve_path(mod_path, None, None)
1373 {
1374 let resolutions = self.r.resolutions(module).borrow();
1375 let targets: Vec<_> =
1376 resolutions
1377 .iter()
1378 .filter_map(|(key, resolution)| {
1379 resolution.borrow().binding.map(|binding| binding.res()).and_then(
1380 |res| if filter_fn(res) { Some((key, res)) } else { None },
1381 )
1382 })
1383 .collect();
1384 if let [target] = targets.as_slice() {
1385 return Some(TypoSuggestion::single_item_from_ident(target.0.ident, target.1));
1386 }
1387 }
1388 }
1389 None
1390 }
1391
1392 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diag<'_>) -> bool {
1394 let (bounded_ty, bounds, where_span) = if let Some(ast::WherePredicate {
1396 kind:
1397 ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
1398 bounded_ty,
1399 bound_generic_params,
1400 bounds,
1401 }),
1402 span,
1403 ..
1404 }) = self.diag_metadata.current_where_predicate
1405 {
1406 if !bound_generic_params.is_empty() {
1407 return false;
1408 }
1409 (bounded_ty, bounds, span)
1410 } else {
1411 return false;
1412 };
1413
1414 let (ty, _, path) = if let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind {
1416 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
1418 return false;
1419 };
1420 if !matches!(
1421 partial_res.full_res(),
1422 Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _))
1423 ) {
1424 return false;
1425 }
1426 (&qself.ty, qself.position, path)
1427 } else {
1428 return false;
1429 };
1430
1431 let peeled_ty = ty.peel_refs();
1432 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
1433 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1435 return false;
1436 };
1437 if !matches!(
1438 partial_res.full_res(),
1439 Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _))
1440 ) {
1441 return false;
1442 }
1443 if let (
1444 [ast::PathSegment { args: None, .. }],
1445 [ast::GenericBound::Trait(poly_trait_ref)],
1446 ) = (&type_param_path.segments[..], &bounds[..])
1447 && poly_trait_ref.modifiers == ast::TraitBoundModifiers::NONE
1448 {
1449 if let [ast::PathSegment { ident, args: None, .. }] =
1450 &poly_trait_ref.trait_ref.path.segments[..]
1451 {
1452 if ident.span == span {
1453 let Some(new_where_bound_predicate) =
1454 mk_where_bound_predicate(path, poly_trait_ref, ty)
1455 else {
1456 return false;
1457 };
1458 err.span_suggestion_verbose(
1459 *where_span,
1460 format!("constrain the associated type to `{ident}`"),
1461 where_bound_predicate_to_string(&new_where_bound_predicate),
1462 Applicability::MaybeIncorrect,
1463 );
1464 }
1465 return true;
1466 }
1467 }
1468 }
1469 false
1470 }
1471
1472 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
1475 let mut has_self_arg = None;
1476 if let PathSource::Expr(Some(parent)) = source
1477 && let ExprKind::Call(_, args) = &parent.kind
1478 && !args.is_empty()
1479 {
1480 let mut expr_kind = &args[0].kind;
1481 loop {
1482 match expr_kind {
1483 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1484 if arg_name.segments[0].ident.name == kw::SelfLower {
1485 let call_span = parent.span;
1486 let tail_args_span = if args.len() > 1 {
1487 Some(Span::new(
1488 args[1].span.lo(),
1489 args.last().unwrap().span.hi(),
1490 call_span.ctxt(),
1491 None,
1492 ))
1493 } else {
1494 None
1495 };
1496 has_self_arg = Some((call_span, tail_args_span));
1497 }
1498 break;
1499 }
1500 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1501 _ => break,
1502 }
1503 }
1504 }
1505 has_self_arg
1506 }
1507
1508 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1509 let sm = self.r.tcx.sess.source_map();
1514 if let Some(followed_brace_span) = sm.span_look_ahead(span, "{", Some(50)) {
1515 let close_brace_span = sm.span_look_ahead(followed_brace_span, "}", Some(50));
1518 let closing_brace = close_brace_span.map(|sp| span.to(sp));
1519 (true, closing_brace)
1520 } else {
1521 (false, None)
1522 }
1523 }
1524
1525 fn smart_resolve_context_dependent_help(
1529 &mut self,
1530 err: &mut Diag<'_>,
1531 span: Span,
1532 source: PathSource<'_>,
1533 path: &[Segment],
1534 res: Res,
1535 path_str: &str,
1536 fallback_label: &str,
1537 ) -> bool {
1538 let ns = source.namespace();
1539 let is_expected = &|res| source.is_expected(res);
1540
1541 let path_sep = |this: &mut Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
1542 const MESSAGE: &str = "use the path separator to refer to an item";
1543
1544 let (lhs_span, rhs_span) = match &expr.kind {
1545 ExprKind::Field(base, ident) => (base.span, ident.span),
1546 ExprKind::MethodCall(box MethodCall { receiver, span, .. }) => {
1547 (receiver.span, *span)
1548 }
1549 _ => return false,
1550 };
1551
1552 if lhs_span.eq_ctxt(rhs_span) {
1553 err.span_suggestion_verbose(
1554 lhs_span.between(rhs_span),
1555 MESSAGE,
1556 "::",
1557 Applicability::MaybeIncorrect,
1558 );
1559 true
1560 } else if matches!(kind, DefKind::Struct | DefKind::TyAlias)
1561 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
1562 && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
1563 {
1564 err.span_suggestion_verbose(
1568 lhs_source_span.until(rhs_span),
1569 MESSAGE,
1570 format!("<{snippet}>::"),
1571 Applicability::MaybeIncorrect,
1572 );
1573 true
1574 } else {
1575 false
1581 }
1582 };
1583
1584 let find_span = |source: &PathSource<'_>, err: &mut Diag<'_>| {
1585 match source {
1586 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1587 | PathSource::TupleStruct(span, _) => {
1588 err.span(*span);
1591 *span
1592 }
1593 _ => span,
1594 }
1595 };
1596
1597 let bad_struct_syntax_suggestion = |this: &mut Self, err: &mut Diag<'_>, def_id: DefId| {
1598 let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
1599
1600 match source {
1601 PathSource::Expr(Some(
1602 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1603 )) if path_sep(this, err, parent, DefKind::Struct) => {}
1604 PathSource::Expr(
1605 None
1606 | Some(Expr {
1607 kind:
1608 ExprKind::Path(..)
1609 | ExprKind::Binary(..)
1610 | ExprKind::Unary(..)
1611 | ExprKind::If(..)
1612 | ExprKind::While(..)
1613 | ExprKind::ForLoop { .. }
1614 | ExprKind::Match(..),
1615 ..
1616 }),
1617 ) if followed_by_brace => {
1618 if let Some(sp) = closing_brace {
1619 err.span_label(span, fallback_label.to_string());
1620 err.multipart_suggestion(
1621 "surround the struct literal with parentheses",
1622 vec![
1623 (sp.shrink_to_lo(), "(".to_string()),
1624 (sp.shrink_to_hi(), ")".to_string()),
1625 ],
1626 Applicability::MaybeIncorrect,
1627 );
1628 } else {
1629 err.span_label(
1630 span, format!(
1632 "you might want to surround a struct literal with parentheses: \
1633 `({path_str} {{ /* fields */ }})`?"
1634 ),
1635 );
1636 }
1637 }
1638 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1639 let span = find_span(&source, err);
1640 err.span_label(this.r.def_span(def_id), format!("`{path_str}` defined here"));
1641
1642 let (tail, descr, applicability, old_fields) = match source {
1643 PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
1644 PathSource::TupleStruct(_, args) => (
1645 "",
1646 "pattern",
1647 Applicability::MachineApplicable,
1648 Some(
1649 args.iter()
1650 .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
1651 .collect::<Vec<Option<String>>>(),
1652 ),
1653 ),
1654 _ => (": val", "literal", Applicability::HasPlaceholders, None),
1655 };
1656
1657 if !this.has_private_fields(def_id) {
1658 let fields = this.r.field_idents(def_id);
1661 let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
1662
1663 if let PathSource::Expr(Some(Expr {
1664 kind: ExprKind::Call(path, args),
1665 span,
1666 ..
1667 })) = source
1668 && !args.is_empty()
1669 && let Some(fields) = &fields
1670 && args.len() == fields.len()
1671 {
1673 let path_span = path.span;
1674 let mut parts = Vec::new();
1675
1676 parts.push((
1678 path_span.shrink_to_hi().until(args[0].span),
1679 "{".to_owned(),
1680 ));
1681
1682 for (field, arg) in fields.iter().zip(args.iter()) {
1683 parts.push((arg.span.shrink_to_lo(), format!("{}: ", field)));
1685 }
1686
1687 parts.push((
1689 args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
1690 "}".to_owned(),
1691 ));
1692
1693 err.multipart_suggestion_verbose(
1694 format!("use struct {descr} syntax instead of calling"),
1695 parts,
1696 applicability,
1697 );
1698 } else {
1699 let (fields, applicability) = match fields {
1700 Some(fields) => {
1701 let fields = if let Some(old_fields) = old_fields {
1702 fields
1703 .iter()
1704 .enumerate()
1705 .map(|(idx, new)| (new, old_fields.get(idx)))
1706 .map(|(new, old)| {
1707 if let Some(Some(old)) = old
1708 && new.as_str() != old
1709 {
1710 format!("{new}: {old}")
1711 } else {
1712 new.to_string()
1713 }
1714 })
1715 .collect::<Vec<String>>()
1716 } else {
1717 fields
1718 .iter()
1719 .map(|f| format!("{f}{tail}"))
1720 .collect::<Vec<String>>()
1721 };
1722
1723 (fields.join(", "), applicability)
1724 }
1725 None => {
1726 ("/* fields */".to_string(), Applicability::HasPlaceholders)
1727 }
1728 };
1729 let pad = if has_fields { " " } else { "" };
1730 err.span_suggestion(
1731 span,
1732 format!("use struct {descr} syntax instead"),
1733 format!("{path_str} {{{pad}{fields}{pad}}}"),
1734 applicability,
1735 );
1736 }
1737 }
1738 if let PathSource::Expr(Some(Expr {
1739 kind: ExprKind::Call(path, args),
1740 span: call_span,
1741 ..
1742 })) = source
1743 {
1744 this.suggest_alternative_construction_methods(
1745 def_id,
1746 err,
1747 path.span,
1748 *call_span,
1749 &args[..],
1750 );
1751 }
1752 }
1753 _ => {
1754 err.span_label(span, fallback_label.to_string());
1755 }
1756 }
1757 };
1758
1759 match (res, source) {
1760 (
1761 Res::Def(DefKind::Macro(MacroKind::Bang), def_id),
1762 PathSource::Expr(Some(Expr {
1763 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1764 }))
1765 | PathSource::Struct,
1766 ) => {
1767 let suggestable = def_id.is_local()
1769 || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
1770
1771 err.span_label(span, fallback_label.to_string());
1772
1773 if path
1775 .last()
1776 .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
1777 && suggestable
1778 {
1779 err.span_suggestion_verbose(
1780 span.shrink_to_hi(),
1781 "use `!` to invoke the macro",
1782 "!",
1783 Applicability::MaybeIncorrect,
1784 );
1785 }
1786
1787 if path_str == "try" && span.is_rust_2015() {
1788 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1789 }
1790 }
1791 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1792 err.span_label(span, fallback_label.to_string());
1793 }
1794 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1795 err.span_label(span, "type aliases cannot be used as traits");
1796 if self.r.tcx.sess.is_nightly_build() {
1797 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1798 `type` alias";
1799 let span = self.r.def_span(def_id);
1800 if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
1801 let snip = snip.replacen("type", "trait", 1);
1804 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1805 } else {
1806 err.span_help(span, msg);
1807 }
1808 }
1809 }
1810 (
1811 Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
1812 PathSource::Expr(Some(parent)),
1813 ) if path_sep(self, err, parent, kind) => {
1814 return true;
1815 }
1816 (
1817 Res::Def(DefKind::Enum, def_id),
1818 PathSource::TupleStruct(..) | PathSource::Expr(..),
1819 ) => {
1820 self.suggest_using_enum_variant(err, source, def_id, span);
1821 }
1822 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1823 let struct_ctor = match def_id.as_local() {
1824 Some(def_id) => self.r.struct_constructors.get(&def_id).cloned(),
1825 None => {
1826 let ctor = self.r.cstore().ctor_untracked(def_id);
1827 ctor.map(|(ctor_kind, ctor_def_id)| {
1828 let ctor_res =
1829 Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1830 let ctor_vis = self.r.tcx.visibility(ctor_def_id);
1831 let field_visibilities = self
1832 .r
1833 .tcx
1834 .associated_item_def_ids(def_id)
1835 .iter()
1836 .map(|field_id| self.r.tcx.visibility(field_id))
1837 .collect();
1838 (ctor_res, ctor_vis, field_visibilities)
1839 })
1840 }
1841 };
1842
1843 let (ctor_def, ctor_vis, fields) = if let Some(struct_ctor) = struct_ctor {
1844 if let PathSource::Expr(Some(parent)) = source {
1845 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1846 bad_struct_syntax_suggestion(self, err, def_id);
1847 return true;
1848 }
1849 }
1850 struct_ctor
1851 } else {
1852 bad_struct_syntax_suggestion(self, err, def_id);
1853 return true;
1854 };
1855
1856 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1857 if !is_expected(ctor_def) || is_accessible {
1858 return true;
1859 }
1860
1861 let field_spans = match source {
1862 PathSource::TupleStruct(_, pattern_spans) => {
1864 err.primary_message(
1865 "cannot match against a tuple struct which contains private fields",
1866 );
1867
1868 Some(Vec::from(pattern_spans))
1870 }
1871 PathSource::Expr(Some(Expr {
1873 kind: ExprKind::Call(path, args),
1874 span: call_span,
1875 ..
1876 })) => {
1877 err.primary_message(
1878 "cannot initialize a tuple struct which contains private fields",
1879 );
1880 self.suggest_alternative_construction_methods(
1881 def_id,
1882 err,
1883 path.span,
1884 *call_span,
1885 &args[..],
1886 );
1887 self.r
1889 .field_idents(def_id)
1890 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1891 }
1892 _ => None,
1893 };
1894
1895 if let Some(spans) =
1896 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1897 {
1898 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1899 .filter(|(vis, _)| {
1900 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1901 })
1902 .map(|(_, span)| *span)
1903 .collect();
1904
1905 if non_visible_spans.len() > 0 {
1906 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
1907 err.multipart_suggestion_verbose(
1908 format!(
1909 "consider making the field{} publicly accessible",
1910 pluralize!(fields.len())
1911 ),
1912 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
1913 Applicability::MaybeIncorrect,
1914 );
1915 }
1916
1917 let mut m: MultiSpan = non_visible_spans.clone().into();
1918 non_visible_spans
1919 .into_iter()
1920 .for_each(|s| m.push_span_label(s, "private field"));
1921 err.span_note(m, "constructor is not visible here due to private fields");
1922 }
1923
1924 return true;
1925 }
1926
1927 err.span_label(span, "constructor is not visible here due to private fields");
1928 }
1929 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
1930 bad_struct_syntax_suggestion(self, err, def_id);
1931 }
1932 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1933 match source {
1934 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1935 let span = find_span(&source, err);
1936 err.span_label(
1937 self.r.def_span(def_id),
1938 format!("`{path_str}` defined here"),
1939 );
1940 err.span_suggestion(
1941 span,
1942 "use this syntax instead",
1943 path_str,
1944 Applicability::MaybeIncorrect,
1945 );
1946 }
1947 _ => return false,
1948 }
1949 }
1950 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
1951 let def_id = self.r.tcx.parent(ctor_def_id);
1952 err.span_label(self.r.def_span(def_id), format!("`{path_str}` defined here"));
1953 let fields = self.r.field_idents(def_id).map_or_else(
1954 || "/* fields */".to_string(),
1955 |field_ids| vec!["_"; field_ids.len()].join(", "),
1956 );
1957 err.span_suggestion(
1958 span,
1959 "use the tuple variant pattern syntax instead",
1960 format!("{path_str}({fields})"),
1961 Applicability::HasPlaceholders,
1962 );
1963 }
1964 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
1965 err.span_label(span, fallback_label.to_string());
1966 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1967 }
1968 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1969 err.note("can't use a type alias as a constructor");
1970 }
1971 _ => return false,
1972 }
1973 true
1974 }
1975
1976 fn suggest_alternative_construction_methods(
1977 &mut self,
1978 def_id: DefId,
1979 err: &mut Diag<'_>,
1980 path_span: Span,
1981 call_span: Span,
1982 args: &[P<Expr>],
1983 ) {
1984 if def_id.is_local() {
1985 return;
1987 }
1988 let mut items = self
1991 .r
1992 .tcx
1993 .inherent_impls(def_id)
1994 .iter()
1995 .flat_map(|i| self.r.tcx.associated_items(i).in_definition_order())
1996 .filter(|item| item.is_fn() && !item.is_method())
1998 .filter_map(|item| {
1999 let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2001 let ret_ty = fn_sig.output().skip_binder();
2003 let ty::Adt(def, _args) = ret_ty.kind() else {
2004 return None;
2005 };
2006 let input_len = fn_sig.inputs().skip_binder().len();
2007 if def.did() != def_id {
2008 return None;
2009 }
2010 let name = item.name();
2011 let order = !name.as_str().starts_with("new");
2012 Some((order, name, input_len))
2013 })
2014 .collect::<Vec<_>>();
2015 items.sort_by_key(|(order, _, _)| *order);
2016 let suggestion = |name, args| {
2017 format!(
2018 "::{name}({})",
2019 std::iter::repeat("_").take(args).collect::<Vec<_>>().join(", ")
2020 )
2021 };
2022 match &items[..] {
2023 [] => {}
2024 [(_, name, len)] if *len == args.len() => {
2025 err.span_suggestion_verbose(
2026 path_span.shrink_to_hi(),
2027 format!("you might have meant to use the `{name}` associated function",),
2028 format!("::{name}"),
2029 Applicability::MaybeIncorrect,
2030 );
2031 }
2032 [(_, name, len)] => {
2033 err.span_suggestion_verbose(
2034 path_span.shrink_to_hi().with_hi(call_span.hi()),
2035 format!("you might have meant to use the `{name}` associated function",),
2036 suggestion(name, *len),
2037 Applicability::MaybeIncorrect,
2038 );
2039 }
2040 _ => {
2041 err.span_suggestions_with_style(
2042 path_span.shrink_to_hi().with_hi(call_span.hi()),
2043 "you might have meant to use an associated function to build this type",
2044 items.iter().map(|(_, name, len)| suggestion(name, *len)),
2045 Applicability::MaybeIncorrect,
2046 SuggestionStyle::ShowAlways,
2047 );
2048 }
2049 }
2050 let default_trait = self
2058 .r
2059 .lookup_import_candidates(
2060 Ident::with_dummy_span(sym::Default),
2061 Namespace::TypeNS,
2062 &self.parent_scope,
2063 &|res: Res| matches!(res, Res::Def(DefKind::Trait, _)),
2064 )
2065 .iter()
2066 .filter_map(|candidate| candidate.did)
2067 .find(|did| {
2068 self.r
2069 .tcx
2070 .get_attrs(*did, sym::rustc_diagnostic_item)
2071 .any(|attr| attr.value_str() == Some(sym::Default))
2072 });
2073 let Some(default_trait) = default_trait else {
2074 return;
2075 };
2076 if self
2077 .r
2078 .extern_crate_map
2079 .items()
2080 .flat_map(|(_, crate_)| self.r.tcx.implementations_of_trait((*crate_, default_trait)))
2082 .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2083 .filter_map(|simplified_self_ty| match simplified_self_ty {
2084 SimplifiedType::Adt(did) => Some(did),
2085 _ => None,
2086 })
2087 .any(|did| did == def_id)
2088 {
2089 err.multipart_suggestion(
2090 "consider using the `Default` trait",
2091 vec![
2092 (path_span.shrink_to_lo(), "<".to_string()),
2093 (
2094 path_span.shrink_to_hi().with_hi(call_span.hi()),
2095 " as std::default::Default>::default()".to_string(),
2096 ),
2097 ],
2098 Applicability::MaybeIncorrect,
2099 );
2100 }
2101 }
2102
2103 fn has_private_fields(&self, def_id: DefId) -> bool {
2104 let fields = match def_id.as_local() {
2105 Some(def_id) => self.r.struct_constructors.get(&def_id).cloned().map(|(_, _, f)| f),
2106 None => Some(
2107 self.r
2108 .tcx
2109 .associated_item_def_ids(def_id)
2110 .iter()
2111 .map(|field_id| self.r.tcx.visibility(field_id))
2112 .collect(),
2113 ),
2114 };
2115
2116 fields.is_some_and(|fields| {
2117 fields.iter().any(|vis| !self.r.is_accessible_from(*vis, self.parent_scope.module))
2118 })
2119 }
2120
2121 pub(crate) fn find_similarly_named_assoc_item(
2124 &mut self,
2125 ident: Symbol,
2126 kind: &AssocItemKind,
2127 ) -> Option<Symbol> {
2128 let (module, _) = self.current_trait_ref.as_ref()?;
2129 if ident == kw::Underscore {
2130 return None;
2132 }
2133
2134 let resolutions = self.r.resolutions(*module);
2135 let targets = resolutions
2136 .borrow()
2137 .iter()
2138 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
2139 .filter(|(_, res)| match (kind, res) {
2140 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
2141 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2142 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2143 (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2144 _ => false,
2145 })
2146 .map(|(key, _)| key.ident.name)
2147 .collect::<Vec<_>>();
2148
2149 find_best_match_for_name(&targets, ident, None)
2150 }
2151
2152 fn lookup_assoc_candidate<FilterFn>(
2153 &mut self,
2154 ident: Ident,
2155 ns: Namespace,
2156 filter_fn: FilterFn,
2157 called: bool,
2158 ) -> Option<AssocSuggestion>
2159 where
2160 FilterFn: Fn(Res) -> bool,
2161 {
2162 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2163 match t.kind {
2164 TyKind::Path(None, _) => Some(t.id),
2165 TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2166 _ => None,
2170 }
2171 }
2172 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2174 if let Some(node_id) =
2175 self.diag_metadata.current_self_type.as_ref().and_then(extract_node_id)
2176 {
2177 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
2179 if let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) =
2180 resolution.full_res()
2181 {
2182 if let Some(fields) = self.r.field_idents(did) {
2183 if let Some(field) = fields.iter().find(|id| ident.name == id.name) {
2184 return Some(AssocSuggestion::Field(field.span));
2185 }
2186 }
2187 }
2188 }
2189 }
2190 }
2191
2192 if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2193 for assoc_item in items {
2194 if let Some(assoc_ident) = assoc_item.kind.ident()
2195 && assoc_ident == ident
2196 {
2197 return Some(match &assoc_item.kind {
2198 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2199 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
2200 AssocSuggestion::MethodWithSelf { called }
2201 }
2202 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2203 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2204 ast::AssocItemKind::Delegation(..)
2205 if self
2206 .r
2207 .delegation_fn_sigs
2208 .get(&self.r.local_def_id(assoc_item.id))
2209 .is_some_and(|sig| sig.has_self) =>
2210 {
2211 AssocSuggestion::MethodWithSelf { called }
2212 }
2213 ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2214 ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2215 continue;
2216 }
2217 });
2218 }
2219 }
2220 }
2221
2222 if let Some((module, _)) = self.current_trait_ref {
2224 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
2225 ModuleOrUniformRoot::Module(module),
2226 ident,
2227 ns,
2228 &self.parent_scope,
2229 None,
2230 ) {
2231 let res = binding.res();
2232 if filter_fn(res) {
2233 match res {
2234 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2235 let has_self = match def_id.as_local() {
2236 Some(def_id) => self
2237 .r
2238 .delegation_fn_sigs
2239 .get(&def_id)
2240 .is_some_and(|sig| sig.has_self),
2241 None => {
2242 self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2243 matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2244 })
2245 }
2246 };
2247 if has_self {
2248 return Some(AssocSuggestion::MethodWithSelf { called });
2249 } else {
2250 return Some(AssocSuggestion::AssocFn { called });
2251 }
2252 }
2253 Res::Def(DefKind::AssocConst, _) => {
2254 return Some(AssocSuggestion::AssocConst);
2255 }
2256 Res::Def(DefKind::AssocTy, _) => {
2257 return Some(AssocSuggestion::AssocType);
2258 }
2259 _ => {}
2260 }
2261 }
2262 }
2263 }
2264
2265 None
2266 }
2267
2268 fn lookup_typo_candidate(
2269 &mut self,
2270 path: &[Segment],
2271 following_seg: Option<&Segment>,
2272 ns: Namespace,
2273 filter_fn: &impl Fn(Res) -> bool,
2274 ) -> TypoCandidate {
2275 let mut names = Vec::new();
2276 if let [segment] = path {
2277 let mut ctxt = segment.ident.span.ctxt();
2278
2279 for rib in self.ribs[ns].iter().rev() {
2282 let rib_ctxt = if rib.kind.contains_params() {
2283 ctxt.normalize_to_macros_2_0()
2284 } else {
2285 ctxt.normalize_to_macro_rules()
2286 };
2287
2288 for (ident, &res) in &rib.bindings {
2290 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2291 names.push(TypoSuggestion::typo_from_ident(*ident, res));
2292 }
2293 }
2294
2295 if let RibKind::MacroDefinition(def) = rib.kind
2296 && def == self.r.macro_def(ctxt)
2297 {
2298 ctxt.remove_mark();
2301 continue;
2302 }
2303
2304 if let RibKind::Module(module) = rib.kind {
2306 self.r.add_module_candidates(module, &mut names, &filter_fn, Some(ctxt));
2308
2309 if let ModuleKind::Block = module.kind {
2310 } else {
2312 if !module.no_implicit_prelude {
2314 let extern_prelude = self.r.extern_prelude.clone();
2315 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
2316 self.r
2317 .crate_loader(|c| c.maybe_process_path_extern(ident.name))
2318 .and_then(|crate_id| {
2319 let crate_mod =
2320 Res::Def(DefKind::Mod, crate_id.as_def_id());
2321
2322 filter_fn(crate_mod).then(|| {
2323 TypoSuggestion::typo_from_ident(*ident, crate_mod)
2324 })
2325 })
2326 }));
2327
2328 if let Some(prelude) = self.r.prelude {
2329 self.r.add_module_candidates(prelude, &mut names, &filter_fn, None);
2330 }
2331 }
2332 break;
2333 }
2334 }
2335 }
2336 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
2338 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
2339 TypoSuggestion::typo_from_name(prim_ty.name(), Res::PrimTy(*prim_ty))
2340 }))
2341 }
2342 } else {
2343 let mod_path = &path[..path.len() - 1];
2345 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2346 self.resolve_path(mod_path, Some(TypeNS), None)
2347 {
2348 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2349 }
2350 }
2351
2352 if let Some(following_seg) = following_seg {
2354 names.retain(|suggestion| match suggestion.res {
2355 Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2356 suggestion.candidate != following_seg.ident.name
2358 }
2359 Res::Def(DefKind::Mod, def_id) => self.r.get_module(def_id).map_or_else(
2360 || false,
2361 |module| {
2362 self.r
2363 .resolutions(module)
2364 .borrow()
2365 .iter()
2366 .any(|(key, _)| key.ident.name == following_seg.ident.name)
2367 },
2368 ),
2369 _ => true,
2370 });
2371 }
2372 let name = path[path.len() - 1].ident.name;
2373 names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2375
2376 match find_best_match_for_name(
2377 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2378 name,
2379 None,
2380 ) {
2381 Some(found) => {
2382 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2383 else {
2384 return TypoCandidate::None;
2385 };
2386 if found == name {
2387 TypoCandidate::Shadowed(sugg.res, sugg.span)
2388 } else {
2389 TypoCandidate::Typo(sugg)
2390 }
2391 }
2392 _ => TypoCandidate::None,
2393 }
2394 }
2395
2396 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
2399 let name = path[path.len() - 1].ident.as_str();
2400 Some(match name {
2402 "byte" => sym::u8, "short" => sym::i16,
2404 "Bool" => sym::bool,
2405 "Boolean" => sym::bool,
2406 "boolean" => sym::bool,
2407 "int" => sym::i32,
2408 "long" => sym::i64,
2409 "float" => sym::f32,
2410 "double" => sym::f64,
2411 _ => return None,
2412 })
2413 }
2414
2415 fn let_binding_suggestion(&mut self, err: &mut Diag<'_>, ident_span: Span) -> bool {
2418 if ident_span.from_expansion() {
2419 return false;
2420 }
2421
2422 if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
2424 && let ast::ExprKind::Path(None, ref path) = lhs.kind
2425 && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
2426 {
2427 let (span, text) = match path.segments.first() {
2428 Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
2429 let name = name.strip_prefix('_').unwrap_or(name);
2431 (ident_span, format!("let {name}"))
2432 }
2433 _ => (ident_span.shrink_to_lo(), "let ".to_string()),
2434 };
2435
2436 err.span_suggestion_verbose(
2437 span,
2438 "you might have meant to introduce a new binding",
2439 text,
2440 Applicability::MaybeIncorrect,
2441 );
2442 return true;
2443 }
2444
2445 if err.code == Some(E0423)
2448 && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
2449 && val_span.contains(ident_span)
2450 && val_span.lo() == ident_span.lo()
2451 {
2452 err.span_suggestion_verbose(
2453 let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
2454 "you might have meant to use `:` for type annotation",
2455 ": ",
2456 Applicability::MaybeIncorrect,
2457 );
2458 return true;
2459 }
2460 false
2461 }
2462
2463 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
2464 let mut result = None;
2465 let mut seen_modules = FxHashSet::default();
2466 let root_did = self.r.graph_root.def_id();
2467 let mut worklist = vec![(
2468 self.r.graph_root,
2469 ThinVec::new(),
2470 root_did.is_local() || !self.r.tcx.is_doc_hidden(root_did),
2471 )];
2472
2473 while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
2474 if result.is_some() {
2476 break;
2477 }
2478
2479 in_module.for_each_child(self.r, |r, ident, _, name_binding| {
2480 if result.is_some() || !name_binding.vis.is_visible_locally() {
2482 return;
2483 }
2484 if let Some(module) = name_binding.module() {
2485 let mut path_segments = path_segments.clone();
2487 path_segments.push(ast::PathSegment::from_ident(ident));
2488 let module_def_id = module.def_id();
2489 let doc_visible = doc_visible
2490 && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
2491 if module_def_id == def_id {
2492 let path =
2493 Path { span: name_binding.span, segments: path_segments, tokens: None };
2494 result = Some((
2495 module,
2496 ImportSuggestion {
2497 did: Some(def_id),
2498 descr: "module",
2499 path,
2500 accessible: true,
2501 doc_visible,
2502 note: None,
2503 via_import: false,
2504 },
2505 ));
2506 } else {
2507 if seen_modules.insert(module_def_id) {
2509 worklist.push((module, path_segments, doc_visible));
2510 }
2511 }
2512 }
2513 });
2514 }
2515
2516 result
2517 }
2518
2519 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
2520 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
2521 let mut variants = Vec::new();
2522 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
2523 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
2524 let mut segms = enum_import_suggestion.path.segments.clone();
2525 segms.push(ast::PathSegment::from_ident(ident));
2526 let path = Path { span: name_binding.span, segments: segms, tokens: None };
2527 variants.push((path, def_id, kind));
2528 }
2529 });
2530 variants
2531 })
2532 }
2533
2534 fn suggest_using_enum_variant(
2536 &mut self,
2537 err: &mut Diag<'_>,
2538 source: PathSource<'_>,
2539 def_id: DefId,
2540 span: Span,
2541 ) {
2542 let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
2543 err.note("you might have meant to use one of the enum's variants");
2544 return;
2545 };
2546
2547 let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
2552 PathSource::TupleStruct(..) => (None, true),
2554 PathSource::Expr(Some(expr)) => match &expr.kind {
2555 ExprKind::Call(..) => (None, true),
2557 ExprKind::MethodCall(box MethodCall {
2560 receiver,
2561 span,
2562 seg: PathSegment { ident, .. },
2563 ..
2564 }) => {
2565 let dot_span = receiver.span.between(*span);
2566 let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
2567 *ctor_kind == CtorKind::Fn
2568 && path.segments.last().is_some_and(|seg| seg.ident == *ident)
2569 });
2570 (found_tuple_variant.then_some(dot_span), false)
2571 }
2572 ExprKind::Field(base, ident) => {
2575 let dot_span = base.span.between(ident.span);
2576 let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
2577 path.segments.last().is_some_and(|seg| seg.ident == *ident)
2578 });
2579 (found_tuple_or_unit_variant.then_some(dot_span), false)
2580 }
2581 _ => (None, false),
2582 },
2583 _ => (None, false),
2584 };
2585
2586 if let Some(dot_span) = suggest_path_sep_dot_span {
2587 err.span_suggestion_verbose(
2588 dot_span,
2589 "use the path separator to refer to a variant",
2590 "::",
2591 Applicability::MaybeIncorrect,
2592 );
2593 } else if suggest_only_tuple_variants {
2594 let mut suggestable_variants = variant_ctors
2597 .iter()
2598 .filter(|(.., kind)| *kind == CtorKind::Fn)
2599 .map(|(variant, ..)| path_names_to_string(variant))
2600 .collect::<Vec<_>>();
2601 suggestable_variants.sort();
2602
2603 let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
2604
2605 let source_msg = if matches!(source, PathSource::TupleStruct(..)) {
2606 "to match against"
2607 } else {
2608 "to construct"
2609 };
2610
2611 if !suggestable_variants.is_empty() {
2612 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
2613 format!("try {source_msg} the enum's variant")
2614 } else {
2615 format!("try {source_msg} one of the enum's variants")
2616 };
2617
2618 err.span_suggestions(
2619 span,
2620 msg,
2621 suggestable_variants,
2622 Applicability::MaybeIncorrect,
2623 );
2624 }
2625
2626 if non_suggestable_variant_count == variant_ctors.len() {
2628 err.help(format!("the enum has no tuple variants {source_msg}"));
2629 }
2630
2631 if non_suggestable_variant_count == 1 {
2633 err.help(format!("you might have meant {source_msg} the enum's non-tuple variant"));
2634 } else if non_suggestable_variant_count >= 1 {
2635 err.help(format!(
2636 "you might have meant {source_msg} one of the enum's non-tuple variants"
2637 ));
2638 }
2639 } else {
2640 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
2641 let def_id = self.r.tcx.parent(ctor_def_id);
2642 match kind {
2643 CtorKind::Const => false,
2644 CtorKind::Fn => {
2645 !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
2646 }
2647 }
2648 };
2649
2650 let mut suggestable_variants = variant_ctors
2651 .iter()
2652 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
2653 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
2654 .map(|(variant, kind)| match kind {
2655 CtorKind::Const => variant,
2656 CtorKind::Fn => format!("({variant}())"),
2657 })
2658 .collect::<Vec<_>>();
2659 suggestable_variants.sort();
2660 let no_suggestable_variant = suggestable_variants.is_empty();
2661
2662 if !no_suggestable_variant {
2663 let msg = if suggestable_variants.len() == 1 {
2664 "you might have meant to use the following enum variant"
2665 } else {
2666 "you might have meant to use one of the following enum variants"
2667 };
2668
2669 err.span_suggestions(
2670 span,
2671 msg,
2672 suggestable_variants,
2673 Applicability::MaybeIncorrect,
2674 );
2675 }
2676
2677 let mut suggestable_variants_with_placeholders = variant_ctors
2678 .iter()
2679 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
2680 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
2681 .filter_map(|(variant, kind)| match kind {
2682 CtorKind::Fn => Some(format!("({variant}(/* fields */))")),
2683 _ => None,
2684 })
2685 .collect::<Vec<_>>();
2686 suggestable_variants_with_placeholders.sort();
2687
2688 if !suggestable_variants_with_placeholders.is_empty() {
2689 let msg =
2690 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
2691 (true, 1) => "the following enum variant is available",
2692 (true, _) => "the following enum variants are available",
2693 (false, 1) => "alternatively, the following enum variant is available",
2694 (false, _) => {
2695 "alternatively, the following enum variants are also available"
2696 }
2697 };
2698
2699 err.span_suggestions(
2700 span,
2701 msg,
2702 suggestable_variants_with_placeholders,
2703 Applicability::HasPlaceholders,
2704 );
2705 }
2706 };
2707
2708 if def_id.is_local() {
2709 err.span_note(self.r.def_span(def_id), "the enum is defined here");
2710 }
2711 }
2712
2713 pub(crate) fn suggest_adding_generic_parameter(
2714 &self,
2715 path: &[Segment],
2716 source: PathSource<'_>,
2717 ) -> Option<(Span, &'static str, String, Applicability)> {
2718 let (ident, span) = match path {
2719 [segment]
2720 if !segment.has_generic_args
2721 && segment.ident.name != kw::SelfUpper
2722 && segment.ident.name != kw::Dyn =>
2723 {
2724 (segment.ident.to_string(), segment.ident.span)
2725 }
2726 _ => return None,
2727 };
2728 let mut iter = ident.chars().map(|c| c.is_uppercase());
2729 let single_uppercase_char =
2730 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
2731 if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
2732 return None;
2733 }
2734 match (self.diag_metadata.current_item, single_uppercase_char, self.diag_metadata.currently_processing_generic_args) {
2735 (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
2736 }
2738 (
2739 Some(Item {
2740 kind:
2741 kind @ ItemKind::Fn(..)
2742 | kind @ ItemKind::Enum(..)
2743 | kind @ ItemKind::Struct(..)
2744 | kind @ ItemKind::Union(..),
2745 ..
2746 }),
2747 true, _
2748 )
2749 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
2751 | (Some(Item { kind, .. }), false, _) => {
2752 if let Some(generics) = kind.generics() {
2753 if span.overlaps(generics.span) {
2754 return None;
2763 }
2764
2765 let (msg, sugg) = match source {
2766 PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
2767 ("you might be missing a type parameter", ident)
2768 }
2769 PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
2770 "you might be missing a const parameter",
2771 format!("const {ident}: /* Type */"),
2772 ),
2773 _ => return None,
2774 };
2775 let (span, sugg) = if let [.., param] = &generics.params[..] {
2776 let span = if let [.., bound] = ¶m.bounds[..] {
2777 bound.span()
2778 } else if let GenericParam {
2779 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
2780 } = param {
2781 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
2782 } else {
2783 param.ident.span
2784 };
2785 (span, format!(", {sugg}"))
2786 } else {
2787 (generics.span, format!("<{sugg}>"))
2788 };
2789 if span.can_be_used_for_suggestions() {
2791 return Some((
2792 span.shrink_to_hi(),
2793 msg,
2794 sugg,
2795 Applicability::MaybeIncorrect,
2796 ));
2797 }
2798 }
2799 }
2800 _ => {}
2801 }
2802 None
2803 }
2804
2805 pub(crate) fn suggestion_for_label_in_rib(
2808 &self,
2809 rib_index: usize,
2810 label: Ident,
2811 ) -> Option<LabelSuggestion> {
2812 let within_scope = self.is_label_valid_from_rib(rib_index);
2814
2815 let rib = &self.label_ribs[rib_index];
2816 let names = rib
2817 .bindings
2818 .iter()
2819 .filter(|(id, _)| id.span.eq_ctxt(label.span))
2820 .map(|(id, _)| id.name)
2821 .collect::<Vec<Symbol>>();
2822
2823 find_best_match_for_name(&names, label.name, None).map(|symbol| {
2824 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
2828 (*ident, within_scope)
2829 })
2830 }
2831
2832 pub(crate) fn maybe_report_lifetime_uses(
2833 &mut self,
2834 generics_span: Span,
2835 params: &[ast::GenericParam],
2836 ) {
2837 for (param_index, param) in params.iter().enumerate() {
2838 let GenericParamKind::Lifetime = param.kind else { continue };
2839
2840 let def_id = self.r.local_def_id(param.id);
2841
2842 let use_set = self.lifetime_uses.remove(&def_id);
2843 debug!(
2844 "Use set for {:?}({:?} at {:?}) is {:?}",
2845 def_id, param.ident, param.ident.span, use_set
2846 );
2847
2848 let deletion_span = || {
2849 if params.len() == 1 {
2850 Some(generics_span)
2852 } else if param_index == 0 {
2853 match (
2856 param.span().find_ancestor_inside(generics_span),
2857 params[param_index + 1].span().find_ancestor_inside(generics_span),
2858 ) {
2859 (Some(param_span), Some(next_param_span)) => {
2860 Some(param_span.to(next_param_span.shrink_to_lo()))
2861 }
2862 _ => None,
2863 }
2864 } else {
2865 match (
2868 param.span().find_ancestor_inside(generics_span),
2869 params[param_index - 1].span().find_ancestor_inside(generics_span),
2870 ) {
2871 (Some(param_span), Some(prev_param_span)) => {
2872 Some(prev_param_span.shrink_to_hi().to(param_span))
2873 }
2874 _ => None,
2875 }
2876 }
2877 };
2878 match use_set {
2879 Some(LifetimeUseSet::Many) => {}
2880 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
2881 debug!(?param.ident, ?param.ident.span, ?use_span);
2882
2883 let elidable = matches!(use_ctxt, LifetimeCtxt::Ref);
2884 let deletion_span =
2885 if param.bounds.is_empty() { deletion_span() } else { None };
2886
2887 self.r.lint_buffer.buffer_lint(
2888 lint::builtin::SINGLE_USE_LIFETIMES,
2889 param.id,
2890 param.ident.span,
2891 lint::BuiltinLintDiag::SingleUseLifetime {
2892 param_span: param.ident.span,
2893 use_span: Some((use_span, elidable)),
2894 deletion_span,
2895 ident: param.ident,
2896 },
2897 );
2898 }
2899 None => {
2900 debug!(?param.ident, ?param.ident.span);
2901 let deletion_span = deletion_span();
2902
2903 if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
2905 self.r.lint_buffer.buffer_lint(
2906 lint::builtin::UNUSED_LIFETIMES,
2907 param.id,
2908 param.ident.span,
2909 lint::BuiltinLintDiag::SingleUseLifetime {
2910 param_span: param.ident.span,
2911 use_span: None,
2912 deletion_span,
2913 ident: param.ident,
2914 },
2915 );
2916 }
2917 }
2918 }
2919 }
2920 }
2921
2922 pub(crate) fn emit_undeclared_lifetime_error(
2923 &self,
2924 lifetime_ref: &ast::Lifetime,
2925 outer_lifetime_ref: Option<Ident>,
2926 ) {
2927 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
2928 let mut err = if let Some(outer) = outer_lifetime_ref {
2929 struct_span_code_err!(
2930 self.r.dcx(),
2931 lifetime_ref.ident.span,
2932 E0401,
2933 "can't use generic parameters from outer item",
2934 )
2935 .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
2936 .with_span_label(outer.span, "lifetime parameter from outer item")
2937 } else {
2938 struct_span_code_err!(
2939 self.r.dcx(),
2940 lifetime_ref.ident.span,
2941 E0261,
2942 "use of undeclared lifetime name `{}`",
2943 lifetime_ref.ident
2944 )
2945 .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
2946 };
2947
2948 if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
2950 err.span_suggestion_verbose(
2951 lifetime_ref.ident.span,
2952 "you may have misspelled the `'static` lifetime",
2953 "'static",
2954 Applicability::MachineApplicable,
2955 );
2956 } else {
2957 self.suggest_introducing_lifetime(
2958 &mut err,
2959 Some(lifetime_ref.ident.name.as_str()),
2960 |err, _, span, message, suggestion, span_suggs| {
2961 err.multipart_suggestion_with_style(
2962 message,
2963 std::iter::once((span, suggestion)).chain(span_suggs.clone()).collect(),
2964 Applicability::MaybeIncorrect,
2965 if span_suggs.is_empty() {
2966 SuggestionStyle::ShowCode
2967 } else {
2968 SuggestionStyle::ShowAlways
2969 },
2970 );
2971 true
2972 },
2973 );
2974 }
2975
2976 err.emit();
2977 }
2978
2979 fn suggest_introducing_lifetime(
2980 &self,
2981 err: &mut Diag<'_>,
2982 name: Option<&str>,
2983 suggest: impl Fn(
2984 &mut Diag<'_>,
2985 bool,
2986 Span,
2987 Cow<'static, str>,
2988 String,
2989 Vec<(Span, String)>,
2990 ) -> bool,
2991 ) {
2992 let mut suggest_note = true;
2993 for rib in self.lifetime_ribs.iter().rev() {
2994 let mut should_continue = true;
2995 match rib.kind {
2996 LifetimeRibKind::Generics { binder, span, kind } => {
2997 if let LifetimeBinderKind::ConstItem = kind
3000 && !self.r.tcx().features().generic_const_items()
3001 {
3002 continue;
3003 }
3004
3005 if !span.can_be_used_for_suggestions()
3006 && suggest_note
3007 && let Some(name) = name
3008 {
3009 suggest_note = false; err.span_label(
3011 span,
3012 format!(
3013 "lifetime `{name}` is missing in item created through this procedural macro",
3014 ),
3015 );
3016 continue;
3017 }
3018
3019 let higher_ranked = matches!(
3020 kind,
3021 LifetimeBinderKind::BareFnType
3022 | LifetimeBinderKind::PolyTrait
3023 | LifetimeBinderKind::WhereBound
3024 );
3025
3026 let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3027 let (span, sugg) = if span.is_empty() {
3028 let mut binder_idents: FxIndexSet<Ident> = Default::default();
3029 binder_idents.insert(Ident::from_str(name.unwrap_or("'a")));
3030
3031 if let LifetimeBinderKind::WhereBound = kind
3038 && let Some(predicate) = self.diag_metadata.current_where_predicate
3039 && let ast::WherePredicateKind::BoundPredicate(
3040 ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3041 ) = &predicate.kind
3042 && bounded_ty.id == binder
3043 {
3044 for bound in bounds {
3045 if let ast::GenericBound::Trait(poly_trait_ref) = bound
3046 && let span = poly_trait_ref
3047 .span
3048 .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3049 && !span.is_empty()
3050 {
3051 rm_inner_binders.insert(span);
3052 poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3053 binder_idents.insert(v.ident);
3054 });
3055 }
3056 }
3057 }
3058
3059 let binders_sugg = binder_idents.into_iter().enumerate().fold(
3060 "".to_string(),
3061 |mut binders, (i, x)| {
3062 if i != 0 {
3063 binders += ", ";
3064 }
3065 binders += x.as_str();
3066 binders
3067 },
3068 );
3069 let sugg = format!(
3070 "{}<{}>{}",
3071 if higher_ranked { "for" } else { "" },
3072 binders_sugg,
3073 if higher_ranked { " " } else { "" },
3074 );
3075 (span, sugg)
3076 } else {
3077 let span = self
3078 .r
3079 .tcx
3080 .sess
3081 .source_map()
3082 .span_through_char(span, '<')
3083 .shrink_to_hi();
3084 let sugg = format!("{}, ", name.unwrap_or("'a"));
3085 (span, sugg)
3086 };
3087
3088 if higher_ranked {
3089 let message = Cow::from(format!(
3090 "consider making the {} lifetime-generic with a new `{}` lifetime",
3091 kind.descr(),
3092 name.unwrap_or("'a"),
3093 ));
3094 should_continue = suggest(
3095 err,
3096 true,
3097 span,
3098 message,
3099 sugg,
3100 if !rm_inner_binders.is_empty() {
3101 rm_inner_binders
3102 .into_iter()
3103 .map(|v| (v, "".to_string()))
3104 .collect::<Vec<_>>()
3105 } else {
3106 vec![]
3107 },
3108 );
3109 err.note_once(
3110 "for more information on higher-ranked polymorphism, visit \
3111 https://doc.rust-lang.org/nomicon/hrtb.html",
3112 );
3113 } else if let Some(name) = name {
3114 let message =
3115 Cow::from(format!("consider introducing lifetime `{name}` here"));
3116 should_continue = suggest(err, false, span, message, sugg, vec![]);
3117 } else {
3118 let message = Cow::from("consider introducing a named lifetime parameter");
3119 should_continue = suggest(err, false, span, message, sugg, vec![]);
3120 }
3121 }
3122 LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
3123 _ => {}
3124 }
3125 if !should_continue {
3126 break;
3127 }
3128 }
3129 }
3130
3131 pub(crate) fn emit_non_static_lt_in_const_param_ty_error(&self, lifetime_ref: &ast::Lifetime) {
3132 self.r
3133 .dcx()
3134 .create_err(errors::ParamInTyOfConstParam {
3135 span: lifetime_ref.ident.span,
3136 name: lifetime_ref.ident.name,
3137 })
3138 .emit();
3139 }
3140
3141 pub(crate) fn emit_forbidden_non_static_lifetime_error(
3145 &self,
3146 cause: NoConstantGenericsReason,
3147 lifetime_ref: &ast::Lifetime,
3148 ) {
3149 match cause {
3150 NoConstantGenericsReason::IsEnumDiscriminant => {
3151 self.r
3152 .dcx()
3153 .create_err(errors::ParamInEnumDiscriminant {
3154 span: lifetime_ref.ident.span,
3155 name: lifetime_ref.ident.name,
3156 param_kind: errors::ParamKindInEnumDiscriminant::Lifetime,
3157 })
3158 .emit();
3159 }
3160 NoConstantGenericsReason::NonTrivialConstArg => {
3161 assert!(!self.r.tcx.features().generic_const_exprs());
3162 self.r
3163 .dcx()
3164 .create_err(errors::ParamInNonTrivialAnonConst {
3165 span: lifetime_ref.ident.span,
3166 name: lifetime_ref.ident.name,
3167 param_kind: errors::ParamKindInNonTrivialAnonConst::Lifetime,
3168 help: self
3169 .r
3170 .tcx
3171 .sess
3172 .is_nightly_build()
3173 .then_some(errors::ParamInNonTrivialAnonConstHelp),
3174 })
3175 .emit();
3176 }
3177 }
3178 }
3179
3180 pub(crate) fn report_missing_lifetime_specifiers(
3181 &mut self,
3182 lifetime_refs: Vec<MissingLifetime>,
3183 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3184 ) -> ErrorGuaranteed {
3185 let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
3186 let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3187
3188 let mut err = struct_span_code_err!(
3189 self.r.dcx(),
3190 spans,
3191 E0106,
3192 "missing lifetime specifier{}",
3193 pluralize!(num_lifetimes)
3194 );
3195 self.add_missing_lifetime_specifiers_label(
3196 &mut err,
3197 lifetime_refs,
3198 function_param_lifetimes,
3199 );
3200 err.emit()
3201 }
3202
3203 fn add_missing_lifetime_specifiers_label(
3204 &mut self,
3205 err: &mut Diag<'_>,
3206 lifetime_refs: Vec<MissingLifetime>,
3207 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3208 ) {
3209 for < in &lifetime_refs {
3210 err.span_label(
3211 lt.span,
3212 format!(
3213 "expected {} lifetime parameter{}",
3214 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
3215 pluralize!(lt.count),
3216 ),
3217 );
3218 }
3219
3220 let mut in_scope_lifetimes: Vec<_> = self
3221 .lifetime_ribs
3222 .iter()
3223 .rev()
3224 .take_while(|rib| {
3225 !matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
3226 })
3227 .flat_map(|rib| rib.bindings.iter())
3228 .map(|(&ident, &res)| (ident, res))
3229 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
3230 .collect();
3231 debug!(?in_scope_lifetimes);
3232
3233 let mut maybe_static = false;
3234 debug!(?function_param_lifetimes);
3235 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
3236 let elided_len = param_lifetimes.len();
3237 let num_params = params.len();
3238
3239 let mut m = String::new();
3240
3241 for (i, info) in params.iter().enumerate() {
3242 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
3243 debug_assert_ne!(lifetime_count, 0);
3244
3245 err.span_label(span, "");
3246
3247 if i != 0 {
3248 if i + 1 < num_params {
3249 m.push_str(", ");
3250 } else if num_params == 2 {
3251 m.push_str(" or ");
3252 } else {
3253 m.push_str(", or ");
3254 }
3255 }
3256
3257 let help_name = if let Some(ident) = ident {
3258 format!("`{ident}`")
3259 } else {
3260 format!("argument {}", index + 1)
3261 };
3262
3263 if lifetime_count == 1 {
3264 m.push_str(&help_name[..])
3265 } else {
3266 m.push_str(&format!("one of {help_name}'s {lifetime_count} lifetimes")[..])
3267 }
3268 }
3269
3270 if num_params == 0 {
3271 err.help(
3272 "this function's return type contains a borrowed value, but there is no value \
3273 for it to be borrowed from",
3274 );
3275 if in_scope_lifetimes.is_empty() {
3276 maybe_static = true;
3277 in_scope_lifetimes = vec![(
3278 Ident::with_dummy_span(kw::StaticLifetime),
3279 (DUMMY_NODE_ID, LifetimeRes::Static { suppress_elision_warning: false }),
3280 )];
3281 }
3282 } else if elided_len == 0 {
3283 err.help(
3284 "this function's return type contains a borrowed value with an elided \
3285 lifetime, but the lifetime cannot be derived from the arguments",
3286 );
3287 if in_scope_lifetimes.is_empty() {
3288 maybe_static = true;
3289 in_scope_lifetimes = vec![(
3290 Ident::with_dummy_span(kw::StaticLifetime),
3291 (DUMMY_NODE_ID, LifetimeRes::Static { suppress_elision_warning: false }),
3292 )];
3293 }
3294 } else if num_params == 1 {
3295 err.help(format!(
3296 "this function's return type contains a borrowed value, but the signature does \
3297 not say which {m} it is borrowed from",
3298 ));
3299 } else {
3300 err.help(format!(
3301 "this function's return type contains a borrowed value, but the signature does \
3302 not say whether it is borrowed from {m}",
3303 ));
3304 }
3305 }
3306
3307 #[allow(rustc::symbol_intern_string_literal)]
3308 let existing_name = match &in_scope_lifetimes[..] {
3309 [] => Symbol::intern("'a"),
3310 [(existing, _)] => existing.name,
3311 _ => Symbol::intern("'lifetime"),
3312 };
3313
3314 let mut spans_suggs: Vec<_> = Vec::new();
3315 let build_sugg = |lt: MissingLifetime| match lt.kind {
3316 MissingLifetimeKind::Underscore => {
3317 debug_assert_eq!(lt.count, 1);
3318 (lt.span, existing_name.to_string())
3319 }
3320 MissingLifetimeKind::Ampersand => {
3321 debug_assert_eq!(lt.count, 1);
3322 (lt.span.shrink_to_hi(), format!("{existing_name} "))
3323 }
3324 MissingLifetimeKind::Comma => {
3325 let sugg: String = std::iter::repeat([existing_name.as_str(), ", "])
3326 .take(lt.count)
3327 .flatten()
3328 .collect();
3329 (lt.span.shrink_to_hi(), sugg)
3330 }
3331 MissingLifetimeKind::Brackets => {
3332 let sugg: String = std::iter::once("<")
3333 .chain(
3334 std::iter::repeat(existing_name.as_str()).take(lt.count).intersperse(", "),
3335 )
3336 .chain([">"])
3337 .collect();
3338 (lt.span.shrink_to_hi(), sugg)
3339 }
3340 };
3341 for < in &lifetime_refs {
3342 spans_suggs.push(build_sugg(lt));
3343 }
3344 debug!(?spans_suggs);
3345 match in_scope_lifetimes.len() {
3346 0 => {
3347 if let Some((param_lifetimes, _)) = function_param_lifetimes {
3348 for lt in param_lifetimes {
3349 spans_suggs.push(build_sugg(lt))
3350 }
3351 }
3352 self.suggest_introducing_lifetime(
3353 err,
3354 None,
3355 |err, higher_ranked, span, message, intro_sugg, _| {
3356 err.multipart_suggestion_verbose(
3357 message,
3358 std::iter::once((span, intro_sugg))
3359 .chain(spans_suggs.clone())
3360 .collect(),
3361 Applicability::MaybeIncorrect,
3362 );
3363 higher_ranked
3364 },
3365 );
3366 }
3367 1 => {
3368 let post = if maybe_static {
3369 let owned = if let [lt] = &lifetime_refs[..]
3370 && lt.kind != MissingLifetimeKind::Ampersand
3371 {
3372 ", or if you will only have owned values"
3373 } else {
3374 ""
3375 };
3376 format!(
3377 ", but this is uncommon unless you're returning a borrowed value from a \
3378 `const` or a `static`{owned}",
3379 )
3380 } else {
3381 String::new()
3382 };
3383 err.multipart_suggestion_verbose(
3384 format!("consider using the `{existing_name}` lifetime{post}"),
3385 spans_suggs,
3386 Applicability::MaybeIncorrect,
3387 );
3388 if maybe_static {
3389 if let [lt] = &lifetime_refs[..]
3395 && (lt.kind == MissingLifetimeKind::Ampersand
3396 || lt.kind == MissingLifetimeKind::Underscore)
3397 {
3398 let pre = if lt.kind == MissingLifetimeKind::Ampersand
3399 && let Some((kind, _span)) = self.diag_metadata.current_function
3400 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3401 && !sig.decl.inputs.is_empty()
3402 && let sugg = sig
3403 .decl
3404 .inputs
3405 .iter()
3406 .filter_map(|param| {
3407 if param.ty.span.contains(lt.span) {
3408 None
3411 } else if let TyKind::CVarArgs = param.ty.kind {
3412 None
3414 } else if let TyKind::ImplTrait(..) = ¶m.ty.kind {
3415 None
3417 } else {
3418 Some((param.ty.span.shrink_to_lo(), "&".to_string()))
3419 }
3420 })
3421 .collect::<Vec<_>>()
3422 && !sugg.is_empty()
3423 {
3424 let (the, s) = if sig.decl.inputs.len() == 1 {
3425 ("the", "")
3426 } else {
3427 ("one of the", "s")
3428 };
3429 err.multipart_suggestion_verbose(
3430 format!(
3431 "instead, you are more likely to want to change {the} \
3432 argument{s} to be borrowed...",
3433 ),
3434 sugg,
3435 Applicability::MaybeIncorrect,
3436 );
3437 "...or alternatively, you might want"
3438 } else if (lt.kind == MissingLifetimeKind::Ampersand
3439 || lt.kind == MissingLifetimeKind::Underscore)
3440 && let Some((kind, _span)) = self.diag_metadata.current_function
3441 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3442 && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
3443 && !sig.decl.inputs.is_empty()
3444 && let arg_refs = sig
3445 .decl
3446 .inputs
3447 .iter()
3448 .filter_map(|param| match ¶m.ty.kind {
3449 TyKind::ImplTrait(_, bounds) => Some(bounds),
3450 _ => None,
3451 })
3452 .flat_map(|bounds| bounds.into_iter())
3453 .collect::<Vec<_>>()
3454 && !arg_refs.is_empty()
3455 {
3456 let mut lt_finder =
3462 LifetimeFinder { lifetime: lt.span, found: None, seen: vec![] };
3463 for bound in arg_refs {
3464 if let ast::GenericBound::Trait(trait_ref) = bound {
3465 lt_finder.visit_trait_ref(&trait_ref.trait_ref);
3466 }
3467 }
3468 lt_finder.visit_ty(ret_ty);
3469 let spans_suggs: Vec<_> = lt_finder
3470 .seen
3471 .iter()
3472 .filter_map(|ty| match &ty.kind {
3473 TyKind::Ref(_, mut_ty) => {
3474 let span = ty.span.with_hi(mut_ty.ty.span.lo());
3475 Some((span, "&'a ".to_string()))
3476 }
3477 _ => None,
3478 })
3479 .collect();
3480 self.suggest_introducing_lifetime(
3481 err,
3482 None,
3483 |err, higher_ranked, span, message, intro_sugg, _| {
3484 err.multipart_suggestion_verbose(
3485 message,
3486 std::iter::once((span, intro_sugg))
3487 .chain(spans_suggs.clone())
3488 .collect(),
3489 Applicability::MaybeIncorrect,
3490 );
3491 higher_ranked
3492 },
3493 );
3494 "alternatively, you might want"
3495 } else {
3496 "instead, you are more likely to want"
3497 };
3498 let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
3499 let mut sugg = vec![(lt.span, String::new())];
3500 if let Some((kind, _span)) = self.diag_metadata.current_function
3501 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3502 && let ast::FnRetTy::Ty(ty) = &sig.decl.output
3503 {
3504 let mut lt_finder =
3505 LifetimeFinder { lifetime: lt.span, found: None, seen: vec![] };
3506 lt_finder.visit_ty(&ty);
3507
3508 if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
3509 <_finder.seen[..]
3510 {
3511 sugg = vec![(span.with_hi(mut_ty.ty.span.lo()), String::new())];
3517 owned_sugg = true;
3518 }
3519 if let Some(ty) = lt_finder.found {
3520 if let TyKind::Path(None, path) = &ty.kind {
3521 let path: Vec<_> = Segment::from_path(path);
3523 match self.resolve_path(&path, Some(TypeNS), None) {
3524 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3525 match module.res() {
3526 Some(Res::PrimTy(PrimTy::Str)) => {
3527 sugg = vec![(
3529 lt.span.with_hi(ty.span.hi()),
3530 "String".to_string(),
3531 )];
3532 }
3533 Some(Res::PrimTy(..)) => {}
3534 Some(Res::Def(
3535 DefKind::Struct
3536 | DefKind::Union
3537 | DefKind::Enum
3538 | DefKind::ForeignTy
3539 | DefKind::AssocTy
3540 | DefKind::OpaqueTy
3541 | DefKind::TyParam,
3542 _,
3543 )) => {}
3544 _ => {
3545 owned_sugg = false;
3547 }
3548 }
3549 }
3550 PathResult::NonModule(res) => {
3551 match res.base_res() {
3552 Res::PrimTy(PrimTy::Str) => {
3553 sugg = vec![(
3555 lt.span.with_hi(ty.span.hi()),
3556 "String".to_string(),
3557 )];
3558 }
3559 Res::PrimTy(..) => {}
3560 Res::Def(
3561 DefKind::Struct
3562 | DefKind::Union
3563 | DefKind::Enum
3564 | DefKind::ForeignTy
3565 | DefKind::AssocTy
3566 | DefKind::OpaqueTy
3567 | DefKind::TyParam,
3568 _,
3569 ) => {}
3570 _ => {
3571 owned_sugg = false;
3573 }
3574 }
3575 }
3576 _ => {
3577 owned_sugg = false;
3579 }
3580 }
3581 }
3582 if let TyKind::Slice(inner_ty) = &ty.kind {
3583 sugg = vec![
3585 (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
3586 (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
3587 ];
3588 }
3589 }
3590 }
3591 if owned_sugg {
3592 err.multipart_suggestion_verbose(
3593 format!("{pre} to return an owned value"),
3594 sugg,
3595 Applicability::MaybeIncorrect,
3596 );
3597 }
3598 }
3599 }
3600 }
3601 _ => {
3602 let lifetime_spans: Vec<_> =
3603 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
3604 err.span_note(lifetime_spans, "these named lifetimes are available to use");
3605
3606 if spans_suggs.len() > 0 {
3607 err.multipart_suggestion_verbose(
3610 "consider using one of the available lifetimes here",
3611 spans_suggs,
3612 Applicability::HasPlaceholders,
3613 );
3614 }
3615 }
3616 }
3617 }
3618}
3619
3620fn mk_where_bound_predicate(
3621 path: &Path,
3622 poly_trait_ref: &ast::PolyTraitRef,
3623 ty: &Ty,
3624) -> Option<ast::WhereBoundPredicate> {
3625 let modified_segments = {
3626 let mut segments = path.segments.clone();
3627 let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
3628 return None;
3629 };
3630 let mut segments = ThinVec::from(preceding);
3631
3632 let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
3633 id: DUMMY_NODE_ID,
3634 ident: last.ident,
3635 gen_args: None,
3636 kind: ast::AssocItemConstraintKind::Equality {
3637 term: ast::Term::Ty(ast::ptr::P(ast::Ty {
3638 kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
3639 id: DUMMY_NODE_ID,
3640 span: DUMMY_SP,
3641 tokens: None,
3642 })),
3643 },
3644 span: DUMMY_SP,
3645 });
3646
3647 match second_last.args.as_deref_mut() {
3648 Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
3649 args.push(added_constraint);
3650 }
3651 Some(_) => return None,
3652 None => {
3653 second_last.args =
3654 Some(ast::ptr::P(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
3655 args: ThinVec::from([added_constraint]),
3656 span: DUMMY_SP,
3657 })));
3658 }
3659 }
3660
3661 segments.push(second_last.clone());
3662 segments
3663 };
3664
3665 let new_where_bound_predicate = ast::WhereBoundPredicate {
3666 bound_generic_params: ThinVec::new(),
3667 bounded_ty: ast::ptr::P(ty.clone()),
3668 bounds: vec![ast::GenericBound::Trait(ast::PolyTraitRef {
3669 bound_generic_params: ThinVec::new(),
3670 modifiers: ast::TraitBoundModifiers::NONE,
3671 trait_ref: ast::TraitRef {
3672 path: ast::Path { segments: modified_segments, span: DUMMY_SP, tokens: None },
3673 ref_id: DUMMY_NODE_ID,
3674 },
3675 span: DUMMY_SP,
3676 })],
3677 };
3678
3679 Some(new_where_bound_predicate)
3680}
3681
3682pub(super) fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
3684 struct_span_code_err!(
3685 sess.dcx(),
3686 shadower.span,
3687 E0496,
3688 "lifetime name `{}` shadows a lifetime name that is already in scope",
3689 orig.name,
3690 )
3691 .with_span_label(orig.span, "first declared here")
3692 .with_span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name))
3693 .emit();
3694}
3695
3696struct LifetimeFinder<'ast> {
3697 lifetime: Span,
3698 found: Option<&'ast Ty>,
3699 seen: Vec<&'ast Ty>,
3700}
3701
3702impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
3703 fn visit_ty(&mut self, t: &'ast Ty) {
3704 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
3705 self.seen.push(t);
3706 if t.span.lo() == self.lifetime.lo() {
3707 self.found = Some(&mut_ty.ty);
3708 }
3709 }
3710 walk_ty(self, t)
3711 }
3712}
3713
3714pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
3717 let name = shadower.name;
3718 let shadower = shadower.span;
3719 sess.dcx()
3720 .struct_span_warn(
3721 shadower,
3722 format!("label name `{name}` shadows a label name that is already in scope"),
3723 )
3724 .with_span_label(orig, "first declared here")
3725 .with_span_label(shadower, format!("label `{name}` already in scope"))
3726 .emit();
3727}