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};
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: _ },
511 ] => hir::Mutability::from(*mut_).ref_prefix_str(),
515 multi_suggestions.push(SourceKindMultiSuggestion::new_fully_qualified(
522 InferSourceKind::ClosureReturn { ty, data, should_wrap_expr } => {
523 let ty_info = ty_to_string(self, ty);
524 multi_suggestions.push(SourceKindMultiSuggestion::new_closure_return(
532 TypeAnnotationNeeded::E0282 => AnnotationRequired {
541 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
542 TypeAnnotationNeeded::E0283 => AmbigousImpl {
551 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
552 TypeAnnotationNeeded::E0284 => AmbigousReturn {
561 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
566 impl<'tcx> InferCtxt<'tcx> {
567 pub fn need_type_info_err_in_generator(
569 kind: hir::GeneratorKind,
572 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
573 let ty = self.resolve_vars_if_possible(ty);
574 let data = self.extract_inference_diagnostics_data(ty.into(), None);
576 NeedTypeInfoInGenerator {
577 bad_label: data.make_bad_error(span),
579 generator_kind: GeneratorKindAsDiagArg(kind),
581 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic)
585 pub struct GeneratorKindAsDiagArg(pub hir::GeneratorKind);
587 impl IntoDiagnosticArg for GeneratorKindAsDiagArg {
588 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
589 let kind = match self.0 {
590 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "async_block",
591 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "async_closure",
592 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "async_fn",
593 hir::GeneratorKind::Gen => "generator",
595 rustc_errors::DiagnosticArgValue::Str(kind.into())
600 struct InferSource<'tcx> {
602 kind: InferSourceKind<'tcx>,
606 enum InferSourceKind<'tcx> {
609 pattern_name: Option<Ident>,
618 argument_index: usize,
619 generics_def_id: DefId,
621 generic_args: &'tcx [GenericArg<'tcx>],
622 have_turbofish: bool,
624 FullyQualifiedMethodCall {
625 receiver: &'tcx Expr<'tcx>,
626 /// If the method has other arguments, this is ", " and the start of the first argument,
627 /// while for methods without arguments this is ")" and the end of the method call.
628 successor: (&'static str, BytePos),
629 substs: SubstsRef<'tcx>,
634 data: &'tcx FnRetTy<'tcx>,
635 should_wrap_expr: Option<Span>,
639 impl<'tcx> InferSource<'tcx> {
640 fn from_expansion(&self) -> bool {
641 let source_from_expansion = match self.kind {
642 InferSourceKind::LetBinding { insert_span, .. }
643 | InferSourceKind::ClosureArg { insert_span, .. }
644 | InferSourceKind::GenericArg { insert_span, .. } => insert_span.from_expansion(),
645 InferSourceKind::FullyQualifiedMethodCall { receiver, .. } => {
646 receiver.span.from_expansion()
648 InferSourceKind::ClosureReturn { data, should_wrap_expr, .. } => {
649 data.span().from_expansion() || should_wrap_expr.map_or(false, Span::from_expansion)
652 source_from_expansion || self.span.from_expansion()
656 impl<'tcx> InferSourceKind<'tcx> {
657 fn ty_localized_msg(&self, infcx: &InferCtxt<'tcx>) -> (&'static str, String) {
659 InferSourceKind::LetBinding { ty, .. }
660 | InferSourceKind::ClosureArg { ty, .. }
661 | InferSourceKind::ClosureReturn { ty, .. } => {
663 ("closure", closure_as_fn_str(infcx, ty))
664 } else if !ty.is_ty_infer() {
665 ("normal", ty_to_string(infcx, ty))
667 ("other", String::new())
670 // FIXME: We should be able to add some additional info here.
671 InferSourceKind::GenericArg { .. }
672 | InferSourceKind::FullyQualifiedMethodCall { .. } => ("other", String::new()),
678 struct InsertableGenericArgs<'tcx> {
680 substs: SubstsRef<'tcx>,
681 generics_def_id: DefId,
683 have_turbofish: bool,
686 /// A visitor which searches for the "best" spot to use in the inference error.
688 /// For this it walks over the hir body and tries to check all places where
689 /// inference variables could be bound.
691 /// While doing so, the currently best spot is stored in `infer_source`.
692 /// For details on how we rank spots, see [Self::source_cost]
693 struct FindInferSourceVisitor<'a, 'tcx> {
694 infcx: &'a InferCtxt<'tcx>,
695 typeck_results: &'a TypeckResults<'tcx>,
697 target: GenericArg<'tcx>,
700 infer_source_cost: usize,
701 infer_source: Option<InferSource<'tcx>>,
704 impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> {
706 infcx: &'a InferCtxt<'tcx>,
707 typeck_results: &'a TypeckResults<'tcx>,
708 target: GenericArg<'tcx>,
710 FindInferSourceVisitor {
717 infer_source_cost: usize::MAX,
722 /// Computes cost for the given source.
724 /// Sources with a small cost are prefer and should result
725 /// in a clearer and idiomatic suggestion.
726 fn source_cost(&self, source: &InferSource<'tcx>) -> usize {
727 #[derive(Clone, Copy)]
728 struct CostCtxt<'tcx> {
731 impl<'tcx> CostCtxt<'tcx> {
732 fn arg_cost(self, arg: GenericArg<'tcx>) -> usize {
734 GenericArgKind::Lifetime(_) => 0, // erased
735 GenericArgKind::Type(ty) => self.ty_cost(ty),
736 GenericArgKind::Const(_) => 3, // some non-zero value
739 fn ty_cost(self, ty: Ty<'tcx>) -> usize {
741 ty::Closure(..) => 1000,
742 ty::FnDef(..) => 150,
744 ty::Adt(def, substs) => {
747 .generics_of(def.did())
748 .own_substs_no_defaults(self.tcx, substs)
750 .map(|&arg| self.arg_cost(arg))
753 ty::Tuple(args) => 5 + args.iter().map(|arg| self.ty_cost(arg)).sum::<usize>(),
754 ty::Ref(_, ty, _) => 2 + self.ty_cost(ty),
761 // The sources are listed in order of preference here.
762 let tcx = self.infcx.tcx;
763 let ctx = CostCtxt { tcx };
764 let base_cost = match source.kind {
765 InferSourceKind::LetBinding { ty, .. } => ctx.ty_cost(ty),
766 InferSourceKind::ClosureArg { ty, .. } => ctx.ty_cost(ty),
767 InferSourceKind::GenericArg { def_id, generic_args, .. } => {
768 let variant_cost = match tcx.def_kind(def_id) {
769 // `None::<u32>` and friends are ugly.
770 DefKind::Variant | DefKind::Ctor(CtorOf::Variant, _) => 15,
773 variant_cost + generic_args.iter().map(|&arg| ctx.arg_cost(arg)).sum::<usize>()
775 InferSourceKind::FullyQualifiedMethodCall { substs, .. } => {
776 20 + substs.iter().map(|arg| ctx.arg_cost(arg)).sum::<usize>()
778 InferSourceKind::ClosureReturn { ty, should_wrap_expr, .. } => {
779 30 + ctx.ty_cost(ty) + if should_wrap_expr.is_some() { 10 } else { 0 }
783 let suggestion_may_apply = if source.from_expansion() { 10000 } else { 0 };
785 base_cost + suggestion_may_apply
788 /// Uses `fn source_cost` to determine whether this inference source is preferable to
789 /// previous sources. We generally prefer earlier sources.
790 #[instrument(level = "debug", skip(self))]
791 fn update_infer_source(&mut self, new_source: InferSource<'tcx>) {
792 let cost = self.source_cost(&new_source) + self.attempt;
795 if cost < self.infer_source_cost {
796 self.infer_source_cost = cost;
797 self.infer_source = Some(new_source);
801 fn node_substs_opt(&self, hir_id: HirId) -> Option<SubstsRef<'tcx>> {
802 let substs = self.typeck_results.node_substs_opt(hir_id);
803 self.infcx.resolve_vars_if_possible(substs)
806 fn opt_node_type(&self, hir_id: HirId) -> Option<Ty<'tcx>> {
807 let ty = self.typeck_results.node_type_opt(hir_id);
808 self.infcx.resolve_vars_if_possible(ty)
811 // Check whether this generic argument is the inference variable we
813 fn generic_arg_is_target(&self, arg: GenericArg<'tcx>) -> bool {
814 if arg == self.target {
818 match (arg.unpack(), self.target.unpack()) {
819 (GenericArgKind::Type(inner_ty), GenericArgKind::Type(target_ty)) => {
820 use ty::{Infer, TyVar};
821 match (inner_ty.kind(), target_ty.kind()) {
822 (&Infer(TyVar(a_vid)), &Infer(TyVar(b_vid))) => {
823 self.infcx.inner.borrow_mut().type_variables().sub_unified(a_vid, b_vid)
828 (GenericArgKind::Const(inner_ct), GenericArgKind::Const(target_ct)) => {
829 use ty::InferConst::*;
830 match (inner_ct.kind(), target_ct.kind()) {
831 (ty::ConstKind::Infer(Var(a_vid)), ty::ConstKind::Infer(Var(b_vid))) => self
835 .const_unification_table()
836 .unioned(a_vid, b_vid),
844 /// Does this generic argument contain our target inference variable
845 /// in a way which can be written by the user.
846 fn generic_arg_contains_target(&self, arg: GenericArg<'tcx>) -> bool {
847 let mut walker = arg.walk();
848 while let Some(inner) = walker.next() {
849 if self.generic_arg_is_target(inner) {
852 match inner.unpack() {
853 GenericArgKind::Lifetime(_) => {}
854 GenericArgKind::Type(ty) => {
855 if matches!(ty.kind(), ty::Opaque(..) | ty::Closure(..) | ty::Generator(..)) {
856 // Opaque types can't be named by the user right now.
858 // Both the generic arguments of closures and generators can
859 // also not be named. We may want to only look into the closure
860 // signature in case it has no captures, as that can be represented
861 // using `fn(T) -> R`.
863 // FIXME(type_alias_impl_trait): These opaque types
864 // can actually be named, so it would make sense to
865 // adjust this case and add a test for it.
866 walker.skip_current_subtree();
869 GenericArgKind::Const(ct) => {
870 if matches!(ct.kind(), ty::ConstKind::Unevaluated(..)) {
871 // You can't write the generic arguments for
872 // unevaluated constants.
873 walker.skip_current_subtree();
881 fn expr_inferred_subst_iter(
883 expr: &'tcx hir::Expr<'tcx>,
884 ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
885 let tcx = self.infcx.tcx;
887 hir::ExprKind::Path(ref path) => {
888 if let Some(substs) = self.node_substs_opt(expr.hir_id) {
889 return self.path_inferred_subst_iter(expr.hir_id, substs, path);
892 // FIXME(#98711): Ideally we would also deal with type relative
893 // paths here, even if that is quite rare.
895 // See the `need_type_info/expr-struct-type-relative-gat.rs` test
896 // for an example where that would be needed.
898 // However, the `type_dependent_def_id` for `Self::Output` in an
899 // impl is currently the `DefId` of `Output` in the trait definition
900 // which makes this somewhat difficult and prevents us from just
901 // using `self.path_inferred_subst_iter` here.
902 hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _)
903 // FIXME(TaKO8Ki): Ideally we should support this. For that
904 // we have to map back from the self type to the
905 // type alias though. That's difficult.
907 // See the `need_type_info/issue-103053.rs` test for
909 if !matches!(path.res, Res::Def(DefKind::TyAlias, _)) => {
910 if let Some(ty) = self.opt_node_type(expr.hir_id)
911 && let ty::Adt(_, substs) = ty.kind()
913 return Box::new(self.resolved_path_inferred_subst_iter(path, substs));
916 hir::ExprKind::MethodCall(segment, ..) => {
917 if let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) {
918 let generics = tcx.generics_of(def_id);
919 let insertable: Option<_> = try {
920 if generics.has_impl_trait() {
923 let substs = self.node_substs_opt(expr.hir_id)?;
924 let span = tcx.hir().span(segment.hir_id);
925 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
926 InsertableGenericArgs {
929 generics_def_id: def_id,
931 have_turbofish: false,
934 return Box::new(insertable.into_iter());
940 Box::new(iter::empty())
943 fn resolved_path_inferred_subst_iter(
945 path: &'tcx hir::Path<'tcx>,
946 substs: SubstsRef<'tcx>,
947 ) -> impl Iterator<Item = InsertableGenericArgs<'tcx>> + 'a {
948 let tcx = self.infcx.tcx;
949 let have_turbofish = path.segments.iter().any(|segment| {
950 segment.args.map_or(false, |args| args.args.iter().any(|arg| arg.is_ty_or_const()))
952 // The last segment of a path often has `Res::Err` and the
953 // correct `Res` is the one of the whole path.
955 // FIXME: We deal with that one separately for now,
956 // would be good to remove this special case.
957 let last_segment_using_path_data: Option<_> = try {
958 let generics_def_id = tcx.res_generics_def_id(path.res)?;
959 let generics = tcx.generics_of(generics_def_id);
960 if generics.has_impl_trait() {
964 path.segments.last().unwrap().ident.span.shrink_to_hi().with_hi(path.span.hi());
965 InsertableGenericArgs {
969 def_id: path.res.def_id(),
976 .filter_map(move |segment| {
977 let res = segment.res;
978 let generics_def_id = tcx.res_generics_def_id(res)?;
979 let generics = tcx.generics_of(generics_def_id);
980 if generics.has_impl_trait() {
983 let span = tcx.hir().span(segment.hir_id);
984 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
985 Some(InsertableGenericArgs {
989 def_id: res.def_id(),
993 .chain(last_segment_using_path_data)
996 fn path_inferred_subst_iter(
999 substs: SubstsRef<'tcx>,
1000 qpath: &'tcx hir::QPath<'tcx>,
1001 ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
1002 let tcx = self.infcx.tcx;
1004 hir::QPath::Resolved(_self_ty, path) => {
1005 Box::new(self.resolved_path_inferred_subst_iter(path, substs))
1007 hir::QPath::TypeRelative(ty, segment) => {
1008 let Some(def_id) = self.typeck_results.type_dependent_def_id(hir_id) else {
1009 return Box::new(iter::empty());
1012 let generics = tcx.generics_of(def_id);
1013 let segment: Option<_> = try {
1014 if !segment.infer_args || generics.has_impl_trait() {
1017 let span = tcx.hir().span(segment.hir_id);
1018 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1019 InsertableGenericArgs {
1022 generics_def_id: def_id,
1024 have_turbofish: false,
1028 let parent_def_id = generics.parent.unwrap();
1029 if tcx.def_kind(parent_def_id) == DefKind::Impl {
1030 let parent_ty = tcx.bound_type_of(parent_def_id).subst(tcx, substs);
1031 match (parent_ty.kind(), &ty.kind) {
1033 ty::Adt(def, substs),
1034 hir::TyKind::Path(hir::QPath::Resolved(_self_ty, path)),
1036 if tcx.res_generics_def_id(path.res) != Some(def.did()) {
1038 Res::Def(DefKind::TyAlias, _) => {
1039 // FIXME: Ideally we should support this. For that
1040 // we have to map back from the self type to the
1041 // type alias though. That's difficult.
1043 // See the `need_type_info/type-alias.rs` test for
1046 // There cannot be inference variables in the self type,
1047 // so there's nothing for us to do here.
1048 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {}
1050 "unexpected path: def={:?} substs={:?} path={:?}",
1056 self.resolved_path_inferred_subst_iter(path, substs)
1065 Box::new(segment.into_iter())
1067 hir::QPath::LangItem(_, _, _) => Box::new(iter::empty()),
1072 impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> {
1073 type NestedFilter = nested_filter::OnlyBodies;
1075 fn nested_visit_map(&mut self) -> Self::Map {
1076 self.infcx.tcx.hir()
1079 fn visit_local(&mut self, local: &'tcx Local<'tcx>) {
1080 intravisit::walk_local(self, local);
1082 if let Some(ty) = self.opt_node_type(local.hir_id) {
1083 if self.generic_arg_contains_target(ty.into()) {
1084 match local.source {
1085 LocalSource::Normal if local.ty.is_none() => {
1086 self.update_infer_source(InferSource {
1087 span: local.pat.span,
1088 kind: InferSourceKind::LetBinding {
1089 insert_span: local.pat.span.shrink_to_hi(),
1090 pattern_name: local.pat.simple_ident(),
1101 /// For closures, we first visit the parameters and then the content,
1102 /// as we prefer those.
1103 fn visit_body(&mut self, body: &'tcx Body<'tcx>) {
1104 for param in body.params {
1106 "param: span {:?}, ty_span {:?}, pat.span {:?}",
1107 param.span, param.ty_span, param.pat.span
1109 if param.ty_span != param.pat.span {
1110 debug!("skipping param: has explicit type");
1114 let Some(param_ty) = self.opt_node_type(param.hir_id) else {
1118 if self.generic_arg_contains_target(param_ty.into()) {
1119 self.update_infer_source(InferSource {
1120 span: param.pat.span,
1121 kind: InferSourceKind::ClosureArg {
1122 insert_span: param.pat.span.shrink_to_hi(),
1128 intravisit::walk_body(self, body);
1131 #[instrument(level = "debug", skip(self))]
1132 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1133 let tcx = self.infcx.tcx;
1135 // When encountering `func(arg)` first look into `arg` and then `func`,
1136 // as `arg` is "more specific".
1137 ExprKind::Call(func, args) => {
1139 self.visit_expr(arg);
1141 self.visit_expr(func);
1143 _ => intravisit::walk_expr(self, expr),
1146 for args in self.expr_inferred_subst_iter(expr) {
1148 let InsertableGenericArgs {
1155 let generics = tcx.generics_of(generics_def_id);
1156 if let Some(argument_index) = generics
1159 .position(|&arg| self.generic_arg_contains_target(arg))
1161 let substs = self.infcx.resolve_vars_if_possible(substs);
1162 let generic_args = &generics.own_substs_no_defaults(tcx, substs)
1163 [generics.own_counts().lifetimes..];
1164 let span = match expr.kind {
1165 ExprKind::MethodCall(path, ..) => path.ident.span,
1169 self.update_infer_source(InferSource {
1171 kind: InferSourceKind::GenericArg {
1183 if let Some(node_ty) = self.opt_node_type(expr.hir_id) {
1185 &ExprKind::Closure(&Closure { fn_decl, body, fn_decl_span, .. }),
1186 ty::Closure(_, substs),
1187 ) = (&expr.kind, node_ty.kind())
1189 let output = substs.as_closure().sig().output().skip_binder();
1190 if self.generic_arg_contains_target(output.into()) {
1191 let body = self.infcx.tcx.hir().body(body);
1192 let should_wrap_expr = if matches!(body.value.kind, ExprKind::Block(..)) {
1195 Some(body.value.span.shrink_to_hi())
1197 self.update_infer_source(InferSource {
1199 kind: InferSourceKind::ClosureReturn {
1201 data: &fn_decl.output,
1209 let has_impl_trait = |def_id| {
1210 iter::successors(Some(tcx.generics_of(def_id)), |generics| {
1211 generics.parent.map(|def_id| tcx.generics_of(def_id))
1213 .any(|generics| generics.has_impl_trait())
1215 if let ExprKind::MethodCall(path, receiver, args, span) = expr.kind
1216 && let Some(substs) = self.node_substs_opt(expr.hir_id)
1217 && substs.iter().any(|arg| self.generic_arg_contains_target(arg))
1218 && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id)
1219 && self.infcx.tcx.trait_of_item(def_id).is_some()
1220 && !has_impl_trait(def_id)
1223 args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo()));
1224 let substs = self.infcx.resolve_vars_if_possible(substs);
1225 self.update_infer_source(InferSource {
1226 span: path.ident.span,
1227 kind: InferSourceKind::FullyQualifiedMethodCall {