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