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