2 AmbigousImpl, AmbigousReturn, AnnotationRequired, InferenceBadError, NeedTypeInfoInGenerator,
3 SourceKindMultiSuggestion, SourceKindSubdiag,
5 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
6 use crate::infer::InferCtxt;
7 use rustc_errors::IntoDiagnostic;
8 use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, IntoDiagnosticArg};
10 use rustc_hir::def::Res;
11 use rustc_hir::def::{CtorOf, DefKind, Namespace};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::intravisit::{self, Visitor};
14 use rustc_hir::{Body, Closure, Expr, ExprKind, FnRetTy, HirId, Local, LocalSource};
15 use rustc_middle::hir::nested_filter;
16 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
17 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
18 use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Print, Printer};
19 use rustc_middle::ty::{self, DefIdTree, InferConst};
20 use rustc_middle::ty::{GenericArg, GenericArgKind, SubstsRef};
21 use rustc_middle::ty::{IsSuggestable, Ty, TyCtxt, TypeckResults};
22 use rustc_span::symbol::{kw, Ident};
23 use rustc_span::{BytePos, Span};
27 pub enum TypeAnnotationNeeded {
28 /// ```compile_fail,E0282
29 /// let x = "hello".chars().rev().collect();
32 /// An implementation cannot be chosen unambiguously because of lack of information.
33 /// ```compile_fail,E0283
34 /// let _ = Default::default();
37 /// ```compile_fail,E0284
38 /// let mut d: u64 = 2;
39 /// d = d % 1u32.into();
44 impl Into<rustc_errors::DiagnosticId> for TypeAnnotationNeeded {
45 fn into(self) -> rustc_errors::DiagnosticId {
47 Self::E0282 => rustc_errors::error_code!(E0282),
48 Self::E0283 => rustc_errors::error_code!(E0283),
49 Self::E0284 => rustc_errors::error_code!(E0284),
54 /// Information about a constant or a type containing inference variables.
55 pub struct InferenceDiagnosticsData {
57 pub span: Option<Span>,
58 pub kind: UnderspecifiedArgKind,
59 pub parent: Option<InferenceDiagnosticsParentData>,
62 /// Data on the parent definition where a generic argument was declared.
63 pub struct InferenceDiagnosticsParentData {
69 pub enum UnderspecifiedArgKind {
70 Type { prefix: Cow<'static, str> },
71 Const { is_parameter: bool },
74 impl InferenceDiagnosticsData {
75 fn can_add_more_info(&self) -> bool {
76 !(self.name == "_" && matches!(self.kind, UnderspecifiedArgKind::Type { .. }))
79 fn where_x_is_kind(&self, in_type: Ty<'_>) -> &'static str {
80 if in_type.is_ty_infer() {
82 } else if self.name == "_" {
83 // FIXME: Consider specializing this message if there is a single `_`
91 /// Generate a label for a generic argument which can't be inferred. When not
92 /// much is known about the argument, `use_diag` may be used to describe the
94 fn make_bad_error(&self, span: Span) -> InferenceBadError<'_> {
95 let has_parent = self.parent.is_some();
96 let bad_kind = if self.can_add_more_info() { "more_info" } else { "other" };
97 let (parent_prefix, parent_name) = self
100 .map(|parent| (parent.prefix, parent.name.clone()))
101 .unwrap_or_default();
105 prefix_kind: self.kind.clone(),
106 prefix: self.kind.try_get_prefix().unwrap_or_default(),
107 name: self.name.clone(),
115 impl InferenceDiagnosticsParentData {
116 fn for_parent_def_id(
118 parent_def_id: DefId,
119 ) -> Option<InferenceDiagnosticsParentData> {
121 tcx.def_key(parent_def_id).disambiguated_data.data.get_opt_name()?.to_string();
123 Some(InferenceDiagnosticsParentData {
124 prefix: tcx.def_kind(parent_def_id).descr(parent_def_id),
129 fn for_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<InferenceDiagnosticsParentData> {
130 Self::for_parent_def_id(tcx, tcx.parent(def_id))
134 impl IntoDiagnosticArg for UnderspecifiedArgKind {
135 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
136 let kind = match self {
137 Self::Type { .. } => "type",
138 Self::Const { is_parameter: true } => "const_with_param",
139 Self::Const { is_parameter: false } => "const",
141 rustc_errors::DiagnosticArgValue::Str(kind.into())
145 impl UnderspecifiedArgKind {
146 fn try_get_prefix(&self) -> Option<&str> {
148 Self::Type { prefix } => Some(prefix.as_ref()),
149 Self::Const { .. } => None,
154 fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'_, 'tcx>, ns: Namespace) -> FmtPrinter<'a, 'tcx> {
155 let mut printer = FmtPrinter::new(infcx.tcx, ns);
156 let ty_getter = move |ty_vid| {
157 if infcx.probe_ty_var(ty_vid).is_ok() {
158 warn!("resolved ty var in error message");
160 if let TypeVariableOriginKind::TypeParameterDefinition(name, _) =
161 infcx.inner.borrow_mut().type_variables().var_origin(ty_vid).kind
168 printer.ty_infer_name_resolver = Some(Box::new(ty_getter));
169 let const_getter = move |ct_vid| {
170 if infcx.probe_const_var(ct_vid).is_ok() {
171 warn!("resolved const var in error message");
173 if let ConstVariableOriginKind::ConstParameterDefinition(name, _) =
174 infcx.inner.borrow_mut().const_unification_table().probe_value(ct_vid).origin.kind
181 printer.const_infer_name_resolver = Some(Box::new(const_getter));
185 fn ty_to_string<'tcx>(infcx: &InferCtxt<'_, 'tcx>, ty: Ty<'tcx>) -> String {
186 let printer = fmt_printer(infcx, Namespace::TypeNS);
187 let ty = infcx.resolve_vars_if_possible(ty);
189 // We don't want the regular output for `fn`s because it includes its path in
190 // invalid pseudo-syntax, we want the `fn`-pointer output instead.
191 ty::FnDef(..) => ty.fn_sig(infcx.tcx).print(printer).unwrap().into_buffer(),
192 // FIXME: The same thing for closures, but this only works when the closure
193 // does not capture anything.
195 // We do have to hide the `extern "rust-call"` ABI in that case though,
196 // which is too much of a bother for now.
197 _ => ty.print(printer).unwrap().into_buffer(),
201 /// We don't want to directly use `ty_to_string` for closures as their type isn't really
202 /// something users are familiar with. Directly printing the `fn_sig` of closures also
203 /// doesn't work as they actually use the "rust-call" API.
204 fn closure_as_fn_str<'tcx>(infcx: &InferCtxt<'_, 'tcx>, ty: Ty<'tcx>) -> String {
205 let ty::Closure(_, substs) = ty.kind() else { unreachable!() };
206 let fn_sig = substs.as_closure().sig();
215 .map(|arg| ty_to_string(infcx, arg))
219 .unwrap_or_default();
220 let ret = if fn_sig.output().skip_binder().is_unit() {
223 format!(" -> {}", ty_to_string(infcx, fn_sig.output().skip_binder()))
225 format!("fn({}){}", args, ret)
228 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
229 /// Extracts data used by diagnostic for either types or constants
230 /// which were stuck during inference.
231 pub fn extract_inference_diagnostics_data(
233 arg: GenericArg<'tcx>,
234 highlight: Option<ty::print::RegionHighlightMode<'tcx>>,
235 ) -> InferenceDiagnosticsData {
237 GenericArgKind::Type(ty) => {
238 if let ty::Infer(ty::TyVar(ty_vid)) = *ty.kind() {
239 let mut inner = self.inner.borrow_mut();
240 let ty_vars = &inner.type_variables();
241 let var_origin = ty_vars.var_origin(ty_vid);
242 if let TypeVariableOriginKind::TypeParameterDefinition(name, def_id) =
245 if name != kw::SelfUpper {
246 return InferenceDiagnosticsData {
247 name: name.to_string(),
248 span: Some(var_origin.span),
249 kind: UnderspecifiedArgKind::Type {
250 prefix: "type parameter".into(),
252 parent: def_id.and_then(|def_id| {
253 InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id)
260 let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS);
261 if let Some(highlight) = highlight {
262 printer.region_highlight_mode = highlight;
264 InferenceDiagnosticsData {
265 name: ty.print(printer).unwrap().into_buffer(),
267 kind: UnderspecifiedArgKind::Type { prefix: ty.prefix_string(self.tcx) },
271 GenericArgKind::Const(ct) => {
272 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
274 self.inner.borrow_mut().const_unification_table().probe_value(vid).origin;
275 if let ConstVariableOriginKind::ConstParameterDefinition(name, def_id) =
278 return InferenceDiagnosticsData {
279 name: name.to_string(),
280 span: Some(origin.span),
281 kind: UnderspecifiedArgKind::Const { is_parameter: true },
282 parent: InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id),
286 debug_assert!(!origin.span.is_dummy());
287 let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::ValueNS);
288 if let Some(highlight) = highlight {
289 printer.region_highlight_mode = highlight;
291 InferenceDiagnosticsData {
292 name: ct.print(printer).unwrap().into_buffer(),
293 span: Some(origin.span),
294 kind: UnderspecifiedArgKind::Const { is_parameter: false },
298 // If we end up here the `FindInferSourceVisitor`
299 // won't work, as its expected argument isn't an inference variable.
301 // FIXME: Ideally we should look into the generic constant
302 // to figure out which inference var is actually unresolved so that
303 // this path is unreachable.
304 let mut printer = ty::print::FmtPrinter::new(self.tcx, Namespace::ValueNS);
305 if let Some(highlight) = highlight {
306 printer.region_highlight_mode = highlight;
308 InferenceDiagnosticsData {
309 name: ct.print(printer).unwrap().into_buffer(),
311 kind: UnderspecifiedArgKind::Const { is_parameter: false },
316 GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"),
320 /// Used as a fallback in [InferCtxt::emit_inference_failure_err]
321 /// in case we weren't able to get a better error.
322 fn bad_inference_failure_err(
325 arg_data: InferenceDiagnosticsData,
326 error_code: TypeAnnotationNeeded,
327 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
328 let source_kind = "other";
329 let source_name = "";
330 let failure_span = None;
331 let infer_subdiags = Vec::new();
332 let multi_suggestions = Vec::new();
333 let bad_label = Some(arg_data.make_bad_error(span));
335 TypeAnnotationNeeded::E0282 => AnnotationRequired {
344 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
345 TypeAnnotationNeeded::E0283 => AmbigousImpl {
354 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
355 TypeAnnotationNeeded::E0284 => AmbigousReturn {
364 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
368 pub fn emit_inference_failure_err(
370 body_id: Option<hir::BodyId>,
372 arg: GenericArg<'tcx>,
373 error_code: TypeAnnotationNeeded,
374 should_label_span: bool,
375 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
376 let arg = self.resolve_vars_if_possible(arg);
377 let arg_data = self.extract_inference_diagnostics_data(arg, None);
379 let Some(typeck_results) = self.in_progress_typeck_results else {
380 // If we don't have any typeck results we're outside
381 // of a body, so we won't be able to get better info
383 return self.bad_inference_failure_err(failure_span, arg_data, error_code);
385 let typeck_results = typeck_results.borrow();
386 let typeck_results = &typeck_results;
388 let mut local_visitor = FindInferSourceVisitor::new(&self, typeck_results, arg);
389 if let Some(body_id) = body_id {
390 let expr = self.tcx.hir().expect_expr(body_id.hir_id);
391 local_visitor.visit_expr(expr);
394 let Some(InferSource { span, kind }) = local_visitor.infer_source else {
395 return self.bad_inference_failure_err(failure_span, arg_data, error_code)
398 let (source_kind, name) = kind.ty_localized_msg(self);
399 let failure_span = if should_label_span && !failure_span.overlaps(span) {
405 let mut infer_subdiags = Vec::new();
406 let mut multi_suggestions = Vec::new();
408 InferSourceKind::LetBinding { insert_span, pattern_name, ty } => {
409 infer_subdiags.push(SourceKindSubdiag::LetLike {
411 name: pattern_name.map(|name| name.to_string()).unwrap_or_else(String::new),
412 x_kind: arg_data.where_x_is_kind(ty),
413 prefix_kind: arg_data.kind.clone(),
414 prefix: arg_data.kind.try_get_prefix().unwrap_or_default(),
415 arg_name: arg_data.name,
416 kind: if pattern_name.is_some() { "with_pattern" } else { "other" },
417 type_name: ty_to_string(self, ty),
420 InferSourceKind::ClosureArg { insert_span, ty } => {
421 infer_subdiags.push(SourceKindSubdiag::LetLike {
424 x_kind: arg_data.where_x_is_kind(ty),
425 prefix_kind: arg_data.kind.clone(),
426 prefix: arg_data.kind.try_get_prefix().unwrap_or_default(),
427 arg_name: arg_data.name,
429 type_name: ty_to_string(self, ty),
432 InferSourceKind::GenericArg {
439 let generics = self.tcx.generics_of(generics_def_id);
440 let is_type = matches!(arg.unpack(), GenericArgKind::Type(_));
442 let (parent_exists, parent_prefix, parent_name) =
443 InferenceDiagnosticsParentData::for_parent_def_id(self.tcx, generics_def_id)
444 .map_or((false, String::new(), String::new()), |parent| {
445 (true, parent.prefix.to_string(), parent.name)
448 infer_subdiags.push(SourceKindSubdiag::GenericLabel {
451 param_name: generics.params[argument_index].name.to_string(),
457 let args = fmt_printer(self, Namespace::TypeNS)
458 .comma_sep(generic_args.iter().copied().map(|arg| {
459 if arg.is_suggestable(self.tcx, true) {
464 GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"),
465 GenericArgKind::Type(_) => self
466 .next_ty_var(TypeVariableOrigin {
467 span: rustc_span::DUMMY_SP,
468 kind: TypeVariableOriginKind::MiscVariable,
471 GenericArgKind::Const(arg) => self
474 ConstVariableOrigin {
475 span: rustc_span::DUMMY_SP,
476 kind: ConstVariableOriginKind::MiscVariable,
485 infer_subdiags.push(SourceKindSubdiag::GenericSuggestion {
487 arg_count: generic_args.len(),
491 InferSourceKind::FullyQualifiedMethodCall { receiver, successor, substs, def_id } => {
492 let printer = fmt_printer(self, Namespace::ValueNS);
493 let def_path = printer.print_def_path(def_id, substs).unwrap().into_buffer();
495 // We only care about whether we have to add `&` or `&mut ` for now.
496 // This is the case if the last adjustment is a borrow and the
497 // first adjustment was not a builtin deref.
498 let adjustment = match typeck_results.expr_adjustments(receiver) {
500 Adjustment { kind: Adjust::Deref(None), target: _ },
502 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), target: _ },
506 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mut_)), target: _ },
508 AutoBorrowMutability::Mut { .. } => "&mut ",
509 AutoBorrowMutability::Not => "&",
514 multi_suggestions.push(SourceKindMultiSuggestion::new_fully_qualified(
521 InferSourceKind::ClosureReturn { ty, data, should_wrap_expr } => {
522 let ty_info = ty_to_string(self, ty);
523 multi_suggestions.push(SourceKindMultiSuggestion::new_closure_return(
531 TypeAnnotationNeeded::E0282 => AnnotationRequired {
540 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
541 TypeAnnotationNeeded::E0283 => AmbigousImpl {
550 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
551 TypeAnnotationNeeded::E0284 => AmbigousReturn {
560 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic),
564 pub fn need_type_info_err_in_generator(
566 kind: hir::GeneratorKind,
569 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
570 let ty = self.resolve_vars_if_possible(ty);
571 let data = self.extract_inference_diagnostics_data(ty.into(), None);
573 NeedTypeInfoInGenerator {
574 bad_label: data.make_bad_error(span),
576 generator_kind: GeneratorKindAsDiagArg(kind),
578 .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic)
582 pub struct GeneratorKindAsDiagArg(pub hir::GeneratorKind);
584 impl IntoDiagnosticArg for GeneratorKindAsDiagArg {
585 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
586 let kind = match self.0 {
587 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "async_block",
588 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "async_closure",
589 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "async_fn",
590 hir::GeneratorKind::Gen => "generator",
592 rustc_errors::DiagnosticArgValue::Str(kind.into())
597 struct InferSource<'tcx> {
599 kind: InferSourceKind<'tcx>,
603 enum InferSourceKind<'tcx> {
606 pattern_name: Option<Ident>,
615 argument_index: usize,
616 generics_def_id: DefId,
618 generic_args: &'tcx [GenericArg<'tcx>],
620 FullyQualifiedMethodCall {
621 receiver: &'tcx Expr<'tcx>,
622 /// If the method has other arguments, this is ", " and the start of the first argument,
623 /// while for methods without arguments this is ")" and the end of the method call.
624 successor: (&'static str, BytePos),
625 substs: SubstsRef<'tcx>,
630 data: &'tcx FnRetTy<'tcx>,
631 should_wrap_expr: Option<Span>,
635 impl<'tcx> InferSource<'tcx> {
636 fn from_expansion(&self) -> bool {
637 let source_from_expansion = match self.kind {
638 InferSourceKind::LetBinding { insert_span, .. }
639 | InferSourceKind::ClosureArg { insert_span, .. }
640 | InferSourceKind::GenericArg { insert_span, .. } => insert_span.from_expansion(),
641 InferSourceKind::FullyQualifiedMethodCall { receiver, .. } => {
642 receiver.span.from_expansion()
644 InferSourceKind::ClosureReturn { data, should_wrap_expr, .. } => {
645 data.span().from_expansion() || should_wrap_expr.map_or(false, Span::from_expansion)
648 source_from_expansion || self.span.from_expansion()
652 impl<'tcx> InferSourceKind<'tcx> {
653 fn ty_localized_msg(&self, infcx: &InferCtxt<'_, 'tcx>) -> (&'static str, String) {
655 InferSourceKind::LetBinding { ty, .. }
656 | InferSourceKind::ClosureArg { ty, .. }
657 | InferSourceKind::ClosureReturn { ty, .. } => {
659 ("closure", closure_as_fn_str(infcx, ty))
660 } else if !ty.is_ty_infer() {
661 ("normal", ty_to_string(infcx, ty))
663 ("other", String::new())
666 // FIXME: We should be able to add some additional info here.
667 InferSourceKind::GenericArg { .. }
668 | InferSourceKind::FullyQualifiedMethodCall { .. } => ("other", String::new()),
674 struct InsertableGenericArgs<'tcx> {
676 substs: SubstsRef<'tcx>,
677 generics_def_id: DefId,
681 /// A visitor which searches for the "best" spot to use in the inference error.
683 /// For this it walks over the hir body and tries to check all places where
684 /// inference variables could be bound.
686 /// While doing so, the currently best spot is stored in `infer_source`.
687 /// For details on how we rank spots, see [Self::source_cost]
688 struct FindInferSourceVisitor<'a, 'tcx> {
689 infcx: &'a InferCtxt<'a, 'tcx>,
690 typeck_results: &'a TypeckResults<'tcx>,
692 target: GenericArg<'tcx>,
695 infer_source_cost: usize,
696 infer_source: Option<InferSource<'tcx>>,
699 impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> {
701 infcx: &'a InferCtxt<'a, 'tcx>,
702 typeck_results: &'a TypeckResults<'tcx>,
703 target: GenericArg<'tcx>,
705 FindInferSourceVisitor {
712 infer_source_cost: usize::MAX,
717 /// Computes cost for the given source.
719 /// Sources with a small cost are prefer and should result
720 /// in a clearer and idiomatic suggestion.
721 fn source_cost(&self, source: &InferSource<'tcx>) -> usize {
722 #[derive(Clone, Copy)]
723 struct CostCtxt<'tcx> {
726 impl<'tcx> CostCtxt<'tcx> {
727 fn arg_cost(self, arg: GenericArg<'tcx>) -> usize {
729 GenericArgKind::Lifetime(_) => 0, // erased
730 GenericArgKind::Type(ty) => self.ty_cost(ty),
731 GenericArgKind::Const(_) => 3, // some non-zero value
734 fn ty_cost(self, ty: Ty<'tcx>) -> usize {
736 ty::Closure(..) => 1000,
737 ty::FnDef(..) => 150,
739 ty::Adt(def, substs) => {
742 .generics_of(def.did())
743 .own_substs_no_defaults(self.tcx, substs)
745 .map(|&arg| self.arg_cost(arg))
748 ty::Tuple(args) => 5 + args.iter().map(|arg| self.ty_cost(arg)).sum::<usize>(),
749 ty::Ref(_, ty, _) => 2 + self.ty_cost(ty),
756 // The sources are listed in order of preference here.
757 let tcx = self.infcx.tcx;
758 let ctx = CostCtxt { tcx };
759 let base_cost = match source.kind {
760 InferSourceKind::LetBinding { ty, .. } => ctx.ty_cost(ty),
761 InferSourceKind::ClosureArg { ty, .. } => ctx.ty_cost(ty),
762 InferSourceKind::GenericArg { def_id, generic_args, .. } => {
763 let variant_cost = match tcx.def_kind(def_id) {
764 // `None::<u32>` and friends are ugly.
765 DefKind::Variant | DefKind::Ctor(CtorOf::Variant, _) => 15,
768 variant_cost + generic_args.iter().map(|&arg| ctx.arg_cost(arg)).sum::<usize>()
770 InferSourceKind::FullyQualifiedMethodCall { substs, .. } => {
771 20 + substs.iter().map(|arg| ctx.arg_cost(arg)).sum::<usize>()
773 InferSourceKind::ClosureReturn { ty, should_wrap_expr, .. } => {
774 30 + ctx.ty_cost(ty) + if should_wrap_expr.is_some() { 10 } else { 0 }
778 let suggestion_may_apply = if source.from_expansion() { 10000 } else { 0 };
780 base_cost + suggestion_may_apply
783 /// Uses `fn source_cost` to determine whether this inference source is preferable to
784 /// previous sources. We generally prefer earlier sources.
785 #[instrument(level = "debug", skip(self))]
786 fn update_infer_source(&mut self, new_source: InferSource<'tcx>) {
787 let cost = self.source_cost(&new_source) + self.attempt;
790 if cost < self.infer_source_cost {
791 self.infer_source_cost = cost;
792 self.infer_source = Some(new_source);
796 fn node_substs_opt(&self, hir_id: HirId) -> Option<SubstsRef<'tcx>> {
797 let substs = self.typeck_results.node_substs_opt(hir_id);
798 self.infcx.resolve_vars_if_possible(substs)
801 fn opt_node_type(&self, hir_id: HirId) -> Option<Ty<'tcx>> {
802 let ty = self.typeck_results.node_type_opt(hir_id);
803 self.infcx.resolve_vars_if_possible(ty)
806 // Check whether this generic argument is the inference variable we
808 fn generic_arg_is_target(&self, arg: GenericArg<'tcx>) -> bool {
809 if arg == self.target {
813 match (arg.unpack(), self.target.unpack()) {
814 (GenericArgKind::Type(inner_ty), GenericArgKind::Type(target_ty)) => {
815 use ty::{Infer, TyVar};
816 match (inner_ty.kind(), target_ty.kind()) {
817 (&Infer(TyVar(a_vid)), &Infer(TyVar(b_vid))) => {
818 self.infcx.inner.borrow_mut().type_variables().sub_unified(a_vid, b_vid)
823 (GenericArgKind::Const(inner_ct), GenericArgKind::Const(target_ct)) => {
824 use ty::InferConst::*;
825 match (inner_ct.kind(), target_ct.kind()) {
826 (ty::ConstKind::Infer(Var(a_vid)), ty::ConstKind::Infer(Var(b_vid))) => self
830 .const_unification_table()
831 .unioned(a_vid, b_vid),
839 /// Does this generic argument contain our target inference variable
840 /// in a way which can be written by the user.
841 fn generic_arg_contains_target(&self, arg: GenericArg<'tcx>) -> bool {
842 let mut walker = arg.walk();
843 while let Some(inner) = walker.next() {
844 if self.generic_arg_is_target(inner) {
847 match inner.unpack() {
848 GenericArgKind::Lifetime(_) => {}
849 GenericArgKind::Type(ty) => {
850 if matches!(ty.kind(), ty::Opaque(..) | ty::Closure(..) | ty::Generator(..)) {
851 // Opaque types can't be named by the user right now.
853 // Both the generic arguments of closures and generators can
854 // also not be named. We may want to only look into the closure
855 // signature in case it has no captures, as that can be represented
856 // using `fn(T) -> R`.
858 // FIXME(type_alias_impl_trait): These opaque types
859 // can actually be named, so it would make sense to
860 // adjust this case and add a test for it.
861 walker.skip_current_subtree();
864 GenericArgKind::Const(ct) => {
865 if matches!(ct.kind(), ty::ConstKind::Unevaluated(..)) {
866 // You can't write the generic arguments for
867 // unevaluated constants.
868 walker.skip_current_subtree();
876 fn expr_inferred_subst_iter(
878 expr: &'tcx hir::Expr<'tcx>,
879 ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
880 let tcx = self.infcx.tcx;
882 hir::ExprKind::Path(ref path) => {
883 if let Some(substs) = self.node_substs_opt(expr.hir_id) {
884 return self.path_inferred_subst_iter(expr.hir_id, substs, path);
887 // FIXME(#98711): Ideally we would also deal with type relative
888 // paths here, even if that is quite rare.
890 // See the `need_type_info/expr-struct-type-relative-gat.rs` test
891 // for an example where that would be needed.
893 // However, the `type_dependent_def_id` for `Self::Output` in an
894 // impl is currently the `DefId` of `Output` in the trait definition
895 // which makes this somewhat difficult and prevents us from just
896 // using `self.path_inferred_subst_iter` here.
897 hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _) => {
898 if let Some(ty) = self.opt_node_type(expr.hir_id) {
899 if let ty::Adt(_, substs) = ty.kind() {
900 return Box::new(self.resolved_path_inferred_subst_iter(path, substs));
904 hir::ExprKind::MethodCall(segment, ..) => {
905 if let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) {
906 let generics = tcx.generics_of(def_id);
907 let insertable: Option<_> = try {
908 if generics.has_impl_trait() {
911 let substs = self.node_substs_opt(expr.hir_id)?;
912 let span = tcx.hir().span(segment.hir_id);
913 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
914 InsertableGenericArgs {
917 generics_def_id: def_id,
921 return Box::new(insertable.into_iter());
927 Box::new(iter::empty())
930 fn resolved_path_inferred_subst_iter(
932 path: &'tcx hir::Path<'tcx>,
933 substs: SubstsRef<'tcx>,
934 ) -> impl Iterator<Item = InsertableGenericArgs<'tcx>> + 'a {
935 let tcx = self.infcx.tcx;
936 // The last segment of a path often has `Res::Err` and the
937 // correct `Res` is the one of the whole path.
939 // FIXME: We deal with that one separately for now,
940 // would be good to remove this special case.
941 let last_segment_using_path_data: Option<_> = try {
942 let generics_def_id = tcx.res_generics_def_id(path.res)?;
943 let generics = tcx.generics_of(generics_def_id);
944 if generics.has_impl_trait() {
948 path.segments.last().unwrap().ident.span.shrink_to_hi().with_hi(path.span.hi());
949 InsertableGenericArgs {
953 def_id: path.res.def_id(),
959 .filter_map(move |segment| {
960 let res = segment.res;
961 let generics_def_id = tcx.res_generics_def_id(res)?;
962 let generics = tcx.generics_of(generics_def_id);
963 if generics.has_impl_trait() {
966 let span = tcx.hir().span(segment.hir_id);
967 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
968 Some(InsertableGenericArgs {
972 def_id: res.def_id(),
975 .chain(last_segment_using_path_data)
978 fn path_inferred_subst_iter(
981 substs: SubstsRef<'tcx>,
982 qpath: &'tcx hir::QPath<'tcx>,
983 ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
984 let tcx = self.infcx.tcx;
986 hir::QPath::Resolved(_self_ty, path) => {
987 Box::new(self.resolved_path_inferred_subst_iter(path, substs))
989 hir::QPath::TypeRelative(ty, segment) => {
990 let Some(def_id) = self.typeck_results.type_dependent_def_id(hir_id) else {
991 return Box::new(iter::empty());
994 let generics = tcx.generics_of(def_id);
995 let segment: Option<_> = try {
996 if !segment.infer_args || generics.has_impl_trait() {
999 let span = tcx.hir().span(segment.hir_id);
1000 let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1001 InsertableGenericArgs { insert_span, substs, generics_def_id: def_id, def_id }
1004 let parent_def_id = generics.parent.unwrap();
1005 if tcx.def_kind(parent_def_id) == DefKind::Impl {
1006 let parent_ty = tcx.bound_type_of(parent_def_id).subst(tcx, substs);
1007 match (parent_ty.kind(), &ty.kind) {
1009 ty::Adt(def, substs),
1010 hir::TyKind::Path(hir::QPath::Resolved(_self_ty, path)),
1012 if tcx.res_generics_def_id(path.res) != Some(def.did()) {
1014 Res::Def(DefKind::TyAlias, _) => {
1015 // FIXME: Ideally we should support this. For that
1016 // we have to map back from the self type to the
1017 // type alias though. That's difficult.
1019 // See the `need_type_info/type-alias.rs` test for
1022 // There cannot be inference variables in the self type,
1023 // so there's nothing for us to do here.
1024 Res::SelfTy { .. } => {}
1026 "unexpected path: def={:?} substs={:?} path={:?}",
1032 self.resolved_path_inferred_subst_iter(path, substs)
1041 Box::new(segment.into_iter())
1043 hir::QPath::LangItem(_, _, _) => Box::new(iter::empty()),
1048 impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> {
1049 type NestedFilter = nested_filter::OnlyBodies;
1051 fn nested_visit_map(&mut self) -> Self::Map {
1052 self.infcx.tcx.hir()
1055 fn visit_local(&mut self, local: &'tcx Local<'tcx>) {
1056 intravisit::walk_local(self, local);
1058 if let Some(ty) = self.opt_node_type(local.hir_id) {
1059 if self.generic_arg_contains_target(ty.into()) {
1060 match local.source {
1061 LocalSource::Normal if local.ty.is_none() => {
1062 self.update_infer_source(InferSource {
1063 span: local.pat.span,
1064 kind: InferSourceKind::LetBinding {
1065 insert_span: local.pat.span.shrink_to_hi(),
1066 pattern_name: local.pat.simple_ident(),
1077 /// For closures, we first visit the parameters and then the content,
1078 /// as we prefer those.
1079 fn visit_body(&mut self, body: &'tcx Body<'tcx>) {
1080 for param in body.params {
1082 "param: span {:?}, ty_span {:?}, pat.span {:?}",
1083 param.span, param.ty_span, param.pat.span
1085 if param.ty_span != param.pat.span {
1086 debug!("skipping param: has explicit type");
1090 let Some(param_ty) = self.opt_node_type(param.hir_id) else {
1094 if self.generic_arg_contains_target(param_ty.into()) {
1095 self.update_infer_source(InferSource {
1096 span: param.pat.span,
1097 kind: InferSourceKind::ClosureArg {
1098 insert_span: param.pat.span.shrink_to_hi(),
1104 intravisit::walk_body(self, body);
1107 #[instrument(level = "debug", skip(self))]
1108 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1109 let tcx = self.infcx.tcx;
1111 // When encountering `func(arg)` first look into `arg` and then `func`,
1112 // as `arg` is "more specific".
1113 ExprKind::Call(func, args) => {
1115 self.visit_expr(arg);
1117 self.visit_expr(func);
1119 _ => intravisit::walk_expr(self, expr),
1122 for args in self.expr_inferred_subst_iter(expr) {
1124 let InsertableGenericArgs { insert_span, substs, generics_def_id, def_id } = args;
1125 let generics = tcx.generics_of(generics_def_id);
1126 if let Some(argument_index) = generics
1129 .position(|&arg| self.generic_arg_contains_target(arg))
1131 let substs = self.infcx.resolve_vars_if_possible(substs);
1132 let generic_args = &generics.own_substs_no_defaults(tcx, substs)
1133 [generics.own_counts().lifetimes..];
1134 let span = match expr.kind {
1135 ExprKind::MethodCall(path, ..) => path.ident.span,
1139 self.update_infer_source(InferSource {
1141 kind: InferSourceKind::GenericArg {
1152 if let Some(node_ty) = self.opt_node_type(expr.hir_id) {
1154 &ExprKind::Closure(&Closure { fn_decl, body, fn_decl_span, .. }),
1155 ty::Closure(_, substs),
1156 ) = (&expr.kind, node_ty.kind())
1158 let output = substs.as_closure().sig().output().skip_binder();
1159 if self.generic_arg_contains_target(output.into()) {
1160 let body = self.infcx.tcx.hir().body(body);
1161 let should_wrap_expr = if matches!(body.value.kind, ExprKind::Block(..)) {
1164 Some(body.value.span.shrink_to_hi())
1166 self.update_infer_source(InferSource {
1168 kind: InferSourceKind::ClosureReturn {
1170 data: &fn_decl.output,
1178 let has_impl_trait = |def_id| {
1179 iter::successors(Some(tcx.generics_of(def_id)), |generics| {
1180 generics.parent.map(|def_id| tcx.generics_of(def_id))
1182 .any(|generics| generics.has_impl_trait())
1184 if let ExprKind::MethodCall(path, receiver, args, span) = expr.kind
1185 && let Some(substs) = self.node_substs_opt(expr.hir_id)
1186 && substs.iter().any(|arg| self.generic_arg_contains_target(arg))
1187 && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id)
1188 && self.infcx.tcx.trait_of_item(def_id).is_some()
1189 && !has_impl_trait(def_id)
1192 args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo()));
1193 let substs = self.infcx.resolve_vars_if_possible(substs);
1194 self.update_infer_source(InferSource {
1195 span: path.ident.span,
1196 kind: InferSourceKind::FullyQualifiedMethodCall {