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