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