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_unification_table_root_var(a_vid)
898 == self.tecx.sub_unification_table_root_var(b_vid)
899 }
900 _ => false,
901 }
902 }
903 (GenericArgKind::Const(inner_ct), TermKind::Const(target_ct)) => {
904 match (inner_ct.kind(), target_ct.kind()) {
905 (
906 ty::ConstKind::Infer(ty::InferConst::Var(a_vid)),
907 ty::ConstKind::Infer(ty::InferConst::Var(b_vid)),
908 ) => self.tecx.root_const_var(a_vid) == self.tecx.root_const_var(b_vid),
909 _ => false,
910 }
911 }
912 _ => false,
913 }
914 }
915
916 fn generic_arg_contains_target(&self, arg: GenericArg<'tcx>) -> bool {
919 let mut walker = arg.walk();
920 while let Some(inner) = walker.next() {
921 if self.generic_arg_is_target(inner) {
922 return true;
923 }
924 match inner.kind() {
925 GenericArgKind::Lifetime(_) => {}
926 GenericArgKind::Type(ty) => {
927 if matches!(
928 ty.kind(),
929 ty::Alias(ty::Opaque, ..)
930 | ty::Closure(..)
931 | ty::CoroutineClosure(..)
932 | ty::Coroutine(..)
933 ) {
934 walker.skip_current_subtree();
945 }
946 }
947 GenericArgKind::Const(ct) => {
948 if matches!(ct.kind(), ty::ConstKind::Unevaluated(..)) {
949 walker.skip_current_subtree();
952 }
953 }
954 }
955 }
956 false
957 }
958
959 fn expr_inferred_arg_iter(
960 &self,
961 expr: &'tcx hir::Expr<'tcx>,
962 ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
963 let tcx = self.tecx.tcx;
964 match expr.kind {
965 hir::ExprKind::Path(ref path) => {
966 if let Some(args) = self.node_args_opt(expr.hir_id) {
967 return self.path_inferred_arg_iter(expr.hir_id, args, path);
968 }
969 }
970 hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _)
981 if matches!(path.res, Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) => {
988 if let Some(ty) = self.opt_node_type(expr.hir_id)
989 && let ty::Adt(_, args) = ty.kind()
990 {
991 return Box::new(self.resolved_path_inferred_arg_iter(path, args));
992 }
993 }
994 hir::ExprKind::MethodCall(segment, ..) => {
995 if let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) {
996 let generics = tcx.generics_of(def_id);
997 let insertable: Option<_> = try {
998 if generics.has_impl_trait() {
999 None?
1000 }
1001 let args = self.node_args_opt(expr.hir_id)?;
1002 let span = tcx.hir_span(segment.hir_id);
1003 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1004 InsertableGenericArgs {
1005 insert_span,
1006 args,
1007 generics_def_id: def_id,
1008 def_id,
1009 have_turbofish: false,
1010 }
1011 };
1012 return Box::new(insertable.into_iter());
1013 }
1014 }
1015 _ => {}
1016 }
1017
1018 Box::new(iter::empty())
1019 }
1020
1021 fn resolved_path_inferred_arg_iter(
1022 &self,
1023 path: &'tcx hir::Path<'tcx>,
1024 args: GenericArgsRef<'tcx>,
1025 ) -> impl Iterator<Item = InsertableGenericArgs<'tcx>> + 'tcx {
1026 let tcx = self.tecx.tcx;
1027 let have_turbofish = path.segments.iter().any(|segment| {
1028 segment.args.is_some_and(|args| args.args.iter().any(|arg| arg.is_ty_or_const()))
1029 });
1030 let last_segment_using_path_data: Option<_> = try {
1036 let generics_def_id = tcx.res_generics_def_id(path.res)?;
1037 let generics = tcx.generics_of(generics_def_id);
1038 if generics.has_impl_trait() {
1039 do yeet ();
1040 }
1041 let insert_span =
1042 path.segments.last().unwrap().ident.span.shrink_to_hi().with_hi(path.span.hi());
1043 InsertableGenericArgs {
1044 insert_span,
1045 args,
1046 generics_def_id,
1047 def_id: path.res.def_id(),
1048 have_turbofish,
1049 }
1050 };
1051
1052 path.segments
1053 .iter()
1054 .filter_map(move |segment| {
1055 let res = segment.res;
1056 let generics_def_id = tcx.res_generics_def_id(res)?;
1057 let generics = tcx.generics_of(generics_def_id);
1058 if generics.has_impl_trait() {
1059 return None;
1060 }
1061 let span = tcx.hir_span(segment.hir_id);
1062 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1063 Some(InsertableGenericArgs {
1064 insert_span,
1065 args,
1066 generics_def_id,
1067 def_id: res.def_id(),
1068 have_turbofish,
1069 })
1070 })
1071 .chain(last_segment_using_path_data)
1072 }
1073
1074 fn path_inferred_arg_iter(
1075 &self,
1076 hir_id: HirId,
1077 args: GenericArgsRef<'tcx>,
1078 qpath: &'tcx hir::QPath<'tcx>,
1079 ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
1080 let tcx = self.tecx.tcx;
1081 match qpath {
1082 hir::QPath::Resolved(_self_ty, path) => {
1083 Box::new(self.resolved_path_inferred_arg_iter(path, args))
1084 }
1085 hir::QPath::TypeRelative(ty, segment) => {
1086 let Some(def_id) = self.typeck_results.type_dependent_def_id(hir_id) else {
1087 return Box::new(iter::empty());
1088 };
1089
1090 let generics = tcx.generics_of(def_id);
1091 let segment: Option<_> = try {
1092 if !segment.infer_args || generics.has_impl_trait() {
1093 do yeet ();
1094 }
1095 let span = tcx.hir_span(segment.hir_id);
1096 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1097 InsertableGenericArgs {
1098 insert_span,
1099 args,
1100 generics_def_id: def_id,
1101 def_id,
1102 have_turbofish: false,
1103 }
1104 };
1105
1106 let parent_def_id = generics.parent.unwrap();
1107 if let DefKind::Impl { .. } = tcx.def_kind(parent_def_id) {
1108 let parent_ty = tcx.type_of(parent_def_id).instantiate(tcx, args);
1109 match (parent_ty.kind(), &ty.kind) {
1110 (
1111 ty::Adt(def, args),
1112 hir::TyKind::Path(hir::QPath::Resolved(_self_ty, path)),
1113 ) => {
1114 if tcx.res_generics_def_id(path.res) != Some(def.did()) {
1115 match path.res {
1116 Res::Def(DefKind::TyAlias, _) => {
1117 }
1124 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {}
1127 _ => warn!(
1128 "unexpected path: def={:?} args={:?} path={:?}",
1129 def, args, path,
1130 ),
1131 }
1132 } else {
1133 return Box::new(
1134 self.resolved_path_inferred_arg_iter(path, args).chain(segment),
1135 );
1136 }
1137 }
1138 _ => (),
1139 }
1140 }
1141
1142 Box::new(segment.into_iter())
1143 }
1144 hir::QPath::LangItem(_, _) => Box::new(iter::empty()),
1145 }
1146 }
1147}
1148
1149impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> {
1150 type NestedFilter = nested_filter::OnlyBodies;
1151
1152 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1153 self.tecx.tcx
1154 }
1155
1156 fn visit_local(&mut self, local: &'tcx LetStmt<'tcx>) {
1157 intravisit::walk_local(self, local);
1158
1159 if let Some(ty) = self.opt_node_type(local.hir_id) {
1160 if self.generic_arg_contains_target(ty.into()) {
1161 match local.source {
1162 LocalSource::Normal if local.ty.is_none() => {
1163 self.update_infer_source(InferSource {
1164 span: local.pat.span,
1165 kind: InferSourceKind::LetBinding {
1166 insert_span: local.pat.span.shrink_to_hi(),
1167 pattern_name: local.pat.simple_ident(),
1168 ty,
1169 def_id: None,
1170 },
1171 })
1172 }
1173 _ => {}
1174 }
1175 }
1176 }
1177 }
1178
1179 fn visit_body(&mut self, body: &Body<'tcx>) {
1182 for param in body.params {
1183 debug!(
1184 "param: span {:?}, ty_span {:?}, pat.span {:?}",
1185 param.span, param.ty_span, param.pat.span
1186 );
1187 if param.ty_span != param.pat.span {
1188 debug!("skipping param: has explicit type");
1189 continue;
1190 }
1191
1192 let Some(param_ty) = self.opt_node_type(param.hir_id) else { continue };
1193
1194 if self.generic_arg_contains_target(param_ty.into()) {
1195 self.update_infer_source(InferSource {
1196 span: param.pat.span,
1197 kind: InferSourceKind::ClosureArg {
1198 insert_span: param.pat.span.shrink_to_hi(),
1199 ty: param_ty,
1200 },
1201 })
1202 }
1203 }
1204 intravisit::walk_body(self, body);
1205 }
1206
1207 #[instrument(level = "debug", skip(self))]
1208 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1209 let tcx = self.tecx.tcx;
1210 match expr.kind {
1211 ExprKind::Call(func, args) => {
1214 for arg in args {
1215 self.visit_expr(arg);
1216 }
1217 self.visit_expr(func);
1218 }
1219 _ => intravisit::walk_expr(self, expr),
1220 }
1221
1222 for args in self.expr_inferred_arg_iter(expr) {
1223 debug!(?args);
1224 let InsertableGenericArgs {
1225 insert_span,
1226 args,
1227 generics_def_id,
1228 def_id,
1229 have_turbofish,
1230 } = args;
1231 let generics = tcx.generics_of(generics_def_id);
1232 if let Some(mut argument_index) = generics
1233 .own_args(args)
1234 .iter()
1235 .position(|&arg| self.generic_arg_contains_target(arg))
1236 {
1237 if generics.parent.is_none() && generics.has_self {
1238 argument_index += 1;
1239 }
1240 let args = self.tecx.resolve_vars_if_possible(args);
1241 let generic_args =
1242 &generics.own_args_no_defaults(tcx, args)[generics.own_counts().lifetimes..];
1243 let span = match expr.kind {
1244 ExprKind::MethodCall(path, ..) => path.ident.span,
1245 _ => expr.span,
1246 };
1247
1248 self.update_infer_source(InferSource {
1249 span,
1250 kind: InferSourceKind::GenericArg {
1251 insert_span,
1252 argument_index,
1253 generics_def_id,
1254 def_id,
1255 generic_args,
1256 have_turbofish,
1257 },
1258 });
1259 }
1260 }
1261
1262 if let Some(node_ty) = self.opt_node_type(expr.hir_id) {
1263 if let (
1264 &ExprKind::Closure(&Closure { fn_decl, body, fn_decl_span, .. }),
1265 ty::Closure(_, args),
1266 ) = (&expr.kind, node_ty.kind())
1267 {
1268 let output = args.as_closure().sig().output().skip_binder();
1269 if self.generic_arg_contains_target(output.into()) {
1270 let body = self.tecx.tcx.hir_body(body);
1271 let should_wrap_expr = if matches!(body.value.kind, ExprKind::Block(..)) {
1272 None
1273 } else {
1274 Some(body.value.span.shrink_to_hi())
1275 };
1276 self.update_infer_source(InferSource {
1277 span: fn_decl_span,
1278 kind: InferSourceKind::ClosureReturn {
1279 ty: output,
1280 data: &fn_decl.output,
1281 should_wrap_expr,
1282 },
1283 })
1284 }
1285 }
1286 }
1287
1288 let has_impl_trait = |def_id| {
1289 iter::successors(Some(tcx.generics_of(def_id)), |generics| {
1290 generics.parent.map(|def_id| tcx.generics_of(def_id))
1291 })
1292 .any(|generics| generics.has_impl_trait())
1293 };
1294 if let ExprKind::MethodCall(path, receiver, method_args, span) = expr.kind
1295 && let Some(args) = self.node_args_opt(expr.hir_id)
1296 && args.iter().any(|arg| self.generic_arg_contains_target(arg))
1297 && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id)
1298 && self.tecx.tcx.trait_of_assoc(def_id).is_some()
1299 && !has_impl_trait(def_id)
1300 && tcx.hir_opt_delegation_sig_id(expr.hir_id.owner.def_id).is_none()
1303 {
1304 let successor =
1305 method_args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo()));
1306 let args = self.tecx.resolve_vars_if_possible(args);
1307 self.update_infer_source(InferSource {
1308 span: path.ident.span,
1309 kind: InferSourceKind::FullyQualifiedMethodCall {
1310 receiver,
1311 successor,
1312 args,
1313 def_id,
1314 },
1315 })
1316 }
1317 }
1318}