1 //! Code for type-checking closure expressions.
3 use super::{check_fn, Expectation, FnCtxt, GeneratorTypes};
5 use crate::astconv::AstConv;
7 use rustc_hir::def_id::DefId;
8 use rustc_hir::lang_items::LangItem;
9 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
10 use rustc_infer::infer::LateBoundRegionConversionTime;
11 use rustc_infer::infer::{InferOk, InferResult};
12 use rustc_middle::ty::fold::TypeFoldable;
13 use rustc_middle::ty::subst::InternalSubsts;
14 use rustc_middle::ty::{self, Ty};
15 use rustc_span::source_map::Span;
16 use rustc_target::spec::abi::Abi;
17 use rustc_trait_selection::traits::error_reporting::ArgKind;
18 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
22 /// What signature do we *expect* the closure to have from context?
24 struct ExpectedSig<'tcx> {
25 /// Span that gave us this expectation, if we know that.
26 cause_span: Option<Span>,
27 sig: ty::PolyFnSig<'tcx>,
30 struct ClosureSignatures<'tcx> {
31 bound_sig: ty::PolyFnSig<'tcx>,
32 liberated_sig: ty::FnSig<'tcx>,
35 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
36 pub fn check_expr_closure(
39 _capture: hir::CaptureBy,
40 decl: &'tcx hir::FnDecl<'tcx>,
42 gen: Option<hir::Movability>,
43 expected: Expectation<'tcx>,
45 debug!("check_expr_closure(expr={:?},expected={:?})", expr, expected);
47 // It's always helpful for inference if we know the kind of
48 // closure sooner rather than later, so first examine the expected
49 // type, and see if can glean a closure kind from there.
50 let (expected_sig, expected_kind) = match expected.to_option(self) {
51 Some(ty) => self.deduce_expectations_from_expected_type(ty),
54 let body = self.tcx.hir().body(body_id);
55 self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
61 opt_kind: Option<ty::ClosureKind>,
62 decl: &'tcx hir::FnDecl<'tcx>,
63 body: &'tcx hir::Body<'tcx>,
64 gen: Option<hir::Movability>,
65 expected_sig: Option<ExpectedSig<'tcx>>,
67 debug!("check_closure(opt_kind={:?}, expected_sig={:?})", opt_kind, expected_sig);
69 let expr_def_id = self.tcx.hir().local_def_id(expr.hir_id);
71 let ClosureSignatures { bound_sig, liberated_sig } =
72 self.sig_of_closure(expr.hir_id, expr_def_id.to_def_id(), decl, body, expected_sig);
74 debug!("check_closure: ty_of_closure returns {:?}", liberated_sig);
76 let return_type_pre_known = !liberated_sig.output().is_ty_infer();
78 let generator_types = check_fn(
86 return_type_pre_known,
90 let parent_substs = InternalSubsts::identity_for_item(
92 self.tcx.closure_base_def_id(expr_def_id.to_def_id()),
95 let tupled_upvars_ty = self.infcx.next_ty_var(TypeVariableOrigin {
96 kind: TypeVariableOriginKind::ClosureSynthetic,
97 span: self.tcx.hir().span(expr.hir_id),
100 if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types
102 let generator_substs = ty::GeneratorSubsts::new(
104 ty::GeneratorSubstsParts {
108 return_ty: liberated_sig.output(),
114 return self.tcx.mk_generator(
115 expr_def_id.to_def_id(),
116 generator_substs.substs,
121 // Tuple up the arguments and insert the resulting function type into
122 // the `closures` table.
123 let sig = bound_sig.map_bound(|sig| {
125 iter::once(self.tcx.intern_tup(sig.inputs())),
134 "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
135 expr_def_id, sig, opt_kind
138 let closure_kind_ty = match opt_kind {
139 Some(kind) => kind.to_ty(self.tcx),
141 // Create a type variable (for now) to represent the closure kind.
142 // It will be unified during the upvar inference phase (`upvar.rs`)
143 None => self.infcx.next_ty_var(TypeVariableOrigin {
144 // FIXME(eddyb) distinguish closure kind inference variables from the rest.
145 kind: TypeVariableOriginKind::ClosureSynthetic,
150 let closure_substs = ty::ClosureSubsts::new(
152 ty::ClosureSubstsParts {
155 closure_sig_as_fn_ptr_ty: self.tcx.mk_fn_ptr(sig),
160 let closure_type = self.tcx.mk_closure(expr_def_id.to_def_id(), closure_substs.substs);
162 debug!("check_closure: expr.hir_id={:?} closure_type={:?}", expr.hir_id, closure_type);
167 /// Given the expected type, figures out what it can about this closure we
168 /// are about to type check:
169 fn deduce_expectations_from_expected_type(
171 expected_ty: Ty<'tcx>,
172 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
173 debug!("deduce_expectations_from_expected_type(expected_ty={:?})", expected_ty);
175 match *expected_ty.kind() {
176 ty::Dynamic(ref object_type, ..) => {
177 let sig = object_type.projection_bounds().find_map(|pb| {
178 let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
179 self.deduce_sig_from_projection(None, pb)
181 let kind = object_type
183 .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did));
186 ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
188 let expected_sig = ExpectedSig { cause_span: None, sig };
189 (Some(expected_sig), Some(ty::ClosureKind::Fn))
195 fn deduce_expectations_from_obligations(
197 expected_vid: ty::TyVid,
198 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
200 self.obligations_for_self_ty(expected_vid).find_map(|(_, obligation)| {
202 "deduce_expectations_from_obligations: obligation.predicate={:?}",
206 let bound_predicate = obligation.predicate.kind();
207 if let ty::PredicateKind::Projection(proj_predicate) =
208 obligation.predicate.kind().skip_binder()
210 // Given a Projection predicate, we can potentially infer
211 // the complete signature.
212 self.deduce_sig_from_projection(
213 Some(obligation.cause.span),
214 bound_predicate.rebind(proj_predicate),
221 // Even if we can't infer the full signature, we may be able to
222 // infer the kind. This can occur when we elaborate a predicate
223 // like `F : Fn<A>`. Note that due to subtyping we could encounter
224 // many viable options, so pick the most restrictive.
225 let expected_kind = self
226 .obligations_for_self_ty(expected_vid)
227 .filter_map(|(tr, _)| self.tcx.fn_trait_kind_from_lang_item(tr.def_id()))
228 .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
230 (expected_sig, expected_kind)
233 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
234 /// everything we need to know about a closure or generator.
236 /// The `cause_span` should be the span that caused us to
237 /// have this expected signature, or `None` if we can't readily
239 fn deduce_sig_from_projection(
241 cause_span: Option<Span>,
242 projection: ty::PolyProjectionPredicate<'tcx>,
243 ) -> Option<ExpectedSig<'tcx>> {
246 debug!("deduce_sig_from_projection({:?})", projection);
248 let trait_def_id = projection.trait_def_id(tcx);
250 let is_fn = tcx.fn_trait_kind_from_lang_item(trait_def_id).is_some();
251 let gen_trait = tcx.require_lang_item(LangItem::Generator, cause_span);
252 let is_gen = gen_trait == trait_def_id;
253 if !is_fn && !is_gen {
254 debug!("deduce_sig_from_projection: not fn or generator");
259 // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
260 // associated item and not yield.
261 let return_assoc_item =
262 self.tcx.associated_items(gen_trait).in_definition_order().nth(1).unwrap().def_id;
263 if return_assoc_item != projection.projection_def_id() {
264 debug!("deduce_sig_from_projection: not return assoc item of generator");
269 let input_tys = if is_fn {
270 let arg_param_ty = projection.skip_binder().projection_ty.substs.type_at(1);
271 let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty);
272 debug!("deduce_sig_from_projection: arg_param_ty={:?}", arg_param_ty);
274 match arg_param_ty.kind() {
275 ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(),
279 // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
280 // else they must have exactly 1 argument. For now though, just give up in this case.
284 let ret_param_ty = projection.skip_binder().ty;
285 let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty);
286 debug!("deduce_sig_from_projection: ret_param_ty={:?}", ret_param_ty);
288 let sig = projection.rebind(self.tcx.mk_fn_sig(
292 hir::Unsafety::Normal,
295 debug!("deduce_sig_from_projection: sig={:?}", sig);
297 Some(ExpectedSig { cause_span, sig })
304 decl: &hir::FnDecl<'_>,
305 body: &hir::Body<'_>,
306 expected_sig: Option<ExpectedSig<'tcx>>,
307 ) -> ClosureSignatures<'tcx> {
308 if let Some(e) = expected_sig {
309 self.sig_of_closure_with_expectation(hir_id, expr_def_id, decl, body, e)
311 self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body)
315 /// If there is no expected signature, then we will convert the
316 /// types that the user gave into a signature.
317 fn sig_of_closure_no_expectation(
321 decl: &hir::FnDecl<'_>,
322 body: &hir::Body<'_>,
323 ) -> ClosureSignatures<'tcx> {
324 debug!("sig_of_closure_no_expectation()");
326 let bound_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
328 self.closure_sigs(expr_def_id, body, bound_sig)
331 /// Invoked to compute the signature of a closure expression. This
332 /// combines any user-provided type annotations (e.g., `|x: u32|
333 /// -> u32 { .. }`) with the expected signature.
335 /// The approach is as follows:
337 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
338 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
339 /// - If we have no expectation `E`, then the signature of the closure is `S`.
340 /// - Otherwise, the signature of the closure is E. Moreover:
341 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
342 /// - Instantiate all the late-bound regions bound in the closure within `S`
343 /// with fresh (existential) variables, yielding `S'`
344 /// - Require that `E' = S'`
345 /// - We could use some kind of subtyping relationship here,
346 /// I imagine, but equality is easier and works fine for
349 /// The key intuition here is that the user's types must be valid
350 /// from "the inside" of the closure, but the expectation
351 /// ultimately drives the overall signature.
356 /// fn with_closure<F>(_: F)
357 /// where F: Fn(&u32) -> &u32 { .. }
359 /// with_closure(|x: &u32| { ... })
363 /// - E would be `fn(&u32) -> &u32`.
364 /// - S would be `fn(&u32) ->
365 /// - E' is `&'!0 u32 -> &'!0 u32`
366 /// - S' is `&'?0 u32 -> ?T`
368 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
372 /// - `expr_def_id`: the `DefId` of the closure expression
373 /// - `decl`: the HIR declaration of the closure
374 /// - `body`: the body of the closure
375 /// - `expected_sig`: the expected signature (if any). Note that
376 /// this is missing a binder: that is, there may be late-bound
377 /// regions with depth 1, which are bound then by the closure.
378 fn sig_of_closure_with_expectation(
382 decl: &hir::FnDecl<'_>,
383 body: &hir::Body<'_>,
384 expected_sig: ExpectedSig<'tcx>,
385 ) -> ClosureSignatures<'tcx> {
386 debug!("sig_of_closure_with_expectation(expected_sig={:?})", expected_sig);
388 // Watch out for some surprises and just ignore the
389 // expectation if things don't see to match up with what we
391 if expected_sig.sig.c_variadic() != decl.c_variadic {
392 return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body);
393 } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 {
394 return self.sig_of_closure_with_mismatched_number_of_arguments(
402 // Create a `PolyFnSig`. Note the oddity that late bound
403 // regions appearing free in `expected_sig` are now bound up
404 // in this binder we are creating.
405 assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST));
406 let bound_sig = expected_sig.sig.map_bound(|sig| {
408 sig.inputs().iter().cloned(),
411 hir::Unsafety::Normal,
416 // `deduce_expectations_from_expected_type` introduces
417 // late-bound lifetimes defined elsewhere, which we now
418 // anonymize away, so as not to confuse the user.
419 let bound_sig = self.tcx.anonymize_late_bound_regions(bound_sig);
421 let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
423 // Up till this point, we have ignored the annotations that the user
424 // gave. This function will check that they unify successfully.
425 // Along the way, it also writes out entries for types that the user
426 // wrote into our typeck results, which are then later used by the privacy
428 match self.check_supplied_sig_against_expectation(
435 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
436 Err(_) => return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body),
442 fn sig_of_closure_with_mismatched_number_of_arguments(
445 decl: &hir::FnDecl<'_>,
446 body: &hir::Body<'_>,
447 expected_sig: ExpectedSig<'tcx>,
448 ) -> ClosureSignatures<'tcx> {
449 let hir = self.tcx.hir();
450 let expr_map_node = hir.get_if_local(expr_def_id).unwrap();
451 let expected_args: Vec<_> = expected_sig
456 .map(|ty| ArgKind::from_expected_ty(ty, None))
458 let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) {
459 Some((sp, args)) => (Some(sp), args),
460 None => (None, Vec::new()),
463 expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap());
464 self.report_arg_count_mismatch(
473 let error_sig = self.error_sig_of_closure(decl);
475 self.closure_sigs(expr_def_id, body, error_sig)
478 /// Enforce the user's types against the expectation. See
479 /// `sig_of_closure_with_expectation` for details on the overall
481 fn check_supplied_sig_against_expectation(
485 decl: &hir::FnDecl<'_>,
486 body: &hir::Body<'_>,
487 expected_sigs: &ClosureSignatures<'tcx>,
488 ) -> InferResult<'tcx, ()> {
489 // Get the signature S that the user gave.
491 // (See comment on `sig_of_closure_with_expectation` for the
492 // meaning of these letters.)
493 let supplied_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
495 debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig);
497 // FIXME(#45727): As discussed in [this comment][c1], naively
498 // forcing equality here actually results in suboptimal error
499 // messages in some cases. For now, if there would have been
500 // an obvious error, we fallback to declaring the type of the
501 // closure to be the one the user gave, which allows other
502 // error message code to trigger.
504 // However, I think [there is potential to do even better
505 // here][c2], since in *this* code we have the precise span of
506 // the type parameter in question in hand when we report the
509 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
510 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
511 self.infcx.commit_if_ok(|_| {
512 let mut all_obligations = vec![];
514 // The liberated version of this signature should be a subtype
515 // of the liberated form of the expectation.
516 for ((hir_ty, &supplied_ty), expected_ty) in iter::zip(
519 supplied_sig.inputs().skip_binder(), // binder moved to (*) below
521 expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'.
523 // Instantiate (this part of..) S to S', i.e., with fresh variables.
524 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
526 LateBoundRegionConversionTime::FnCall,
527 supplied_sig.inputs().rebind(supplied_ty),
528 ); // recreated from (*) above
530 // Check that E' = S'.
531 let cause = self.misc(hir_ty.span);
532 let InferOk { value: (), obligations } =
533 self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
534 all_obligations.extend(obligations);
537 let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
539 LateBoundRegionConversionTime::FnCall,
540 supplied_sig.output(),
542 let cause = &self.misc(decl.output.span());
543 let InferOk { value: (), obligations } = self
544 .at(cause, self.param_env)
545 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
546 all_obligations.extend(obligations);
548 Ok(InferOk { value: (), obligations: all_obligations })
552 /// If there is no expected signature, then we will convert the
553 /// types that the user gave into a signature.
555 /// Also, record this closure signature for later.
556 fn supplied_sig_of_closure(
560 decl: &hir::FnDecl<'_>,
561 body: &hir::Body<'_>,
562 ) -> ty::PolyFnSig<'tcx> {
563 let astconv: &dyn AstConv<'_> = self;
566 "supplied_sig_of_closure(decl={:?}, body.generator_kind={:?})",
567 decl, body.generator_kind,
570 let bound_vars = self.tcx.late_bound_vars(hir_id);
572 // First, convert the types that the user supplied (if any).
573 let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
574 let supplied_return = match decl.output {
575 hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
576 hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
577 // In the case of the async block that we create for a function body,
578 // we expect the return type of the block to match that of the enclosing
580 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
581 debug!("supplied_sig_of_closure: closure is async fn body");
582 self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| {
583 // AFAIK, deducing the future output
584 // always succeeds *except* in error cases
585 // like #65159. I'd like to return Error
586 // here, but I can't because I can't
587 // easily (and locally) prove that we
588 // *have* reported an
589 // error. --nikomatsakis
590 astconv.ty_infer(None, decl.output.span())
594 _ => astconv.ty_infer(None, decl.output.span()),
598 let result = ty::Binder::bind_with_vars(
603 hir::Unsafety::Normal,
609 debug!("supplied_sig_of_closure: result={:?}", result);
611 let c_result = self.inh.infcx.canonicalize_response(result);
612 self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
617 /// Invoked when we are translating the generator that results
618 /// from desugaring an `async fn`. Returns the "sugared" return
619 /// type of the `async fn` -- that is, the return type that the
620 /// user specified. The "desugared" return type is an `impl
621 /// Future<Output = T>`, so we do this by searching through the
622 /// obligations to extract the `T`.
623 fn deduce_future_output_from_obligations(&self, expr_def_id: DefId) -> Option<Ty<'tcx>> {
624 debug!("deduce_future_output_from_obligations(expr_def_id={:?})", expr_def_id);
626 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
627 span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
630 // In practice, the return type of the surrounding function is
631 // always a (not yet resolved) inference variable, because it
632 // is the hidden type for an `impl Trait` that we are going to
634 let ret_ty = ret_coercion.borrow().expected_ty();
635 let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
636 let ret_vid = match *ret_ty.kind() {
637 ty::Infer(ty::TyVar(ret_vid)) => ret_vid,
638 ty::Error(_) => return None,
640 self.tcx.def_span(expr_def_id),
641 "async fn generator return type not an inference variable"
645 // Search for a pending obligation like
647 // `<R as Future>::Output = T`
649 // where R is the return type we are expecting. This type `T`
650 // will be our output.
651 let output_ty = self.obligations_for_self_ty(ret_vid).find_map(|(_, obligation)| {
652 let bound_predicate = obligation.predicate.kind();
653 if let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder() {
654 self.deduce_future_output_from_projection(
655 obligation.cause.span,
656 bound_predicate.rebind(proj_predicate),
663 debug!("deduce_future_output_from_obligations: output_ty={:?}", output_ty);
667 /// Given a projection like
669 /// `<X as Future>::Output = T`
671 /// where `X` is some type that has no late-bound regions, returns
672 /// `Some(T)`. If the projection is for some other trait, returns
674 fn deduce_future_output_from_projection(
677 predicate: ty::PolyProjectionPredicate<'tcx>,
678 ) -> Option<Ty<'tcx>> {
679 debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
681 // We do not expect any bound regions in our predicate, so
682 // skip past the bound vars.
683 let predicate = match predicate.no_bound_vars() {
686 debug!("deduce_future_output_from_projection: has late-bound regions");
691 // Check that this is a projection from the `Future` trait.
692 let trait_def_id = predicate.projection_ty.trait_def_id(self.tcx);
693 let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span));
694 if trait_def_id != future_trait {
695 debug!("deduce_future_output_from_projection: not a future");
699 // The `Future` trait has only one associted item, `Output`,
700 // so check that this is what we see.
701 let output_assoc_item =
702 self.tcx.associated_items(future_trait).in_definition_order().next().unwrap().def_id;
703 if output_assoc_item != predicate.projection_ty.item_def_id {
706 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
707 predicate.projection_ty.item_def_id,
712 // Extract the type from the projection. Note that there can
713 // be no bound variables in this type because the "self type"
714 // does not have any regions in it.
715 let output_ty = self.resolve_vars_if_possible(predicate.ty);
716 debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
720 /// Converts the types that the user supplied, in case that doing
721 /// so should yield an error, but returns back a signature where
722 /// all parameters are of type `TyErr`.
723 fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
724 let astconv: &dyn AstConv<'_> = self;
726 let supplied_arguments = decl.inputs.iter().map(|a| {
727 // Convert the types that the user supplied (if any), but ignore them.
728 astconv.ast_ty_to_ty(a);
732 if let hir::FnRetTy::Return(ref output) = decl.output {
733 astconv.ast_ty_to_ty(&output);
736 let result = ty::Binder::dummy(self.tcx.mk_fn_sig(
740 hir::Unsafety::Normal,
744 debug!("supplied_sig_of_closure: result={:?}", result);
752 body: &hir::Body<'_>,
753 bound_sig: ty::PolyFnSig<'tcx>,
754 ) -> ClosureSignatures<'tcx> {
755 let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, bound_sig);
756 let liberated_sig = self.inh.normalize_associated_types_in(
762 ClosureSignatures { bound_sig, liberated_sig }