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