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