1use std::borrow::Cow;
2use std::iter;
3use std::path::PathBuf;
4
5use rustc_errors::codes::*;
6use rustc_errors::{Diag, IntoDiagArg};
7use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
8use rustc_hir::def_id::{DefId, LocalDefId};
9use rustc_hir::intravisit::{self, Visitor};
10use rustc_hir::{
11 self as hir, Body, Closure, Expr, ExprKind, FnRetTy, HirId, LetStmt, LocalSource, PatKind,
12};
13use rustc_middle::bug;
14use rustc_middle::hir::nested_filter;
15use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow};
16use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Print, Printer};
17use rustc_middle::ty::{
18 self, GenericArg, GenericArgKind, GenericArgsRef, InferConst, IsSuggestable, Term, TermKind,
19 Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, TypeckResults,
20};
21use rustc_span::{BytePos, DUMMY_SP, Ident, Span, sym};
22use tracing::{debug, instrument, warn};
23
24use super::nice_region_error::placeholder_error::Highlighted;
25use crate::error_reporting::TypeErrCtxt;
26use crate::errors::{
27 AmbiguousImpl, AmbiguousReturn, AnnotationRequired, InferenceBadError,
28 SourceKindMultiSuggestion, SourceKindSubdiag,
29};
30use crate::infer::InferCtxt;
31
32pub enum TypeAnnotationNeeded {
33 E0282,
37 E0283,
42 E0284,
47}
48
49impl From<TypeAnnotationNeeded> for ErrCode {
50 fn from(val: TypeAnnotationNeeded) -> Self {
51 match val {
52 TypeAnnotationNeeded::E0282 => E0282,
53 TypeAnnotationNeeded::E0283 => E0283,
54 TypeAnnotationNeeded::E0284 => E0284,
55 }
56 }
57}
58
59pub struct InferenceDiagnosticsData {
61 pub name: String,
62 pub span: Option<Span>,
63 pub kind: UnderspecifiedArgKind,
64 pub parent: Option<InferenceDiagnosticsParentData>,
65}
66
67pub struct InferenceDiagnosticsParentData {
69 prefix: &'static str,
70 name: String,
71}
72
73#[derive(Clone)]
74pub enum UnderspecifiedArgKind {
75 Type { prefix: Cow<'static, str> },
76 Const { is_parameter: bool },
77}
78
79impl InferenceDiagnosticsData {
80 fn can_add_more_info(&self) -> bool {
81 !(self.name == "_" && matches!(self.kind, UnderspecifiedArgKind::Type { .. }))
82 }
83
84 fn where_x_is_kind(&self, in_type: Ty<'_>) -> &'static str {
85 if in_type.is_ty_or_numeric_infer() {
86 ""
87 } else if self.name == "_" {
88 "underscore"
91 } else {
92 "has_name"
93 }
94 }
95
96 fn make_bad_error(&self, span: Span) -> InferenceBadError<'_> {
100 let has_parent = self.parent.is_some();
101 let bad_kind = if self.can_add_more_info() { "more_info" } else { "other" };
102 let (parent_prefix, parent_name) = self
103 .parent
104 .as_ref()
105 .map(|parent| (parent.prefix, parent.name.clone()))
106 .unwrap_or_default();
107 InferenceBadError {
108 span,
109 bad_kind,
110 prefix_kind: self.kind.clone(),
111 prefix: self.kind.try_get_prefix().unwrap_or_default(),
112 name: self.name.clone(),
113 has_parent,
114 parent_prefix,
115 parent_name,
116 }
117 }
118}
119
120impl InferenceDiagnosticsParentData {
121 fn for_parent_def_id(
122 tcx: TyCtxt<'_>,
123 parent_def_id: DefId,
124 ) -> Option<InferenceDiagnosticsParentData> {
125 let parent_name =
126 tcx.def_key(parent_def_id).disambiguated_data.data.get_opt_name()?.to_string();
127
128 Some(InferenceDiagnosticsParentData {
129 prefix: tcx.def_descr(parent_def_id),
130 name: parent_name,
131 })
132 }
133
134 fn for_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<InferenceDiagnosticsParentData> {
135 Self::for_parent_def_id(tcx, tcx.parent(def_id))
136 }
137}
138
139impl IntoDiagArg for UnderspecifiedArgKind {
140 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
141 let kind = match self {
142 Self::Type { .. } => "type",
143 Self::Const { is_parameter: true } => "const_with_param",
144 Self::Const { is_parameter: false } => "const",
145 };
146 rustc_errors::DiagArgValue::Str(kind.into())
147 }
148}
149
150impl UnderspecifiedArgKind {
151 fn try_get_prefix(&self) -> Option<&str> {
152 match self {
153 Self::Type { prefix } => Some(prefix.as_ref()),
154 Self::Const { .. } => None,
155 }
156 }
157}
158
159struct ClosureEraser<'a, 'tcx> {
160 infcx: &'a InferCtxt<'tcx>,
161}
162
163impl<'a, 'tcx> ClosureEraser<'a, 'tcx> {
164 fn new_infer(&mut self) -> Ty<'tcx> {
165 self.infcx.next_ty_var(DUMMY_SP)
166 }
167}
168
169impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ClosureEraser<'a, 'tcx> {
170 fn cx(&self) -> TyCtxt<'tcx> {
171 self.infcx.tcx
172 }
173
174 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
175 match ty.kind() {
176 ty::Closure(_, args) => {
177 let closure_sig = args.as_closure().sig();
180 Ty::new_fn_ptr(
181 self.cx(),
182 self.cx().signature_unclosure(closure_sig, hir::Safety::Safe),
183 )
184 }
185 ty::Adt(_, args) if !args.iter().any(|a| a.has_infer()) => {
186 self.new_infer()
191 }
192 ty::Adt(def, args) => {
193 let generics = self.cx().generics_of(def.did());
194 let generics: Vec<bool> = generics
195 .own_params
196 .iter()
197 .map(|param| param.default_value(self.cx()).is_some())
198 .collect();
199 let ty = Ty::new_adt(
200 self.cx(),
201 *def,
202 self.cx().mk_args_from_iter(generics.into_iter().zip(args.iter()).map(
203 |(has_default, arg)| {
204 if arg.has_infer() {
205 arg.fold_with(self)
211 } else if has_default {
212 arg
219 } else if let GenericArgKind::Type(_) = arg.kind() {
220 self.new_infer().into()
222 } else {
223 arg.fold_with(self)
224 }
225 },
226 )),
227 );
228 ty
229 }
230 _ if ty.has_infer() => {
231 ty.super_fold_with(self)
235 }
236 _ => self.new_infer(),
238 }
239 }
240
241 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
242 c
244 }
245}
246
247fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'tcx>, ns: Namespace) -> FmtPrinter<'a, 'tcx> {
248 let mut p = FmtPrinter::new(infcx.tcx, ns);
249 let ty_getter = move |ty_vid| {
250 if infcx.probe_ty_var(ty_vid).is_ok() {
251 warn!("resolved ty var in error message");
252 }
253
254 let var_origin = infcx.type_var_origin(ty_vid);
255 if let Some(def_id) = var_origin.param_def_id
256 && infcx.tcx.def_kind(def_id) == DefKind::TyParam
259 && let name = infcx.tcx.item_name(def_id)
260 && !var_origin.span.from_expansion()
261 {
262 let generics = infcx.tcx.generics_of(infcx.tcx.parent(def_id));
263 let idx = generics.param_def_id_to_index(infcx.tcx, def_id).unwrap();
264 let generic_param_def = generics.param_at(idx as usize, infcx.tcx);
265 if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param_def.kind {
266 None
267 } else {
268 Some(name)
269 }
270 } else {
271 None
272 }
273 };
274 p.ty_infer_name_resolver = Some(Box::new(ty_getter));
275 let const_getter =
276 move |ct_vid| Some(infcx.tcx.item_name(infcx.const_var_origin(ct_vid)?.param_def_id?));
277 p.const_infer_name_resolver = Some(Box::new(const_getter));
278 p
279}
280
281fn ty_to_string<'tcx>(
282 infcx: &InferCtxt<'tcx>,
283 ty: Ty<'tcx>,
284 called_method_def_id: Option<DefId>,
285) -> String {
286 let mut p = fmt_printer(infcx, Namespace::TypeNS);
287 let ty = infcx.resolve_vars_if_possible(ty);
288 let ty = ty.fold_with(&mut ClosureEraser { infcx });
291
292 match (ty.kind(), called_method_def_id) {
293 (ty::FnDef(..), _) => {
296 ty.fn_sig(infcx.tcx).print(&mut p).unwrap();
297 p.into_buffer()
298 }
299 (_, Some(def_id))
300 if ty.is_ty_or_numeric_infer()
301 && infcx.tcx.get_diagnostic_item(sym::iterator_collect_fn) == Some(def_id) =>
302 {
303 "Vec<_>".to_string()
304 }
305 _ if ty.is_ty_or_numeric_infer() => "/* Type */".to_string(),
306 _ => {
307 ty.print(&mut p).unwrap();
308 p.into_buffer()
309 }
310 }
311}
312
313fn closure_as_fn_str<'tcx>(infcx: &InferCtxt<'tcx>, ty: Ty<'tcx>) -> String {
317 let ty::Closure(_, args) = ty.kind() else {
318 bug!("cannot convert non-closure to fn str in `closure_as_fn_str`")
319 };
320 let fn_sig = args.as_closure().sig();
321 let args = fn_sig
322 .inputs()
323 .skip_binder()
324 .iter()
325 .next()
326 .map(|args| {
327 args.tuple_fields()
328 .iter()
329 .map(|arg| ty_to_string(infcx, arg, None))
330 .collect::<Vec<_>>()
331 .join(", ")
332 })
333 .unwrap_or_default();
334 let ret = if fn_sig.output().skip_binder().is_unit() {
335 String::new()
336 } else {
337 format!(" -> {}", ty_to_string(infcx, fn_sig.output().skip_binder(), None))
338 };
339 format!("fn({args}){ret}")
340}
341
342impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
343 pub fn extract_inference_diagnostics_data(
346 &self,
347 term: Term<'tcx>,
348 highlight: ty::print::RegionHighlightMode<'tcx>,
349 ) -> InferenceDiagnosticsData {
350 let tcx = self.tcx;
351 match term.kind() {
352 TermKind::Ty(ty) => {
353 if let ty::Infer(ty::TyVar(ty_vid)) = *ty.kind() {
354 let var_origin = self.infcx.type_var_origin(ty_vid);
355 if let Some(def_id) = var_origin.param_def_id
356 && self.tcx.def_kind(def_id) == DefKind::TyParam
359 && !var_origin.span.from_expansion()
360 {
361 return InferenceDiagnosticsData {
362 name: self.tcx.item_name(def_id).to_string(),
363 span: Some(var_origin.span),
364 kind: UnderspecifiedArgKind::Type { prefix: "type parameter".into() },
365 parent: InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id),
366 };
367 }
368 }
369
370 InferenceDiagnosticsData {
371 name: Highlighted { highlight, ns: Namespace::TypeNS, tcx, value: ty }
372 .to_string(),
373 span: None,
374 kind: UnderspecifiedArgKind::Type { prefix: ty.prefix_string(self.tcx) },
375 parent: None,
376 }
377 }
378 TermKind::Const(ct) => {
379 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
380 let origin = self.const_var_origin(vid).expect("expected unresolved const var");
381 if let Some(def_id) = origin.param_def_id {
382 return InferenceDiagnosticsData {
383 name: self.tcx.item_name(def_id).to_string(),
384 span: Some(origin.span),
385 kind: UnderspecifiedArgKind::Const { is_parameter: true },
386 parent: InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id),
387 };
388 }
389
390 debug_assert!(!origin.span.is_dummy());
391 InferenceDiagnosticsData {
392 name: Highlighted { highlight, ns: Namespace::ValueNS, tcx, value: ct }
393 .to_string(),
394 span: Some(origin.span),
395 kind: UnderspecifiedArgKind::Const { is_parameter: false },
396 parent: None,
397 }
398 } else {
399 InferenceDiagnosticsData {
406 name: Highlighted { highlight, ns: Namespace::ValueNS, tcx, value: ct }
407 .to_string(),
408 span: None,
409 kind: UnderspecifiedArgKind::Const { is_parameter: false },
410 parent: None,
411 }
412 }
413 }
414 }
415 }
416
417 fn bad_inference_failure_err(
420 &self,
421 span: Span,
422 arg_data: InferenceDiagnosticsData,
423 error_code: TypeAnnotationNeeded,
424 ) -> Diag<'a> {
425 let source_kind = "other";
426 let source_name = "";
427 let failure_span = None;
428 let infer_subdiags = Vec::new();
429 let multi_suggestions = Vec::new();
430 let bad_label = Some(arg_data.make_bad_error(span));
431 match error_code {
432 TypeAnnotationNeeded::E0282 => self.dcx().create_err(AnnotationRequired {
433 span,
434 source_kind,
435 source_name,
436 failure_span,
437 infer_subdiags,
438 multi_suggestions,
439 bad_label,
440 }),
441 TypeAnnotationNeeded::E0283 => self.dcx().create_err(AmbiguousImpl {
442 span,
443 source_kind,
444 source_name,
445 failure_span,
446 infer_subdiags,
447 multi_suggestions,
448 bad_label,
449 }),
450 TypeAnnotationNeeded::E0284 => self.dcx().create_err(AmbiguousReturn {
451 span,
452 source_kind,
453 source_name,
454 failure_span,
455 infer_subdiags,
456 multi_suggestions,
457 bad_label,
458 }),
459 }
460 }
461
462 #[instrument(level = "debug", skip(self, error_code))]
463 pub fn emit_inference_failure_err(
464 &self,
465 body_def_id: LocalDefId,
466 failure_span: Span,
467 term: Term<'tcx>,
468 error_code: TypeAnnotationNeeded,
469 should_label_span: bool,
470 ) -> Diag<'a> {
471 let term = self.resolve_vars_if_possible(term);
472 let arg_data = self
473 .extract_inference_diagnostics_data(term, ty::print::RegionHighlightMode::default());
474
475 let Some(typeck_results) = &self.typeck_results else {
476 return self.bad_inference_failure_err(failure_span, arg_data, error_code);
480 };
481
482 let mut local_visitor = FindInferSourceVisitor::new(self, typeck_results, term);
483 if let Some(body) = self.tcx.hir_maybe_body_owned_by(
484 self.tcx.typeck_root_def_id(body_def_id.to_def_id()).expect_local(),
485 ) {
486 let expr = body.value;
487 local_visitor.visit_expr(expr);
488 }
489
490 let Some(InferSource { span, kind }) = local_visitor.infer_source else {
491 return self.bad_inference_failure_err(failure_span, arg_data, error_code);
492 };
493
494 let (source_kind, name, long_ty_path) = kind.ty_localized_msg(self);
495 let failure_span = if should_label_span && !failure_span.overlaps(span) {
496 Some(failure_span)
497 } else {
498 None
499 };
500
501 let mut infer_subdiags = Vec::new();
502 let mut multi_suggestions = Vec::new();
503 match kind {
504 InferSourceKind::LetBinding { insert_span, pattern_name, ty, def_id } => {
505 infer_subdiags.push(SourceKindSubdiag::LetLike {
506 span: insert_span,
507 name: pattern_name.map(|name| name.to_string()).unwrap_or_else(String::new),
508 x_kind: arg_data.where_x_is_kind(ty),
509 prefix_kind: arg_data.kind.clone(),
510 prefix: arg_data.kind.try_get_prefix().unwrap_or_default(),
511 arg_name: arg_data.name,
512 kind: if pattern_name.is_some() { "with_pattern" } else { "other" },
513 type_name: ty_to_string(self, ty, def_id),
514 });
515 }
516 InferSourceKind::ClosureArg { insert_span, ty, .. } => {
517 infer_subdiags.push(SourceKindSubdiag::LetLike {
518 span: insert_span,
519 name: String::new(),
520 x_kind: arg_data.where_x_is_kind(ty),
521 prefix_kind: arg_data.kind.clone(),
522 prefix: arg_data.kind.try_get_prefix().unwrap_or_default(),
523 arg_name: arg_data.name,
524 kind: "closure",
525 type_name: ty_to_string(self, ty, None),
526 });
527 }
528 InferSourceKind::GenericArg {
529 insert_span,
530 argument_index,
531 generics_def_id,
532 def_id: _,
533 generic_args,
534 have_turbofish,
535 } => {
536 let generics = self.tcx.generics_of(generics_def_id);
537 let is_type = term.as_type().is_some();
538
539 let (parent_exists, parent_prefix, parent_name) =
540 InferenceDiagnosticsParentData::for_parent_def_id(self.tcx, generics_def_id)
541 .map_or((false, String::new(), String::new()), |parent| {
542 (true, parent.prefix.to_string(), parent.name)
543 });
544
545 infer_subdiags.push(SourceKindSubdiag::GenericLabel {
546 span,
547 is_type,
548 param_name: generics.own_params[argument_index].name.to_string(),
549 parent_exists,
550 parent_prefix,
551 parent_name,
552 });
553
554 let args = if self.tcx.get_diagnostic_item(sym::iterator_collect_fn)
555 == Some(generics_def_id)
556 {
557 "Vec<_>".to_string()
558 } else {
559 let mut p = fmt_printer(self, Namespace::TypeNS);
560 p.comma_sep(generic_args.iter().copied().map(|arg| {
561 if arg.is_suggestable(self.tcx, true) {
562 return arg;
563 }
564
565 match arg.kind() {
566 GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"),
567 GenericArgKind::Type(_) => self.next_ty_var(DUMMY_SP).into(),
568 GenericArgKind::Const(_) => self.next_const_var(DUMMY_SP).into(),
569 }
570 }))
571 .unwrap();
572 p.into_buffer()
573 };
574
575 if !have_turbofish {
576 infer_subdiags.push(SourceKindSubdiag::GenericSuggestion {
577 span: insert_span,
578 arg_count: generic_args.len(),
579 args,
580 });
581 }
582 }
583 InferSourceKind::FullyQualifiedMethodCall { receiver, successor, args, def_id } => {
584 let placeholder = Some(self.next_ty_var(DUMMY_SP));
585 if let Some(args) = args.make_suggestable(self.infcx.tcx, true, placeholder) {
586 let mut p = fmt_printer(self, Namespace::ValueNS);
587 p.print_def_path(def_id, args).unwrap();
588 let def_path = p.into_buffer();
589
590 let adjustment = match typeck_results.expr_adjustments(receiver) {
594 [
595 Adjustment { kind: Adjust::Deref(None), target: _ },
596 ..,
597 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), target: _ },
598 ] => "",
599 [
600 ..,
601 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mut_)), target: _ },
602 ] => hir::Mutability::from(*mut_).ref_prefix_str(),
603 _ => "",
604 };
605
606 multi_suggestions.push(SourceKindMultiSuggestion::new_fully_qualified(
607 receiver.span,
608 def_path,
609 adjustment,
610 successor,
611 ));
612 }
613 }
614 InferSourceKind::ClosureReturn { ty, data, should_wrap_expr } => {
615 let placeholder = Some(self.next_ty_var(DUMMY_SP));
616 if let Some(ty) = ty.make_suggestable(self.infcx.tcx, true, placeholder) {
617 let ty_info = ty_to_string(self, ty, None);
618 multi_suggestions.push(SourceKindMultiSuggestion::new_closure_return(
619 ty_info,
620 data,
621 should_wrap_expr,
622 ));
623 }
624 }
625 }
626 let mut err = match error_code {
627 TypeAnnotationNeeded::E0282 => self.dcx().create_err(AnnotationRequired {
628 span,
629 source_kind,
630 source_name: &name,
631 failure_span,
632 infer_subdiags,
633 multi_suggestions,
634 bad_label: None,
635 }),
636 TypeAnnotationNeeded::E0283 => self.dcx().create_err(AmbiguousImpl {
637 span,
638 source_kind,
639 source_name: &name,
640 failure_span,
641 infer_subdiags,
642 multi_suggestions,
643 bad_label: None,
644 }),
645 TypeAnnotationNeeded::E0284 => self.dcx().create_err(AmbiguousReturn {
646 span,
647 source_kind,
648 source_name: &name,
649 failure_span,
650 infer_subdiags,
651 multi_suggestions,
652 bad_label: None,
653 }),
654 };
655 *err.long_ty_path() = long_ty_path;
656 if let InferSourceKind::ClosureArg { kind: PatKind::Err(_), .. } = kind {
657 err.downgrade_to_delayed_bug();
659 }
660 err
661 }
662}
663
664#[derive(Debug)]
665struct InferSource<'tcx> {
666 span: Span,
667 kind: InferSourceKind<'tcx>,
668}
669
670#[derive(Debug)]
671enum InferSourceKind<'tcx> {
672 LetBinding {
673 insert_span: Span,
674 pattern_name: Option<Ident>,
675 ty: Ty<'tcx>,
676 def_id: Option<DefId>,
677 },
678 ClosureArg {
679 insert_span: Span,
680 ty: Ty<'tcx>,
681 kind: PatKind<'tcx>,
682 },
683 GenericArg {
684 insert_span: Span,
685 argument_index: usize,
686 generics_def_id: DefId,
687 def_id: DefId,
688 generic_args: &'tcx [GenericArg<'tcx>],
689 have_turbofish: bool,
690 },
691 FullyQualifiedMethodCall {
692 receiver: &'tcx Expr<'tcx>,
693 successor: (&'static str, BytePos),
696 args: GenericArgsRef<'tcx>,
697 def_id: DefId,
698 },
699 ClosureReturn {
700 ty: Ty<'tcx>,
701 data: &'tcx FnRetTy<'tcx>,
702 should_wrap_expr: Option<Span>,
703 },
704}
705
706impl<'tcx> InferSource<'tcx> {
707 fn from_expansion(&self) -> bool {
708 let source_from_expansion = match self.kind {
709 InferSourceKind::LetBinding { insert_span, .. }
710 | InferSourceKind::ClosureArg { insert_span, .. }
711 | InferSourceKind::GenericArg { insert_span, .. } => insert_span.from_expansion(),
712 InferSourceKind::FullyQualifiedMethodCall { receiver, .. } => {
713 receiver.span.from_expansion()
714 }
715 InferSourceKind::ClosureReturn { data, should_wrap_expr, .. } => {
716 data.span().from_expansion() || should_wrap_expr.is_some_and(Span::from_expansion)
717 }
718 };
719 source_from_expansion || self.span.from_expansion()
720 }
721}
722
723impl<'tcx> InferSourceKind<'tcx> {
724 fn ty_localized_msg(&self, infcx: &InferCtxt<'tcx>) -> (&'static str, String, Option<PathBuf>) {
725 let mut long_ty_path = None;
726 match *self {
727 InferSourceKind::LetBinding { ty, .. }
728 | InferSourceKind::ClosureArg { ty, .. }
729 | InferSourceKind::ClosureReturn { ty, .. } => {
730 if ty.is_closure() {
731 ("closure", closure_as_fn_str(infcx, ty), long_ty_path)
732 } else if !ty.is_ty_or_numeric_infer() {
733 ("normal", infcx.tcx.short_string(ty, &mut long_ty_path), long_ty_path)
734 } else {
735 ("other", String::new(), long_ty_path)
736 }
737 }
738 InferSourceKind::GenericArg { .. }
740 | InferSourceKind::FullyQualifiedMethodCall { .. } => {
741 ("other", String::new(), long_ty_path)
742 }
743 }
744 }
745}
746
747#[derive(Debug)]
748struct InsertableGenericArgs<'tcx> {
749 insert_span: Span,
750 args: GenericArgsRef<'tcx>,
751 generics_def_id: DefId,
752 def_id: DefId,
753 have_turbofish: bool,
754}
755
756struct FindInferSourceVisitor<'a, 'tcx> {
764 tecx: &'a TypeErrCtxt<'a, 'tcx>,
765 typeck_results: &'a TypeckResults<'tcx>,
766
767 target: Term<'tcx>,
768
769 attempt: usize,
770 infer_source_cost: usize,
771 infer_source: Option<InferSource<'tcx>>,
772}
773
774impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> {
775 fn new(
776 tecx: &'a TypeErrCtxt<'a, 'tcx>,
777 typeck_results: &'a TypeckResults<'tcx>,
778 target: Term<'tcx>,
779 ) -> Self {
780 FindInferSourceVisitor {
781 tecx,
782 typeck_results,
783
784 target,
785
786 attempt: 0,
787 infer_source_cost: usize::MAX,
788 infer_source: None,
789 }
790 }
791
792 fn source_cost(&self, source: &InferSource<'tcx>) -> usize {
797 #[derive(Clone, Copy)]
798 struct CostCtxt<'tcx> {
799 tcx: TyCtxt<'tcx>,
800 }
801 impl<'tcx> CostCtxt<'tcx> {
802 fn arg_cost(self, arg: GenericArg<'tcx>) -> usize {
803 match arg.kind() {
804 GenericArgKind::Lifetime(_) => 0, GenericArgKind::Type(ty) => self.ty_cost(ty),
806 GenericArgKind::Const(_) => 3, }
808 }
809 fn ty_cost(self, ty: Ty<'tcx>) -> usize {
810 match *ty.kind() {
811 ty::Closure(..) => 1000,
812 ty::FnDef(..) => 150,
813 ty::FnPtr(..) => 30,
814 ty::Adt(def, args) => {
815 5 + self
816 .tcx
817 .generics_of(def.did())
818 .own_args_no_defaults(self.tcx, args)
819 .iter()
820 .map(|&arg| self.arg_cost(arg))
821 .sum::<usize>()
822 }
823 ty::Tuple(args) => 5 + args.iter().map(|arg| self.ty_cost(arg)).sum::<usize>(),
824 ty::Ref(_, ty, _) => 2 + self.ty_cost(ty),
825 ty::Infer(..) => 0,
826 _ => 1,
827 }
828 }
829 }
830
831 let tcx = self.tecx.tcx;
833 let ctx = CostCtxt { tcx };
834 match source.kind {
835 InferSourceKind::LetBinding { ty, .. } => ctx.ty_cost(ty),
836 InferSourceKind::ClosureArg { ty, .. } => ctx.ty_cost(ty),
837 InferSourceKind::GenericArg { def_id, generic_args, .. } => {
838 let variant_cost = match tcx.def_kind(def_id) {
839 DefKind::Variant | DefKind::Ctor(CtorOf::Variant, _) => 15,
841 _ => 10,
842 };
843 variant_cost + generic_args.iter().map(|&arg| ctx.arg_cost(arg)).sum::<usize>()
844 }
845 InferSourceKind::FullyQualifiedMethodCall { args, .. } => {
846 20 + args.iter().map(|arg| ctx.arg_cost(arg)).sum::<usize>()
847 }
848 InferSourceKind::ClosureReturn { ty, should_wrap_expr, .. } => {
849 30 + ctx.ty_cost(ty) + if should_wrap_expr.is_some() { 10 } else { 0 }
850 }
851 }
852 }
853
854 #[instrument(level = "debug", skip(self))]
857 fn update_infer_source(&mut self, mut new_source: InferSource<'tcx>) {
858 if new_source.from_expansion() {
859 return;
860 }
861
862 let cost = self.source_cost(&new_source) + self.attempt;
863 debug!(?cost);
864 self.attempt += 1;
865 if let Some(InferSource { kind: InferSourceKind::GenericArg { def_id: did, .. }, .. }) =
866 self.infer_source
867 && let InferSourceKind::LetBinding { ref ty, ref mut def_id, .. } = new_source.kind
868 && ty.is_ty_or_numeric_infer()
869 {
870 *def_id = Some(did);
873 }
874
875 if cost < self.infer_source_cost {
876 self.infer_source_cost = cost;
877 self.infer_source = Some(new_source);
878 }
879 }
880
881 fn node_args_opt(&self, hir_id: HirId) -> Option<GenericArgsRef<'tcx>> {
882 let args = self.typeck_results.node_args_opt(hir_id);
883 self.tecx.resolve_vars_if_possible(args)
884 }
885
886 fn opt_node_type(&self, hir_id: HirId) -> Option<Ty<'tcx>> {
887 let ty = self.typeck_results.node_type_opt(hir_id);
888 self.tecx.resolve_vars_if_possible(ty)
889 }
890
891 fn generic_arg_is_target(&self, arg: GenericArg<'tcx>) -> bool {
894 if arg == self.target.into() {
895 return true;
896 }
897
898 match (arg.kind(), self.target.kind()) {
899 (GenericArgKind::Type(inner_ty), TermKind::Ty(target_ty)) => {
900 use ty::{Infer, TyVar};
901 match (inner_ty.kind(), target_ty.kind()) {
902 (&Infer(TyVar(a_vid)), &Infer(TyVar(b_vid))) => {
903 self.tecx.sub_unification_table_root_var(a_vid)
904 == self.tecx.sub_unification_table_root_var(b_vid)
905 }
906 _ => false,
907 }
908 }
909 (GenericArgKind::Const(inner_ct), TermKind::Const(target_ct)) => {
910 match (inner_ct.kind(), target_ct.kind()) {
911 (
912 ty::ConstKind::Infer(ty::InferConst::Var(a_vid)),
913 ty::ConstKind::Infer(ty::InferConst::Var(b_vid)),
914 ) => self.tecx.root_const_var(a_vid) == self.tecx.root_const_var(b_vid),
915 _ => false,
916 }
917 }
918 _ => false,
919 }
920 }
921
922 fn generic_arg_contains_target(&self, arg: GenericArg<'tcx>) -> bool {
925 let mut walker = arg.walk();
926 while let Some(inner) = walker.next() {
927 if self.generic_arg_is_target(inner) {
928 return true;
929 }
930 match inner.kind() {
931 GenericArgKind::Lifetime(_) => {}
932 GenericArgKind::Type(ty) => {
933 if matches!(
934 ty.kind(),
935 ty::Alias(ty::Opaque, ..)
936 | ty::Closure(..)
937 | ty::CoroutineClosure(..)
938 | ty::Coroutine(..)
939 ) {
940 walker.skip_current_subtree();
951 }
952 }
953 GenericArgKind::Const(ct) => {
954 if matches!(ct.kind(), ty::ConstKind::Unevaluated(..)) {
955 walker.skip_current_subtree();
958 }
959 }
960 }
961 }
962 false
963 }
964
965 fn expr_inferred_arg_iter(
966 &self,
967 expr: &'tcx hir::Expr<'tcx>,
968 ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
969 let tcx = self.tecx.tcx;
970 match expr.kind {
971 hir::ExprKind::Path(ref path) => {
972 if let Some(args) = self.node_args_opt(expr.hir_id) {
973 return self.path_inferred_arg_iter(expr.hir_id, args, path);
974 }
975 }
976 hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _)
987 if matches!(path.res, Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) => {
994 if let Some(ty) = self.opt_node_type(expr.hir_id)
995 && let ty::Adt(_, args) = ty.kind()
996 {
997 return Box::new(self.resolved_path_inferred_arg_iter(path, args));
998 }
999 }
1000 hir::ExprKind::MethodCall(segment, ..) => {
1001 if let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) {
1002 let generics = tcx.generics_of(def_id);
1003 let insertable: Option<_> = try {
1004 if generics.has_impl_trait() {
1005 None?
1006 }
1007 let args = self.node_args_opt(expr.hir_id)?;
1008 let span = tcx.hir_span(segment.hir_id);
1009 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1010 InsertableGenericArgs {
1011 insert_span,
1012 args,
1013 generics_def_id: def_id,
1014 def_id,
1015 have_turbofish: false,
1016 }
1017 };
1018 return Box::new(insertable.into_iter());
1019 }
1020 }
1021 _ => {}
1022 }
1023
1024 Box::new(iter::empty())
1025 }
1026
1027 fn resolved_path_inferred_arg_iter(
1028 &self,
1029 path: &'tcx hir::Path<'tcx>,
1030 args: GenericArgsRef<'tcx>,
1031 ) -> impl Iterator<Item = InsertableGenericArgs<'tcx>> + 'tcx {
1032 let tcx = self.tecx.tcx;
1033 let have_turbofish = path.segments.iter().any(|segment| {
1034 segment.args.is_some_and(|args| args.args.iter().any(|arg| arg.is_ty_or_const()))
1035 });
1036 let last_segment_using_path_data: Option<_> = try {
1042 let generics_def_id = tcx.res_generics_def_id(path.res)?;
1043 let generics = tcx.generics_of(generics_def_id);
1044 if generics.has_impl_trait() {
1045 do yeet ();
1046 }
1047 let insert_span =
1048 path.segments.last().unwrap().ident.span.shrink_to_hi().with_hi(path.span.hi());
1049 InsertableGenericArgs {
1050 insert_span,
1051 args,
1052 generics_def_id,
1053 def_id: path.res.def_id(),
1054 have_turbofish,
1055 }
1056 };
1057
1058 path.segments
1059 .iter()
1060 .filter_map(move |segment| {
1061 let res = segment.res;
1062 let generics_def_id = tcx.res_generics_def_id(res)?;
1063 let generics = tcx.generics_of(generics_def_id);
1064 if generics.has_impl_trait() {
1065 return None;
1066 }
1067 let span = tcx.hir_span(segment.hir_id);
1068 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1069 Some(InsertableGenericArgs {
1070 insert_span,
1071 args,
1072 generics_def_id,
1073 def_id: res.def_id(),
1074 have_turbofish,
1075 })
1076 })
1077 .chain(last_segment_using_path_data)
1078 }
1079
1080 fn path_inferred_arg_iter(
1081 &self,
1082 hir_id: HirId,
1083 args: GenericArgsRef<'tcx>,
1084 qpath: &'tcx hir::QPath<'tcx>,
1085 ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
1086 let tcx = self.tecx.tcx;
1087 match qpath {
1088 hir::QPath::Resolved(_self_ty, path) => {
1089 Box::new(self.resolved_path_inferred_arg_iter(path, args))
1090 }
1091 hir::QPath::TypeRelative(ty, segment) => {
1092 let Some(def_id) = self.typeck_results.type_dependent_def_id(hir_id) else {
1093 return Box::new(iter::empty());
1094 };
1095
1096 let generics = tcx.generics_of(def_id);
1097 let segment: Option<_> = try {
1098 if !segment.infer_args || generics.has_impl_trait() {
1099 do yeet ();
1100 }
1101 let span = tcx.hir_span(segment.hir_id);
1102 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1103 InsertableGenericArgs {
1104 insert_span,
1105 args,
1106 generics_def_id: def_id,
1107 def_id,
1108 have_turbofish: false,
1109 }
1110 };
1111
1112 let parent_def_id = generics.parent.unwrap();
1113 if let DefKind::Impl { .. } = tcx.def_kind(parent_def_id) {
1114 let parent_ty = tcx.type_of(parent_def_id).instantiate(tcx, args);
1115 match (parent_ty.kind(), &ty.kind) {
1116 (
1117 ty::Adt(def, args),
1118 hir::TyKind::Path(hir::QPath::Resolved(_self_ty, path)),
1119 ) => {
1120 if tcx.res_generics_def_id(path.res) != Some(def.did()) {
1121 match path.res {
1122 Res::Def(DefKind::TyAlias, _) => {
1123 }
1130 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {}
1133 _ => warn!(
1134 "unexpected path: def={:?} args={:?} path={:?}",
1135 def, args, path,
1136 ),
1137 }
1138 } else {
1139 return Box::new(
1140 self.resolved_path_inferred_arg_iter(path, args).chain(segment),
1141 );
1142 }
1143 }
1144 _ => (),
1145 }
1146 }
1147
1148 Box::new(segment.into_iter())
1149 }
1150 }
1151 }
1152}
1153
1154impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> {
1155 type NestedFilter = nested_filter::OnlyBodies;
1156
1157 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1158 self.tecx.tcx
1159 }
1160
1161 fn visit_local(&mut self, local: &'tcx LetStmt<'tcx>) {
1162 intravisit::walk_local(self, local);
1163
1164 if let Some(ty) = self.opt_node_type(local.hir_id) {
1165 if self.generic_arg_contains_target(ty.into()) {
1166 match local.source {
1167 LocalSource::Normal if local.ty.is_none() => {
1168 self.update_infer_source(InferSource {
1169 span: local.pat.span,
1170 kind: InferSourceKind::LetBinding {
1171 insert_span: local.pat.span.shrink_to_hi(),
1172 pattern_name: local.pat.simple_ident(),
1173 ty,
1174 def_id: None,
1175 },
1176 })
1177 }
1178 _ => {}
1179 }
1180 }
1181 }
1182 }
1183
1184 fn visit_body(&mut self, body: &Body<'tcx>) {
1187 for param in body.params {
1188 debug!(
1189 "param: span {:?}, ty_span {:?}, pat.span {:?}",
1190 param.span, param.ty_span, param.pat.span
1191 );
1192 if param.ty_span != param.pat.span {
1193 debug!("skipping param: has explicit type");
1194 continue;
1195 }
1196
1197 let Some(param_ty) = self.opt_node_type(param.hir_id) else { continue };
1198
1199 if self.generic_arg_contains_target(param_ty.into()) {
1200 self.update_infer_source(InferSource {
1201 span: param.pat.span,
1202 kind: InferSourceKind::ClosureArg {
1203 insert_span: param.pat.span.shrink_to_hi(),
1204 ty: param_ty,
1205 kind: param.pat.kind,
1206 },
1207 })
1208 }
1209 }
1210 intravisit::walk_body(self, body);
1211 }
1212
1213 #[instrument(level = "debug", skip(self))]
1214 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1215 let tcx = self.tecx.tcx;
1216 match expr.kind {
1217 ExprKind::Call(func, args) => {
1220 for arg in args {
1221 self.visit_expr(arg);
1222 }
1223 self.visit_expr(func);
1224 }
1225 _ => intravisit::walk_expr(self, expr),
1226 }
1227
1228 for args in self.expr_inferred_arg_iter(expr) {
1229 debug!(?args);
1230 let InsertableGenericArgs {
1231 insert_span,
1232 args,
1233 generics_def_id,
1234 def_id,
1235 have_turbofish,
1236 } = args;
1237 let generics = tcx.generics_of(generics_def_id);
1238 if let Some(mut argument_index) = generics
1239 .own_args(args)
1240 .iter()
1241 .position(|&arg| self.generic_arg_contains_target(arg))
1242 {
1243 if generics.parent.is_none() && generics.has_self {
1244 argument_index += 1;
1245 }
1246 let args = self.tecx.resolve_vars_if_possible(args);
1247 let generic_args =
1248 &generics.own_args_no_defaults(tcx, args)[generics.own_counts().lifetimes..];
1249 let span = match expr.kind {
1250 ExprKind::MethodCall(path, ..) => path.ident.span,
1251 _ => expr.span,
1252 };
1253
1254 self.update_infer_source(InferSource {
1255 span,
1256 kind: InferSourceKind::GenericArg {
1257 insert_span,
1258 argument_index,
1259 generics_def_id,
1260 def_id,
1261 generic_args,
1262 have_turbofish,
1263 },
1264 });
1265 }
1266 }
1267
1268 if let Some(node_ty) = self.opt_node_type(expr.hir_id) {
1269 if let (
1270 &ExprKind::Closure(&Closure { fn_decl, body, fn_decl_span, .. }),
1271 ty::Closure(_, args),
1272 ) = (&expr.kind, node_ty.kind())
1273 {
1274 let output = args.as_closure().sig().output().skip_binder();
1275 if self.generic_arg_contains_target(output.into()) {
1276 let body = self.tecx.tcx.hir_body(body);
1277 let should_wrap_expr = if matches!(body.value.kind, ExprKind::Block(..)) {
1278 None
1279 } else {
1280 Some(body.value.span.shrink_to_hi())
1281 };
1282 self.update_infer_source(InferSource {
1283 span: fn_decl_span,
1284 kind: InferSourceKind::ClosureReturn {
1285 ty: output,
1286 data: &fn_decl.output,
1287 should_wrap_expr,
1288 },
1289 })
1290 }
1291 }
1292 }
1293
1294 let has_impl_trait = |def_id| {
1295 iter::successors(Some(tcx.generics_of(def_id)), |generics| {
1296 generics.parent.map(|def_id| tcx.generics_of(def_id))
1297 })
1298 .any(|generics| generics.has_impl_trait())
1299 };
1300 if let ExprKind::MethodCall(path, receiver, method_args, span) = expr.kind
1301 && let Some(args) = self.node_args_opt(expr.hir_id)
1302 && args.iter().any(|arg| self.generic_arg_contains_target(arg))
1303 && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id)
1304 && self.tecx.tcx.trait_of_assoc(def_id).is_some()
1305 && !has_impl_trait(def_id)
1306 && tcx.hir_opt_delegation_sig_id(expr.hir_id.owner.def_id).is_none()
1309 {
1310 let successor =
1311 method_args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo()));
1312 let args = self.tecx.resolve_vars_if_possible(args);
1313 self.update_infer_source(InferSource {
1314 span: path.ident.span,
1315 kind: InferSourceKind::FullyQualifiedMethodCall {
1316 receiver,
1317 successor,
1318 args,
1319 def_id,
1320 },
1321 })
1322 }
1323 }
1324}