2 AmbigousImpl, AmbigousReturn, AnnotationRequired, InferenceBadError, NeedTypeInfoInGenerator,
3 SourceKindMultiSuggestion, SourceKindSubdiag,
5 use crate::infer::error_reporting::TypeErrCtxt;
6 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
7 use crate::infer::InferCtxt;
8 use rustc_errors::IntoDiagnostic;
9 use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, IntoDiagnosticArg};
11 use rustc_hir::def::Res;
12 use rustc_hir::def::{CtorOf, DefKind, Namespace};
13 use rustc_hir::def_id::DefId;
14 use rustc_hir::intravisit::{self, Visitor};
15 use rustc_hir::{Body, Closure, Expr, ExprKind, FnRetTy, HirId, Local, LocalSource};
16 use rustc_middle::hir::nested_filter;
17 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
18 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
19 use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Print, Printer};
20 use rustc_middle::ty::{self, DefIdTree, InferConst};
21 use rustc_middle::ty::{GenericArg, GenericArgKind, SubstsRef};
22 use rustc_middle::ty::{IsSuggestable, Ty, TyCtxt, TypeckResults};
23 use rustc_span::symbol::{kw, Ident};
24 use rustc_span::{BytePos, Span};
28 pub enum TypeAnnotationNeeded {
29 /// ```compile_fail,E0282
30 /// let x = "hello".chars().rev().collect();
33 /// An implementation cannot be chosen unambiguously because of lack of information.
34 /// ```compile_fail,E0283
35 /// let _ = Default::default();
38 /// ```compile_fail,E0284
39 /// let mut d: u64 = 2;
40 /// d = d % 1u32.into();
45 impl Into<rustc_errors::DiagnosticId> for TypeAnnotationNeeded {
46 fn into(self) -> rustc_errors::DiagnosticId {
48 Self::E0282 => rustc_errors::error_code!(E0282),
49 Self::E0283 => rustc_errors::error_code!(E0283),
50 Self::E0284 => rustc_errors::error_code!(E0284),
55 /// Information about a constant or a type containing inference variables.
56 pub struct InferenceDiagnosticsData {
58 pub span: Option<Span>,
59 pub kind: UnderspecifiedArgKind,
60 pub parent: Option<InferenceDiagnosticsParentData>,
63 /// Data on the parent definition where a generic argument was declared.
64 pub struct InferenceDiagnosticsParentData {
70 pub enum UnderspecifiedArgKind {
71 Type { prefix: Cow<'static, str> },
72 Const { is_parameter: bool },
75 impl InferenceDiagnosticsData {
76 fn can_add_more_info(&self) -> bool {
77 !(self.name == "_" && matches!(self.kind, UnderspecifiedArgKind::Type { .. }))
80 fn where_x_is_kind(&self, in_type: Ty<'_>) -> &'static str {
81 if in_type.is_ty_infer() {
83 } else if self.name == "_" {
84 // FIXME: Consider specializing this message if there is a single `_`
92 /// Generate a label for a generic argument which can't be inferred. When not
93 /// much is known about the argument, `use_diag` may be used to describe the
95 fn make_bad_error(&self, span: Span) -> InferenceBadError<'_> {
96 let has_parent = self.parent.is_some();
97 let bad_kind = if self.can_add_more_info() { "more_info" } else { "other" };
98 let (parent_prefix, parent_name) = self
101 .map(|parent| (parent.prefix, parent.name.clone()))
102 .unwrap_or_default();
106 prefix_kind: self.kind.clone(),
107 prefix: self.kind.try_get_prefix().unwrap_or_default(),
108 name: self.name.clone(),
116 impl InferenceDiagnosticsParentData {
117 fn for_parent_def_id(
119 parent_def_id: DefId,
120 ) -> Option<InferenceDiagnosticsParentData> {
122 tcx.def_key(parent_def_id).disambiguated_data.data.get_opt_name()?.to_string();
124 Some(InferenceDiagnosticsParentData {
125 prefix: tcx.def_kind(parent_def_id).descr(parent_def_id),
130 fn for_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<InferenceDiagnosticsParentData> {
131 Self::for_parent_def_id(tcx, tcx.parent(def_id))
135 impl IntoDiagnosticArg for UnderspecifiedArgKind {
136 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
137 let kind = match self {
138 Self::Type { .. } => "type",
139 Self::Const { is_parameter: true } => "const_with_param",
140 Self::Const { is_parameter: false } => "const",
142 rustc_errors::DiagnosticArgValue::Str(kind.into())
146 impl UnderspecifiedArgKind {
147 fn try_get_prefix(&self) -> Option<&str> {
149 Self::Type { prefix } => Some(prefix.as_ref()),
150 Self::Const { .. } => None,
155 fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'tcx>, ns: Namespace) -> FmtPrinter<'a, 'tcx> {
156 let mut printer = FmtPrinter::new(infcx.tcx, ns);
157 let ty_getter = move |ty_vid| {
158 if infcx.probe_ty_var(ty_vid).is_ok() {
159 warn!("resolved ty var in error message");
161 if let TypeVariableOriginKind::TypeParameterDefinition(name, _) =
162 infcx.inner.borrow_mut().type_variables().var_origin(ty_vid).kind
169 printer.ty_infer_name_resolver = Some(Box::new(ty_getter));
170 let const_getter = move |ct_vid| {
171 if infcx.probe_const_var(ct_vid).is_ok() {
172 warn!("resolved const var in error message");
174 if let ConstVariableOriginKind::ConstParameterDefinition(name, _) =
175 infcx.inner.borrow_mut().const_unification_table().probe_value(ct_vid).origin.kind
182 printer.const_infer_name_resolver = Some(Box::new(const_getter));
186 fn ty_to_string<'tcx>(infcx: &InferCtxt<'tcx>, ty: Ty<'tcx>) -> String {
187 let printer = fmt_printer(infcx, Namespace::TypeNS);
188 let ty = infcx.resolve_vars_if_possible(ty);
190 // We don't want the regular output for `fn`s because it includes its path in
191 // invalid pseudo-syntax, we want the `fn`-pointer output instead.
192 ty::FnDef(..) => ty.fn_sig(infcx.tcx).print(printer).unwrap().into_buffer(),
193 // FIXME: The same thing for closures, but this only works when the closure
194 // does not capture anything.
196 // We do have to hide the `extern "rust-call"` ABI in that case though,
197 // which is too much of a bother for now.
198 _ => ty.print(printer).unwrap().into_buffer(),
202 /// We don't want to directly use `ty_to_string` for closures as their type isn't really
203 /// something users are familiar with. Directly printing the `fn_sig` of closures also
204 /// doesn't work as they actually use the "rust-call" API.
205 fn closure_as_fn_str<'tcx>(infcx: &InferCtxt<'tcx>, ty: Ty<'tcx>) -> String {
206 let ty::Closure(_, substs) = ty.kind() else { unreachable!() };
207 let fn_sig = substs.as_closure().sig();
216 .map(|arg| ty_to_string(infcx, arg))
220 .unwrap_or_default();
221 let ret = if fn_sig.output().skip_binder().is_unit() {
224 format!(" -> {}", ty_to_string(infcx, fn_sig.output().skip_binder()))
226 format!("fn({}){}", args, ret)
229 impl<'tcx> InferCtxt<'tcx> {
230 /// Extracts data used by diagnostic for either types or constants
231 /// which were stuck during inference.
232 pub fn extract_inference_diagnostics_data(
234 arg: GenericArg<'tcx>,
235 highlight: Option<ty::print::RegionHighlightMode<'tcx>>,
236 ) -> InferenceDiagnosticsData {
238 GenericArgKind::Type(ty) => {
239 if let ty::Infer(ty::TyVar(ty_vid)) = *ty.kind() {
240 let mut inner = self.inner.borrow_mut();
241 let ty_vars = &inner.type_variables();
242 let var_origin = ty_vars.var_origin(ty_vid);
243 if let TypeVariableOriginKind::TypeParameterDefinition(name, def_id) =
246 if name != kw::SelfUpper {
247 return InferenceDiagnosticsData {
248 name: name.to_string(),
249 span: Some(var_origin.span),
250 kind: UnderspecifiedArgKind::Type {
251 prefix: "type parameter".into(),
253 parent: def_id.and_then(|def_id| {
254 InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id)
261 let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS);
262 if let Some(highlight) = highlight {
263 printer.region_highlight_mode = highlight;
265 InferenceDiagnosticsData {
266 name: ty.print(printer).unwrap().into_buffer(),
268 kind: UnderspecifiedArgKind::Type { prefix: ty.prefix_string(self.tcx) },
272 GenericArgKind::Const(ct) => {
273 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
275 self.inner.borrow_mut().const_unification_table().probe_value(vid).origin;
276 if let ConstVariableOriginKind::ConstParameterDefinition(name, def_id) =
279 return InferenceDiagnosticsData {
280 name: name.to_string(),
281 span: Some(origin.span),
282 kind: UnderspecifiedArgKind::Const { is_parameter: true },
283 parent: InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id),
287 debug_assert!(!origin.span.is_dummy());
288 let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::ValueNS);
289 if let Some(highlight) = highlight {
290 printer.region_highlight_mode = highlight;
292 InferenceDiagnosticsData {
293 name: ct.print(printer).unwrap().into_buffer(),
294 span: Some(origin.span),
295 kind: UnderspecifiedArgKind::Const { is_parameter: false },
299 // If we end up here the `FindInferSourceVisitor`
300 // won't work, as its expected argument isn't an inference variable.
302 // FIXME: Ideally we should look into the generic constant
303 // to figure out which inference var is actually unresolved so that
304 // this path is unreachable.
305 let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::ValueNS);
306 if let Some(highlight) = highlight {
307 printer.region_highlight_mode = highlight;
309 InferenceDiagnosticsData {
310 name: ct.print(printer).unwrap().into_buffer(),
312 kind: UnderspecifiedArgKind::Const { is_parameter: false },
317 GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"),
321 /// Used as a fallback in [TypeErrCtxt::emit_inference_failure_err]
322 /// in case we weren't able to get a better error.
323 fn bad_inference_failure_err(
326 arg_data: InferenceDiagnosticsData,
327 error_code: TypeAnnotationNeeded,
328 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
329 let source_kind = "other";
330 let source_name = "";
331 let failure_span = None;
332 let infer_subdiags = Vec::new();
333 let multi_suggestions = Vec::new();
334 let bad_label = Some(arg_data.make_bad_error(span));
336 TypeAnnotationNeeded::E0282 => AnnotationRequired {
345 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
346 TypeAnnotationNeeded::E0283 => AmbigousImpl {
355 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
356 TypeAnnotationNeeded::E0284 => AmbigousReturn {
365 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
370 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
371 pub fn emit_inference_failure_err(
373 body_id: Option<hir::BodyId>,
375 arg: GenericArg<'tcx>,
376 error_code: TypeAnnotationNeeded,
377 should_label_span: bool,
378 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
379 let arg = self.resolve_vars_if_possible(arg);
380 let arg_data = self.extract_inference_diagnostics_data(arg, None);
382 let Some(typeck_results) = &self.typeck_results else {
383 // If we don't have any typeck results we're outside
384 // of a body, so we won't be able to get better info
386 return self.bad_inference_failure_err(failure_span, arg_data, error_code);
389 let mut local_visitor = FindInferSourceVisitor::new(&self, typeck_results, arg);
390 if let Some(body_id) = body_id {
391 let expr = self.tcx.hir().expect_expr(body_id.hir_id);
392 local_visitor.visit_expr(expr);
395 let Some(InferSource { span, kind }) = local_visitor.infer_source else {
396 return self.bad_inference_failure_err(failure_span, arg_data, error_code)
399 let (source_kind, name) = kind.ty_localized_msg(self);
400 let failure_span = if should_label_span && !failure_span.overlaps(span) {
406 let mut infer_subdiags = Vec::new();
407 let mut multi_suggestions = Vec::new();
409 InferSourceKind::LetBinding { insert_span, pattern_name, ty } => {
410 infer_subdiags.push(SourceKindSubdiag::LetLike {
412 name: pattern_name.map(|name| name.to_string()).unwrap_or_else(String::new),
413 x_kind: arg_data.where_x_is_kind(ty),
414 prefix_kind: arg_data.kind.clone(),
415 prefix: arg_data.kind.try_get_prefix().unwrap_or_default(),
416 arg_name: arg_data.name,
417 kind: if pattern_name.is_some() { "with_pattern" } else { "other" },
418 type_name: ty_to_string(self, ty),
421 InferSourceKind::ClosureArg { insert_span, ty } => {
422 infer_subdiags.push(SourceKindSubdiag::LetLike {
425 x_kind: arg_data.where_x_is_kind(ty),
426 prefix_kind: arg_data.kind.clone(),
427 prefix: arg_data.kind.try_get_prefix().unwrap_or_default(),
428 arg_name: arg_data.name,
430 type_name: ty_to_string(self, ty),
433 InferSourceKind::GenericArg {
441 let generics = self.tcx.generics_of(generics_def_id);
442 let is_type = matches!(arg.unpack(), GenericArgKind::Type(_));
444 let (parent_exists, parent_prefix, parent_name) =
445 InferenceDiagnosticsParentData::for_parent_def_id(self.tcx, generics_def_id)
446 .map_or((false, String::new(), String::new()), |parent| {
447 (true, parent.prefix.to_string(), parent.name)
450 infer_subdiags.push(SourceKindSubdiag::GenericLabel {
453 param_name: generics.params[argument_index].name.to_string(),
459 let args = fmt_printer(self, Namespace::TypeNS)
460 .comma_sep(generic_args.iter().copied().map(|arg| {
461 if arg.is_suggestable(self.tcx, true) {
466 GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"),
467 GenericArgKind::Type(_) => self
468 .next_ty_var(TypeVariableOrigin {
469 span: rustc_span::DUMMY_SP,
470 kind: TypeVariableOriginKind::MiscVariable,
473 GenericArgKind::Const(arg) => self
476 ConstVariableOrigin {
477 span: rustc_span::DUMMY_SP,
478 kind: ConstVariableOriginKind::MiscVariable,
488 infer_subdiags.push(SourceKindSubdiag::GenericSuggestion {
490 arg_count: generic_args.len(),
495 InferSourceKind::FullyQualifiedMethodCall { receiver, successor, substs, def_id } => {
496 let printer = fmt_printer(self, Namespace::ValueNS);
497 let def_path = printer.print_def_path(def_id, substs).unwrap().into_buffer();
499 // We only care about whether we have to add `&` or `&mut ` for now.
500 // This is the case if the last adjustment is a borrow and the
501 // first adjustment was not a builtin deref.
502 let adjustment = match typeck_results.expr_adjustments(receiver) {
504 Adjustment { kind: Adjust::Deref(None), target: _ },
506 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), target: _ },
510 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mut_)), target: _ },
512 AutoBorrowMutability::Mut { .. } => "&mut ",
513 AutoBorrowMutability::Not => "&",
518 multi_suggestions.push(SourceKindMultiSuggestion::new_fully_qualified(
525 InferSourceKind::ClosureReturn { ty, data, should_wrap_expr } => {
526 let ty_info = ty_to_string(self, ty);
527 multi_suggestions.push(SourceKindMultiSuggestion::new_closure_return(
535 TypeAnnotationNeeded::E0282 => AnnotationRequired {
544 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
545 TypeAnnotationNeeded::E0283 => AmbigousImpl {
554 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
555 TypeAnnotationNeeded::E0284 => AmbigousReturn {
564 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
569 impl<'tcx> InferCtxt<'tcx> {
570 pub fn need_type_info_err_in_generator(
572 kind: hir::GeneratorKind,
575 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
576 let ty = self.resolve_vars_if_possible(ty);
577 let data = self.extract_inference_diagnostics_data(ty.into(), None);
579 NeedTypeInfoInGenerator {
580 bad_label: data.make_bad_error(span),
582 generator_kind: GeneratorKindAsDiagArg(kind),
584 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic)
588 pub struct GeneratorKindAsDiagArg(pub hir::GeneratorKind);
590 impl IntoDiagnosticArg for GeneratorKindAsDiagArg {
591 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
592 let kind = match self.0 {
593 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "async_block",
594 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "async_closure",
595 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "async_fn",
596 hir::GeneratorKind::Gen => "generator",
598 rustc_errors::DiagnosticArgValue::Str(kind.into())
603 struct InferSource<'tcx> {
605 kind: InferSourceKind<'tcx>,
609 enum InferSourceKind<'tcx> {
612 pattern_name: Option<Ident>,
621 argument_index: usize,
622 generics_def_id: DefId,
624 generic_args: &'tcx [GenericArg<'tcx>],
625 have_turbofish: bool,
627 FullyQualifiedMethodCall {
628 receiver: &'tcx Expr<'tcx>,
629 /// If the method has other arguments, this is ", " and the start of the first argument,
630 /// while for methods without arguments this is ")" and the end of the method call.
631 successor: (&'static str, BytePos),
632 substs: SubstsRef<'tcx>,
637 data: &'tcx FnRetTy<'tcx>,
638 should_wrap_expr: Option<Span>,
642 impl<'tcx> InferSource<'tcx> {
643 fn from_expansion(&self) -> bool {
644 let source_from_expansion = match self.kind {
645 InferSourceKind::LetBinding { insert_span, .. }
646 | InferSourceKind::ClosureArg { insert_span, .. }
647 | InferSourceKind::GenericArg { insert_span, .. } => insert_span.from_expansion(),
648 InferSourceKind::FullyQualifiedMethodCall { receiver, .. } => {
649 receiver.span.from_expansion()
651 InferSourceKind::ClosureReturn { data, should_wrap_expr, .. } => {
652 data.span().from_expansion() || should_wrap_expr.map_or(false, Span::from_expansion)
655 source_from_expansion || self.span.from_expansion()
659 impl<'tcx> InferSourceKind<'tcx> {
660 fn ty_localized_msg(&self, infcx: &InferCtxt<'tcx>) -> (&'static str, String) {
662 InferSourceKind::LetBinding { ty, .. }
663 | InferSourceKind::ClosureArg { ty, .. }
664 | InferSourceKind::ClosureReturn { ty, .. } => {
666 ("closure", closure_as_fn_str(infcx, ty))
667 } else if !ty.is_ty_infer() {
668 ("normal", ty_to_string(infcx, ty))
670 ("other", String::new())
673 // FIXME: We should be able to add some additional info here.
674 InferSourceKind::GenericArg { .. }
675 | InferSourceKind::FullyQualifiedMethodCall { .. } => ("other", String::new()),
681 struct InsertableGenericArgs<'tcx> {
683 substs: SubstsRef<'tcx>,
684 generics_def_id: DefId,
686 have_turbofish: bool,
689 /// A visitor which searches for the "best" spot to use in the inference error.
691 /// For this it walks over the hir body and tries to check all places where
692 /// inference variables could be bound.
694 /// While doing so, the currently best spot is stored in `infer_source`.
695 /// For details on how we rank spots, see [Self::source_cost]
696 struct FindInferSourceVisitor<'a, 'tcx> {
697 infcx: &'a InferCtxt<'tcx>,
698 typeck_results: &'a TypeckResults<'tcx>,
700 target: GenericArg<'tcx>,
703 infer_source_cost: usize,
704 infer_source: Option<InferSource<'tcx>>,
707 impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> {
709 infcx: &'a InferCtxt<'tcx>,
710 typeck_results: &'a TypeckResults<'tcx>,
711 target: GenericArg<'tcx>,
713 FindInferSourceVisitor {
720 infer_source_cost: usize::MAX,
725 /// Computes cost for the given source.
727 /// Sources with a small cost are prefer and should result
728 /// in a clearer and idiomatic suggestion.
729 fn source_cost(&self, source: &InferSource<'tcx>) -> usize {
730 #[derive(Clone, Copy)]
731 struct CostCtxt<'tcx> {
734 impl<'tcx> CostCtxt<'tcx> {
735 fn arg_cost(self, arg: GenericArg<'tcx>) -> usize {
737 GenericArgKind::Lifetime(_) => 0, // erased
738 GenericArgKind::Type(ty) => self.ty_cost(ty),
739 GenericArgKind::Const(_) => 3, // some non-zero value
742 fn ty_cost(self, ty: Ty<'tcx>) -> usize {
744 ty::Closure(..) => 1000,
745 ty::FnDef(..) => 150,
747 ty::Adt(def, substs) => {
750 .generics_of(def.did())
751 .own_substs_no_defaults(self.tcx, substs)
753 .map(|&arg| self.arg_cost(arg))
756 ty::Tuple(args) => 5 + args.iter().map(|arg| self.ty_cost(arg)).sum::<usize>(),
757 ty::Ref(_, ty, _) => 2 + self.ty_cost(ty),
764 // The sources are listed in order of preference here.
765 let tcx = self.infcx.tcx;
766 let ctx = CostCtxt { tcx };
767 let base_cost = match source.kind {
768 InferSourceKind::LetBinding { ty, .. } => ctx.ty_cost(ty),
769 InferSourceKind::ClosureArg { ty, .. } => ctx.ty_cost(ty),
770 InferSourceKind::GenericArg { def_id, generic_args, .. } => {
771 let variant_cost = match tcx.def_kind(def_id) {
772 // `None::<u32>` and friends are ugly.
773 DefKind::Variant | DefKind::Ctor(CtorOf::Variant, _) => 15,
776 variant_cost + generic_args.iter().map(|&arg| ctx.arg_cost(arg)).sum::<usize>()
778 InferSourceKind::FullyQualifiedMethodCall { substs, .. } => {
779 20 + substs.iter().map(|arg| ctx.arg_cost(arg)).sum::<usize>()
781 InferSourceKind::ClosureReturn { ty, should_wrap_expr, .. } => {
782 30 + ctx.ty_cost(ty) + if should_wrap_expr.is_some() { 10 } else { 0 }
786 let suggestion_may_apply = if source.from_expansion() { 10000 } else { 0 };
788 base_cost + suggestion_may_apply
791 /// Uses `fn source_cost` to determine whether this inference source is preferable to
792 /// previous sources. We generally prefer earlier sources.
793 #[instrument(level = "debug", skip(self))]
794 fn update_infer_source(&mut self, new_source: InferSource<'tcx>) {
795 let cost = self.source_cost(&new_source) + self.attempt;
798 if cost < self.infer_source_cost {
799 self.infer_source_cost = cost;
800 self.infer_source = Some(new_source);
804 fn node_substs_opt(&self, hir_id: HirId) -> Option<SubstsRef<'tcx>> {
805 let substs = self.typeck_results.node_substs_opt(hir_id);
806 self.infcx.resolve_vars_if_possible(substs)
809 fn opt_node_type(&self, hir_id: HirId) -> Option<Ty<'tcx>> {
810 let ty = self.typeck_results.node_type_opt(hir_id);
811 self.infcx.resolve_vars_if_possible(ty)
814 // Check whether this generic argument is the inference variable we
816 fn generic_arg_is_target(&self, arg: GenericArg<'tcx>) -> bool {
817 if arg == self.target {
821 match (arg.unpack(), self.target.unpack()) {
822 (GenericArgKind::Type(inner_ty), GenericArgKind::Type(target_ty)) => {
823 use ty::{Infer, TyVar};
824 match (inner_ty.kind(), target_ty.kind()) {
825 (&Infer(TyVar(a_vid)), &Infer(TyVar(b_vid))) => {
826 self.infcx.inner.borrow_mut().type_variables().sub_unified(a_vid, b_vid)
831 (GenericArgKind::Const(inner_ct), GenericArgKind::Const(target_ct)) => {
832 use ty::InferConst::*;
833 match (inner_ct.kind(), target_ct.kind()) {
834 (ty::ConstKind::Infer(Var(a_vid)), ty::ConstKind::Infer(Var(b_vid))) => self
838 .const_unification_table()
839 .unioned(a_vid, b_vid),
847 /// Does this generic argument contain our target inference variable
848 /// in a way which can be written by the user.
849 fn generic_arg_contains_target(&self, arg: GenericArg<'tcx>) -> bool {
850 let mut walker = arg.walk();
851 while let Some(inner) = walker.next() {
852 if self.generic_arg_is_target(inner) {
855 match inner.unpack() {
856 GenericArgKind::Lifetime(_) => {}
857 GenericArgKind::Type(ty) => {
858 if matches!(ty.kind(), ty::Opaque(..) | ty::Closure(..) | ty::Generator(..)) {
859 // Opaque types can't be named by the user right now.
861 // Both the generic arguments of closures and generators can
862 // also not be named. We may want to only look into the closure
863 // signature in case it has no captures, as that can be represented
864 // using `fn(T) -> R`.
866 // FIXME(type_alias_impl_trait): These opaque types
867 // can actually be named, so it would make sense to
868 // adjust this case and add a test for it.
869 walker.skip_current_subtree();
872 GenericArgKind::Const(ct) => {
873 if matches!(ct.kind(), ty::ConstKind::Unevaluated(..)) {
874 // You can't write the generic arguments for
875 // unevaluated constants.
876 walker.skip_current_subtree();
884 fn expr_inferred_subst_iter(
886 expr: &'tcx hir::Expr<'tcx>,
887 ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
888 let tcx = self.infcx.tcx;
890 hir::ExprKind::Path(ref path) => {
891 if let Some(substs) = self.node_substs_opt(expr.hir_id) {
892 return self.path_inferred_subst_iter(expr.hir_id, substs, path);
895 // FIXME(#98711): Ideally we would also deal with type relative
896 // paths here, even if that is quite rare.
898 // See the `need_type_info/expr-struct-type-relative-gat.rs` test
899 // for an example where that would be needed.
901 // However, the `type_dependent_def_id` for `Self::Output` in an
902 // impl is currently the `DefId` of `Output` in the trait definition
903 // which makes this somewhat difficult and prevents us from just
904 // using `self.path_inferred_subst_iter` here.
905 hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _) => {
906 if let Some(ty) = self.opt_node_type(expr.hir_id) {
907 if let ty::Adt(_, substs) = ty.kind() {
908 return Box::new(self.resolved_path_inferred_subst_iter(path, substs));
912 hir::ExprKind::MethodCall(segment, ..) => {
913 if let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) {
914 let generics = tcx.generics_of(def_id);
915 let insertable: Option<_> = try {
916 if generics.has_impl_trait() {
919 let substs = self.node_substs_opt(expr.hir_id)?;
920 let span = tcx.hir().span(segment.hir_id);
921 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
922 InsertableGenericArgs {
925 generics_def_id: def_id,
927 have_turbofish: false,
930 return Box::new(insertable.into_iter());
936 Box::new(iter::empty())
939 fn resolved_path_inferred_subst_iter(
941 path: &'tcx hir::Path<'tcx>,
942 substs: SubstsRef<'tcx>,
943 ) -> impl Iterator<Item = InsertableGenericArgs<'tcx>> + 'a {
944 let tcx = self.infcx.tcx;
945 let have_turbofish = path.segments.iter().any(|segment| {
946 segment.args.map_or(false, |args| args.args.iter().any(|arg| arg.is_ty_or_const()))
948 // The last segment of a path often has `Res::Err` and the
949 // correct `Res` is the one of the whole path.
951 // FIXME: We deal with that one separately for now,
952 // would be good to remove this special case.
953 let last_segment_using_path_data: Option<_> = try {
954 let generics_def_id = tcx.res_generics_def_id(path.res)?;
955 let generics = tcx.generics_of(generics_def_id);
956 if generics.has_impl_trait() {
960 path.segments.last().unwrap().ident.span.shrink_to_hi().with_hi(path.span.hi());
961 InsertableGenericArgs {
965 def_id: path.res.def_id(),
972 .filter_map(move |segment| {
973 let res = segment.res;
974 let generics_def_id = tcx.res_generics_def_id(res)?;
975 let generics = tcx.generics_of(generics_def_id);
976 if generics.has_impl_trait() {
979 let span = tcx.hir().span(segment.hir_id);
980 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
981 Some(InsertableGenericArgs {
985 def_id: res.def_id(),
989 .chain(last_segment_using_path_data)
992 fn path_inferred_subst_iter(
995 substs: SubstsRef<'tcx>,
996 qpath: &'tcx hir::QPath<'tcx>,
997 ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
998 let tcx = self.infcx.tcx;
1000 hir::QPath::Resolved(_self_ty, path) => {
1001 Box::new(self.resolved_path_inferred_subst_iter(path, substs))
1003 hir::QPath::TypeRelative(ty, segment) => {
1004 let Some(def_id) = self.typeck_results.type_dependent_def_id(hir_id) else {
1005 return Box::new(iter::empty());
1008 let generics = tcx.generics_of(def_id);
1009 let segment: Option<_> = try {
1010 if !segment.infer_args || generics.has_impl_trait() {
1013 let span = tcx.hir().span(segment.hir_id);
1014 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1015 InsertableGenericArgs {
1018 generics_def_id: def_id,
1020 have_turbofish: false,
1024 let parent_def_id = generics.parent.unwrap();
1025 if tcx.def_kind(parent_def_id) == DefKind::Impl {
1026 let parent_ty = tcx.bound_type_of(parent_def_id).subst(tcx, substs);
1027 match (parent_ty.kind(), &ty.kind) {
1029 ty::Adt(def, substs),
1030 hir::TyKind::Path(hir::QPath::Resolved(_self_ty, path)),
1032 if tcx.res_generics_def_id(path.res) != Some(def.did()) {
1034 Res::Def(DefKind::TyAlias, _) => {
1035 // FIXME: Ideally we should support this. For that
1036 // we have to map back from the self type to the
1037 // type alias though. That's difficult.
1039 // See the `need_type_info/type-alias.rs` test for
1042 // There cannot be inference variables in the self type,
1043 // so there's nothing for us to do here.
1044 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {}
1046 "unexpected path: def={:?} substs={:?} path={:?}",
1052 self.resolved_path_inferred_subst_iter(path, substs)
1061 Box::new(segment.into_iter())
1063 hir::QPath::LangItem(_, _, _) => Box::new(iter::empty()),
1068 impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> {
1069 type NestedFilter = nested_filter::OnlyBodies;
1071 fn nested_visit_map(&mut self) -> Self::Map {
1072 self.infcx.tcx.hir()
1075 fn visit_local(&mut self, local: &'tcx Local<'tcx>) {
1076 intravisit::walk_local(self, local);
1078 if let Some(ty) = self.opt_node_type(local.hir_id) {
1079 if self.generic_arg_contains_target(ty.into()) {
1080 match local.source {
1081 LocalSource::Normal if local.ty.is_none() => {
1082 self.update_infer_source(InferSource {
1083 span: local.pat.span,
1084 kind: InferSourceKind::LetBinding {
1085 insert_span: local.pat.span.shrink_to_hi(),
1086 pattern_name: local.pat.simple_ident(),
1097 /// For closures, we first visit the parameters and then the content,
1098 /// as we prefer those.
1099 fn visit_body(&mut self, body: &'tcx Body<'tcx>) {
1100 for param in body.params {
1102 "param: span {:?}, ty_span {:?}, pat.span {:?}",
1103 param.span, param.ty_span, param.pat.span
1105 if param.ty_span != param.pat.span {
1106 debug!("skipping param: has explicit type");
1110 let Some(param_ty) = self.opt_node_type(param.hir_id) else {
1114 if self.generic_arg_contains_target(param_ty.into()) {
1115 self.update_infer_source(InferSource {
1116 span: param.pat.span,
1117 kind: InferSourceKind::ClosureArg {
1118 insert_span: param.pat.span.shrink_to_hi(),
1124 intravisit::walk_body(self, body);
1127 #[instrument(level = "debug", skip(self))]
1128 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1129 let tcx = self.infcx.tcx;
1131 // When encountering `func(arg)` first look into `arg` and then `func`,
1132 // as `arg` is "more specific".
1133 ExprKind::Call(func, args) => {
1135 self.visit_expr(arg);
1137 self.visit_expr(func);
1139 _ => intravisit::walk_expr(self, expr),
1142 for args in self.expr_inferred_subst_iter(expr) {
1144 let InsertableGenericArgs {
1151 let generics = tcx.generics_of(generics_def_id);
1152 if let Some(argument_index) = generics
1155 .position(|&arg| self.generic_arg_contains_target(arg))
1157 let substs = self.infcx.resolve_vars_if_possible(substs);
1158 let generic_args = &generics.own_substs_no_defaults(tcx, substs)
1159 [generics.own_counts().lifetimes..];
1160 let span = match expr.kind {
1161 ExprKind::MethodCall(path, ..) => path.ident.span,
1165 self.update_infer_source(InferSource {
1167 kind: InferSourceKind::GenericArg {
1179 if let Some(node_ty) = self.opt_node_type(expr.hir_id) {
1181 &ExprKind::Closure(&Closure { fn_decl, body, fn_decl_span, .. }),
1182 ty::Closure(_, substs),
1183 ) = (&expr.kind, node_ty.kind())
1185 let output = substs.as_closure().sig().output().skip_binder();
1186 if self.generic_arg_contains_target(output.into()) {
1187 let body = self.infcx.tcx.hir().body(body);
1188 let should_wrap_expr = if matches!(body.value.kind, ExprKind::Block(..)) {
1191 Some(body.value.span.shrink_to_hi())
1193 self.update_infer_source(InferSource {
1195 kind: InferSourceKind::ClosureReturn {
1197 data: &fn_decl.output,
1205 let has_impl_trait = |def_id| {
1206 iter::successors(Some(tcx.generics_of(def_id)), |generics| {
1207 generics.parent.map(|def_id| tcx.generics_of(def_id))
1209 .any(|generics| generics.has_impl_trait())
1211 if let ExprKind::MethodCall(path, receiver, args, span) = expr.kind
1212 && let Some(substs) = self.node_substs_opt(expr.hir_id)
1213 && substs.iter().any(|arg| self.generic_arg_contains_target(arg))
1214 && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id)
1215 && self.infcx.tcx.trait_of_item(def_id).is_some()
1216 && !has_impl_trait(def_id)
1219 args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo()));
1220 let substs = self.infcx.resolve_vars_if_possible(substs);
1221 self.update_infer_source(InferSource {
1222 span: path.ident.span,
1223 kind: InferSourceKind::FullyQualifiedMethodCall {