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