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