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_def_id.to_def_id(), decl, body, expected_sig);
74 debug!("check_closure: ty_of_closure returns {:?}", liberated_sig);
77 check_fn(self, self.param_env, liberated_sig, decl, expr.hir_id, body, gen).1;
79 let parent_substs = InternalSubsts::identity_for_item(
81 self.tcx.closure_base_def_id(expr_def_id.to_def_id()),
84 let tupled_upvars_ty = self.infcx.next_ty_var(TypeVariableOrigin {
85 kind: TypeVariableOriginKind::ClosureSynthetic,
86 span: self.tcx.hir().span(expr.hir_id),
89 if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types
91 let generator_substs = ty::GeneratorSubsts::new(
93 ty::GeneratorSubstsParts {
97 return_ty: liberated_sig.output(),
103 return self.tcx.mk_generator(
104 expr_def_id.to_def_id(),
105 generator_substs.substs,
110 // Tuple up the arguments and insert the resulting function type into
111 // the `closures` table.
112 let sig = bound_sig.map_bound(|sig| {
114 iter::once(self.tcx.intern_tup(sig.inputs())),
123 "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
124 expr_def_id, sig, opt_kind
127 let closure_kind_ty = match opt_kind {
128 Some(kind) => kind.to_ty(self.tcx),
130 // Create a type variable (for now) to represent the closure kind.
131 // It will be unified during the upvar inference phase (`upvar.rs`)
132 None => self.infcx.next_ty_var(TypeVariableOrigin {
133 // FIXME(eddyb) distinguish closure kind inference variables from the rest.
134 kind: TypeVariableOriginKind::ClosureSynthetic,
139 let closure_substs = ty::ClosureSubsts::new(
141 ty::ClosureSubstsParts {
144 closure_sig_as_fn_ptr_ty: self.tcx.mk_fn_ptr(sig),
149 let closure_type = self.tcx.mk_closure(expr_def_id.to_def_id(), closure_substs.substs);
151 debug!("check_closure: expr.hir_id={:?} closure_type={:?}", expr.hir_id, closure_type);
156 /// Given the expected type, figures out what it can about this closure we
157 /// are about to type check:
158 fn deduce_expectations_from_expected_type(
160 expected_ty: Ty<'tcx>,
161 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
162 debug!("deduce_expectations_from_expected_type(expected_ty={:?})", expected_ty);
164 match *expected_ty.kind() {
165 ty::Dynamic(ref object_type, ..) => {
166 let sig = object_type.projection_bounds().find_map(|pb| {
167 let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
168 self.deduce_sig_from_projection(None, pb)
170 let kind = object_type
172 .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did));
175 ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
177 let expected_sig = ExpectedSig { cause_span: None, sig };
178 (Some(expected_sig), Some(ty::ClosureKind::Fn))
184 fn deduce_expectations_from_obligations(
186 expected_vid: ty::TyVid,
187 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
189 self.obligations_for_self_ty(expected_vid).find_map(|(_, obligation)| {
191 "deduce_expectations_from_obligations: obligation.predicate={:?}",
195 let bound_predicate = obligation.predicate.bound_atom();
196 if let ty::PredicateAtom::Projection(proj_predicate) =
197 obligation.predicate.skip_binders()
199 // Given a Projection predicate, we can potentially infer
200 // the complete signature.
201 self.deduce_sig_from_projection(
202 Some(obligation.cause.span),
203 bound_predicate.rebind(proj_predicate),
210 // Even if we can't infer the full signature, we may be able to
211 // infer the kind. This can occur if there is a trait-reference
212 // like `F : Fn<A>`. Note that due to subtyping we could encounter
213 // many viable options, so pick the most restrictive.
214 let expected_kind = self
215 .obligations_for_self_ty(expected_vid)
216 .filter_map(|(tr, _)| self.tcx.fn_trait_kind_from_lang_item(tr.def_id()))
217 .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
219 (expected_sig, expected_kind)
222 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
223 /// everything we need to know about a closure or generator.
225 /// The `cause_span` should be the span that caused us to
226 /// have this expected signature, or `None` if we can't readily
228 fn deduce_sig_from_projection(
230 cause_span: Option<Span>,
231 projection: ty::PolyProjectionPredicate<'tcx>,
232 ) -> Option<ExpectedSig<'tcx>> {
235 debug!("deduce_sig_from_projection({:?})", projection);
237 let trait_ref = projection.to_poly_trait_ref(tcx);
239 let is_fn = tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some();
240 let gen_trait = tcx.require_lang_item(LangItem::Generator, cause_span);
241 let is_gen = gen_trait == trait_ref.def_id();
242 if !is_fn && !is_gen {
243 debug!("deduce_sig_from_projection: not fn or generator");
248 // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
249 // associated item and not yield.
250 let return_assoc_item =
251 self.tcx.associated_items(gen_trait).in_definition_order().nth(1).unwrap().def_id;
252 if return_assoc_item != projection.projection_def_id() {
253 debug!("deduce_sig_from_projection: not return assoc item of generator");
258 let input_tys = if is_fn {
259 let arg_param_ty = trait_ref.skip_binder().substs.type_at(1);
260 let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty);
261 debug!("deduce_sig_from_projection: arg_param_ty={:?}", arg_param_ty);
263 match arg_param_ty.kind() {
264 ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(),
268 // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
269 // else they must have exactly 1 argument. For now though, just give up in this case.
273 let ret_param_ty = projection.skip_binder().ty;
274 let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty);
275 debug!("deduce_sig_from_projection: ret_param_ty={:?}", ret_param_ty);
277 let sig = projection.rebind(self.tcx.mk_fn_sig(
281 hir::Unsafety::Normal,
284 debug!("deduce_sig_from_projection: sig={:?}", sig);
286 Some(ExpectedSig { cause_span, sig })
292 decl: &hir::FnDecl<'_>,
293 body: &hir::Body<'_>,
294 expected_sig: Option<ExpectedSig<'tcx>>,
295 ) -> ClosureSignatures<'tcx> {
296 if let Some(e) = expected_sig {
297 self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
299 self.sig_of_closure_no_expectation(expr_def_id, decl, body)
303 /// If there is no expected signature, then we will convert the
304 /// types that the user gave into a signature.
305 fn sig_of_closure_no_expectation(
308 decl: &hir::FnDecl<'_>,
309 body: &hir::Body<'_>,
310 ) -> ClosureSignatures<'tcx> {
311 debug!("sig_of_closure_no_expectation()");
313 let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
315 self.closure_sigs(expr_def_id, body, bound_sig)
318 /// Invoked to compute the signature of a closure expression. This
319 /// combines any user-provided type annotations (e.g., `|x: u32|
320 /// -> u32 { .. }`) with the expected signature.
322 /// The approach is as follows:
324 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
325 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
326 /// - If we have no expectation `E`, then the signature of the closure is `S`.
327 /// - Otherwise, the signature of the closure is E. Moreover:
328 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
329 /// - Instantiate all the late-bound regions bound in the closure within `S`
330 /// with fresh (existential) variables, yielding `S'`
331 /// - Require that `E' = S'`
332 /// - We could use some kind of subtyping relationship here,
333 /// I imagine, but equality is easier and works fine for
336 /// The key intuition here is that the user's types must be valid
337 /// from "the inside" of the closure, but the expectation
338 /// ultimately drives the overall signature.
343 /// fn with_closure<F>(_: F)
344 /// where F: Fn(&u32) -> &u32 { .. }
346 /// with_closure(|x: &u32| { ... })
350 /// - E would be `fn(&u32) -> &u32`.
351 /// - S would be `fn(&u32) ->
352 /// - E' is `&'!0 u32 -> &'!0 u32`
353 /// - S' is `&'?0 u32 -> ?T`
355 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
359 /// - `expr_def_id`: the `DefId` of the closure expression
360 /// - `decl`: the HIR declaration of the closure
361 /// - `body`: the body of the closure
362 /// - `expected_sig`: the expected signature (if any). Note that
363 /// this is missing a binder: that is, there may be late-bound
364 /// regions with depth 1, which are bound then by the closure.
365 fn sig_of_closure_with_expectation(
368 decl: &hir::FnDecl<'_>,
369 body: &hir::Body<'_>,
370 expected_sig: ExpectedSig<'tcx>,
371 ) -> ClosureSignatures<'tcx> {
372 debug!("sig_of_closure_with_expectation(expected_sig={:?})", expected_sig);
374 // Watch out for some surprises and just ignore the
375 // expectation if things don't see to match up with what we
377 if expected_sig.sig.c_variadic() != decl.c_variadic {
378 return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
379 } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 {
380 return self.sig_of_closure_with_mismatched_number_of_arguments(
388 // Create a `PolyFnSig`. Note the oddity that late bound
389 // regions appearing free in `expected_sig` are now bound up
390 // in this binder we are creating.
391 assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST));
392 let bound_sig = expected_sig.sig.map_bound(|sig| {
394 sig.inputs().iter().cloned(),
397 hir::Unsafety::Normal,
402 // `deduce_expectations_from_expected_type` introduces
403 // late-bound lifetimes defined elsewhere, which we now
404 // anonymize away, so as not to confuse the user.
405 let bound_sig = self.tcx.anonymize_late_bound_regions(bound_sig);
407 let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
409 // Up till this point, we have ignored the annotations that the user
410 // gave. This function will check that they unify successfully.
411 // Along the way, it also writes out entries for types that the user
412 // wrote into our typeck results, which are then later used by the privacy
414 match self.check_supplied_sig_against_expectation(expr_def_id, decl, body, &closure_sigs) {
415 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
416 Err(_) => return self.sig_of_closure_no_expectation(expr_def_id, decl, body),
422 fn sig_of_closure_with_mismatched_number_of_arguments(
425 decl: &hir::FnDecl<'_>,
426 body: &hir::Body<'_>,
427 expected_sig: ExpectedSig<'tcx>,
428 ) -> ClosureSignatures<'tcx> {
429 let hir = self.tcx.hir();
430 let expr_map_node = hir.get_if_local(expr_def_id).unwrap();
431 let expected_args: Vec<_> = expected_sig
436 .map(|ty| ArgKind::from_expected_ty(ty, None))
438 let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) {
439 Some((sp, args)) => (Some(sp), args),
440 None => (None, Vec::new()),
443 expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap());
444 self.report_arg_count_mismatch(
453 let error_sig = self.error_sig_of_closure(decl);
455 self.closure_sigs(expr_def_id, body, error_sig)
458 /// Enforce the user's types against the expectation. See
459 /// `sig_of_closure_with_expectation` for details on the overall
461 fn check_supplied_sig_against_expectation(
464 decl: &hir::FnDecl<'_>,
465 body: &hir::Body<'_>,
466 expected_sigs: &ClosureSignatures<'tcx>,
467 ) -> InferResult<'tcx, ()> {
468 // Get the signature S that the user gave.
470 // (See comment on `sig_of_closure_with_expectation` for the
471 // meaning of these letters.)
472 let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
474 debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig);
476 // FIXME(#45727): As discussed in [this comment][c1], naively
477 // forcing equality here actually results in suboptimal error
478 // messages in some cases. For now, if there would have been
479 // an obvious error, we fallback to declaring the type of the
480 // closure to be the one the user gave, which allows other
481 // error message code to trigger.
483 // However, I think [there is potential to do even better
484 // here][c2], since in *this* code we have the precise span of
485 // the type parameter in question in hand when we report the
488 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
489 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
490 self.infcx.commit_if_ok(|_| {
491 let mut all_obligations = vec![];
493 // The liberated version of this signature should be a subtype
494 // of the liberated form of the expectation.
495 for ((hir_ty, &supplied_ty), expected_ty) in decl
498 .zip(supplied_sig.inputs().skip_binder()) // binder moved to (*) below
499 .zip(expected_sigs.liberated_sig.inputs())
500 // `liberated_sig` is E'.
502 // Instantiate (this part of..) S to S', i.e., with fresh variables.
503 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
505 LateBoundRegionConversionTime::FnCall,
506 supplied_sig.inputs().rebind(supplied_ty),
507 ); // recreated from (*) above
509 // Check that E' = S'.
510 let cause = self.misc(hir_ty.span);
511 let InferOk { value: (), obligations } =
512 self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
513 all_obligations.extend(obligations);
516 let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
518 LateBoundRegionConversionTime::FnCall,
519 supplied_sig.output(),
521 let cause = &self.misc(decl.output.span());
522 let InferOk { value: (), obligations } = self
523 .at(cause, self.param_env)
524 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
525 all_obligations.extend(obligations);
527 Ok(InferOk { value: (), obligations: all_obligations })
531 /// If there is no expected signature, then we will convert the
532 /// types that the user gave into a signature.
534 /// Also, record this closure signature for later.
535 fn supplied_sig_of_closure(
538 decl: &hir::FnDecl<'_>,
539 body: &hir::Body<'_>,
540 ) -> ty::PolyFnSig<'tcx> {
541 let astconv: &dyn AstConv<'_> = self;
544 "supplied_sig_of_closure(decl={:?}, body.generator_kind={:?})",
545 decl, body.generator_kind,
548 // First, convert the types that the user supplied (if any).
549 let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
550 let supplied_return = match decl.output {
551 hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
552 hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
553 // In the case of the async block that we create for a function body,
554 // we expect the return type of the block to match that of the enclosing
556 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
557 debug!("supplied_sig_of_closure: closure is async fn body");
558 self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| {
559 // AFAIK, deducing the future output
560 // always succeeds *except* in error cases
561 // like #65159. I'd like to return Error
562 // here, but I can't because I can't
563 // easily (and locally) prove that we
564 // *have* reported an
565 // error. --nikomatsakis
566 astconv.ty_infer(None, decl.output.span())
570 _ => astconv.ty_infer(None, decl.output.span()),
574 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
578 hir::Unsafety::Normal,
582 debug!("supplied_sig_of_closure: result={:?}", result);
584 let c_result = self.inh.infcx.canonicalize_response(result);
585 self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
590 /// Invoked when we are translating the generator that results
591 /// from desugaring an `async fn`. Returns the "sugared" return
592 /// type of the `async fn` -- that is, the return type that the
593 /// user specified. The "desugared" return type is a `impl
594 /// Future<Output = T>`, so we do this by searching through the
595 /// obligations to extract the `T`.
596 fn deduce_future_output_from_obligations(&self, expr_def_id: DefId) -> Option<Ty<'tcx>> {
597 debug!("deduce_future_output_from_obligations(expr_def_id={:?})", expr_def_id);
599 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
600 span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
603 // In practice, the return type of the surrounding function is
604 // always a (not yet resolved) inference variable, because it
605 // is the hidden type for an `impl Trait` that we are going to
607 let ret_ty = ret_coercion.borrow().expected_ty();
608 let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
609 let ret_vid = match *ret_ty.kind() {
610 ty::Infer(ty::TyVar(ret_vid)) => ret_vid,
611 ty::Error(_) => return None,
613 self.tcx.def_span(expr_def_id),
614 "async fn generator return type not an inference variable"
618 // Search for a pending obligation like
620 // `<R as Future>::Output = T`
622 // where R is the return type we are expecting. This type `T`
623 // will be our output.
624 let output_ty = self.obligations_for_self_ty(ret_vid).find_map(|(_, obligation)| {
625 let bound_predicate = obligation.predicate.bound_atom();
626 if let ty::PredicateAtom::Projection(proj_predicate) = bound_predicate.skip_binder() {
627 self.deduce_future_output_from_projection(
628 obligation.cause.span,
629 bound_predicate.rebind(proj_predicate),
636 debug!("deduce_future_output_from_obligations: output_ty={:?}", output_ty);
640 /// Given a projection like
642 /// `<X as Future>::Output = T`
644 /// where `X` is some type that has no late-bound regions, returns
645 /// `Some(T)`. If the projection is for some other trait, returns
647 fn deduce_future_output_from_projection(
650 predicate: ty::PolyProjectionPredicate<'tcx>,
651 ) -> Option<Ty<'tcx>> {
652 debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
654 // We do not expect any bound regions in our predicate, so
655 // skip past the bound vars.
656 let predicate = match predicate.no_bound_vars() {
659 debug!("deduce_future_output_from_projection: has late-bound regions");
664 // Check that this is a projection from the `Future` trait.
665 let trait_ref = predicate.projection_ty.trait_ref(self.tcx);
666 let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span));
667 if trait_ref.def_id != future_trait {
668 debug!("deduce_future_output_from_projection: not a future");
672 // The `Future` trait has only one associted item, `Output`,
673 // so check that this is what we see.
674 let output_assoc_item =
675 self.tcx.associated_items(future_trait).in_definition_order().next().unwrap().def_id;
676 if output_assoc_item != predicate.projection_ty.item_def_id {
679 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
680 predicate.projection_ty.item_def_id,
685 // Extract the type from the projection. Note that there can
686 // be no bound variables in this type because the "self type"
687 // does not have any regions in it.
688 let output_ty = self.resolve_vars_if_possible(predicate.ty);
689 debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
693 /// Converts the types that the user supplied, in case that doing
694 /// so should yield an error, but returns back a signature where
695 /// all parameters are of type `TyErr`.
696 fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
697 let astconv: &dyn AstConv<'_> = self;
699 let supplied_arguments = decl.inputs.iter().map(|a| {
700 // Convert the types that the user supplied (if any), but ignore them.
701 astconv.ast_ty_to_ty(a);
705 if let hir::FnRetTy::Return(ref output) = decl.output {
706 astconv.ast_ty_to_ty(&output);
709 let result = ty::Binder::dummy(self.tcx.mk_fn_sig(
713 hir::Unsafety::Normal,
717 debug!("supplied_sig_of_closure: result={:?}", result);
725 body: &hir::Body<'_>,
726 bound_sig: ty::PolyFnSig<'tcx>,
727 ) -> ClosureSignatures<'tcx> {
728 let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, bound_sig);
729 let liberated_sig = self.inh.normalize_associated_types_in(
735 ClosureSignatures { bound_sig, liberated_sig }