1 //! Code for type-checking closure expressions.
3 use super::{check_fn, Expectation, FnCtxt, GeneratorTypes};
5 use crate::astconv::AstConv;
6 use crate::middle::{lang_items, region};
8 use rustc::hir::def_id::DefId;
9 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
10 use rustc::infer::LateBoundRegionConversionTime;
11 use rustc::infer::{InferOk, InferResult};
12 use rustc::traits::error_reporting::ArgKind;
13 use rustc::traits::Obligation;
14 use rustc::ty::fold::TypeFoldable;
15 use rustc::ty::subst::InternalSubsts;
16 use rustc::ty::{self, GenericParamDefKind, Ty};
17 use rustc_span::source_map::Span;
18 use rustc_target::spec::abi::Abi;
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>,
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, 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 // Create type variables (for now) to represent the transformed
80 // types of upvars. These will be unified during the upvar
81 // inference phase (`upvar.rs`).
83 InternalSubsts::identity_for_item(self.tcx, self.tcx.closure_base_def_id(expr_def_id));
84 let substs = base_substs.extend_to(self.tcx, expr_def_id, |param, _| match param.kind {
85 GenericParamDefKind::Lifetime => span_bug!(expr.span, "closure has lifetime param"),
86 GenericParamDefKind::Type { .. } => self
88 .next_ty_var(TypeVariableOrigin {
89 kind: TypeVariableOriginKind::ClosureSynthetic,
93 GenericParamDefKind::Const => span_bug!(expr.span, "closure has const param"),
95 if let Some(GeneratorTypes { yield_ty, interior, movability }) = generator_types {
96 let generator_substs = substs.as_generator();
100 generator_substs.yield_ty(expr_def_id, self.tcx),
104 liberated_sig.output(),
105 generator_substs.return_ty(expr_def_id, self.tcx),
110 generator_substs.witness(expr_def_id, self.tcx),
112 return self.tcx.mk_generator(expr_def_id, substs, movability);
115 let closure_type = self.tcx.mk_closure(expr_def_id, substs);
117 debug!("check_closure: expr.hir_id={:?} closure_type={:?}", expr.hir_id, closure_type);
119 // Tuple up the arguments and insert the resulting function type into
120 // the `closures` table.
121 let sig = bound_sig.map_bound(|sig| {
123 iter::once(self.tcx.intern_tup(sig.inputs())),
132 "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
133 expr_def_id, sig, opt_kind
136 let sig_fn_ptr_ty = self.tcx.mk_fn_ptr(sig);
140 substs.as_closure().sig_ty(expr_def_id, self.tcx),
143 if let Some(kind) = opt_kind {
146 kind.to_ty(self.tcx),
147 substs.as_closure().kind_ty(expr_def_id, self.tcx),
154 /// Given the expected type, figures out what it can about this closure we
155 /// are about to type check:
156 fn deduce_expectations_from_expected_type(
158 expected_ty: Ty<'tcx>,
159 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
160 debug!("deduce_expectations_from_expected_type(expected_ty={:?})", expected_ty);
162 match expected_ty.kind {
163 ty::Dynamic(ref object_type, ..) => {
164 let sig = object_type
167 let pb = pb.with_self_ty(self.tcx, self.tcx.types.err);
168 self.deduce_sig_from_projection(None, &pb)
171 let kind = object_type
173 .and_then(|did| self.tcx.lang_items().fn_trait_kind(did));
176 ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
178 let expected_sig = ExpectedSig { cause_span: None, sig: sig.skip_binder().clone() };
179 (Some(expected_sig), Some(ty::ClosureKind::Fn))
185 fn deduce_expectations_from_obligations(
187 expected_vid: ty::TyVid,
188 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
190 self.obligations_for_self_ty(expected_vid).find_map(|(_, obligation)| {
192 "deduce_expectations_from_obligations: obligation.predicate={:?}",
196 if let ty::Predicate::Projection(ref proj_predicate) = obligation.predicate {
197 // Given a Projection predicate, we can potentially infer
198 // the complete signature.
199 self.deduce_sig_from_projection(Some(obligation.cause.span), proj_predicate)
205 // Even if we can't infer the full signature, we may be able to
206 // infer the kind. This can occur if there is a trait-reference
207 // like `F : Fn<A>`. Note that due to subtyping we could encounter
208 // many viable options, so pick the most restrictive.
209 let expected_kind = self
210 .obligations_for_self_ty(expected_vid)
211 .filter_map(|(tr, _)| self.tcx.lang_items().fn_trait_kind(tr.def_id()))
212 .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
214 (expected_sig, expected_kind)
217 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
218 /// everything we need to know about a closure or generator.
220 /// The `cause_span` should be the span that caused us to
221 /// have this expected signature, or `None` if we can't readily
223 fn deduce_sig_from_projection(
225 cause_span: Option<Span>,
226 projection: &ty::PolyProjectionPredicate<'tcx>,
227 ) -> Option<ExpectedSig<'tcx>> {
230 debug!("deduce_sig_from_projection({:?})", projection);
232 let trait_ref = projection.to_poly_trait_ref(tcx);
234 let is_fn = tcx.lang_items().fn_trait_kind(trait_ref.def_id()).is_some();
235 let gen_trait = tcx.require_lang_item(lang_items::GeneratorTraitLangItem, cause_span);
236 let is_gen = gen_trait == trait_ref.def_id();
237 if !is_fn && !is_gen {
238 debug!("deduce_sig_from_projection: not fn or generator");
243 // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
244 // associated item and not yield.
245 let return_assoc_item = self.tcx.associated_items(gen_trait).nth(1).unwrap().def_id;
246 if return_assoc_item != projection.projection_def_id() {
247 debug!("deduce_sig_from_projection: not return assoc item of generator");
252 let input_tys = if is_fn {
253 let arg_param_ty = trait_ref.skip_binder().substs.type_at(1);
254 let arg_param_ty = self.resolve_vars_if_possible(&arg_param_ty);
255 debug!("deduce_sig_from_projection: arg_param_ty={:?}", arg_param_ty);
257 match arg_param_ty.kind {
258 ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(),
262 // Generators cannot have explicit arguments.
266 let ret_param_ty = projection.skip_binder().ty;
267 let ret_param_ty = self.resolve_vars_if_possible(&ret_param_ty);
268 debug!("deduce_sig_from_projection: ret_param_ty={:?}", ret_param_ty);
270 let sig = self.tcx.mk_fn_sig(
274 hir::Unsafety::Normal,
277 debug!("deduce_sig_from_projection: sig={:?}", sig);
279 Some(ExpectedSig { cause_span, sig })
285 decl: &hir::FnDecl<'_>,
286 body: &hir::Body<'_>,
287 expected_sig: Option<ExpectedSig<'tcx>>,
288 ) -> ClosureSignatures<'tcx> {
289 if let Some(e) = expected_sig {
290 self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
292 self.sig_of_closure_no_expectation(expr_def_id, decl, body)
296 /// If there is no expected signature, then we will convert the
297 /// types that the user gave into a signature.
298 fn sig_of_closure_no_expectation(
301 decl: &hir::FnDecl<'_>,
302 body: &hir::Body<'_>,
303 ) -> ClosureSignatures<'tcx> {
304 debug!("sig_of_closure_no_expectation()");
306 let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
308 self.closure_sigs(expr_def_id, body, bound_sig)
311 /// Invoked to compute the signature of a closure expression. This
312 /// combines any user-provided type annotations (e.g., `|x: u32|
313 /// -> u32 { .. }`) with the expected signature.
315 /// The approach is as follows:
317 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
318 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
319 /// - If we have no expectation `E`, then the signature of the closure is `S`.
320 /// - Otherwise, the signature of the closure is E. Moreover:
321 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
322 /// - Instantiate all the late-bound regions bound in the closure within `S`
323 /// with fresh (existential) variables, yielding `S'`
324 /// - Require that `E' = S'`
325 /// - We could use some kind of subtyping relationship here,
326 /// I imagine, but equality is easier and works fine for
329 /// The key intuition here is that the user's types must be valid
330 /// from "the inside" of the closure, but the expectation
331 /// ultimately drives the overall signature.
336 /// fn with_closure<F>(_: F)
337 /// where F: Fn(&u32) -> &u32 { .. }
339 /// with_closure(|x: &u32| { ... })
343 /// - E would be `fn(&u32) -> &u32`.
344 /// - S would be `fn(&u32) ->
345 /// - E' is `&'!0 u32 -> &'!0 u32`
346 /// - S' is `&'?0 u32 -> ?T`
348 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
352 /// - `expr_def_id`: the `DefId` of the closure expression
353 /// - `decl`: the HIR declaration of the closure
354 /// - `body`: the body of the closure
355 /// - `expected_sig`: the expected signature (if any). Note that
356 /// this is missing a binder: that is, there may be late-bound
357 /// regions with depth 1, which are bound then by the closure.
358 fn sig_of_closure_with_expectation(
361 decl: &hir::FnDecl<'_>,
362 body: &hir::Body<'_>,
363 expected_sig: ExpectedSig<'tcx>,
364 ) -> ClosureSignatures<'tcx> {
365 debug!("sig_of_closure_with_expectation(expected_sig={:?})", expected_sig);
367 // Watch out for some surprises and just ignore the
368 // expectation if things don't see to match up with what we
370 if expected_sig.sig.c_variadic != decl.c_variadic {
371 return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
372 } else if expected_sig.sig.inputs_and_output.len() != decl.inputs.len() + 1 {
373 return self.sig_of_closure_with_mismatched_number_of_arguments(
381 // Create a `PolyFnSig`. Note the oddity that late bound
382 // regions appearing free in `expected_sig` are now bound up
383 // in this binder we are creating.
384 assert!(!expected_sig.sig.has_vars_bound_above(ty::INNERMOST));
385 let bound_sig = ty::Binder::bind(self.tcx.mk_fn_sig(
386 expected_sig.sig.inputs().iter().cloned(),
387 expected_sig.sig.output(),
389 hir::Unsafety::Normal,
393 // `deduce_expectations_from_expected_type` introduces
394 // late-bound lifetimes defined elsewhere, which we now
395 // anonymize away, so as not to confuse the user.
396 let bound_sig = self.tcx.anonymize_late_bound_regions(&bound_sig);
398 let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
400 // Up till this point, we have ignored the annotations that the user
401 // gave. This function will check that they unify successfully.
402 // Along the way, it also writes out entries for types that the user
403 // wrote into our tables, which are then later used by the privacy
405 match self.check_supplied_sig_against_expectation(expr_def_id, decl, body, &closure_sigs) {
406 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
407 Err(_) => return self.sig_of_closure_no_expectation(expr_def_id, decl, body),
413 fn sig_of_closure_with_mismatched_number_of_arguments(
416 decl: &hir::FnDecl<'_>,
417 body: &hir::Body<'_>,
418 expected_sig: ExpectedSig<'tcx>,
419 ) -> ClosureSignatures<'tcx> {
420 let expr_map_node = self.tcx.hir().get_if_local(expr_def_id).unwrap();
421 let expected_args: Vec<_> = expected_sig
425 .map(|ty| ArgKind::from_expected_ty(ty, None))
427 let (closure_span, found_args) = self.get_fn_like_arguments(expr_map_node);
428 let expected_span = expected_sig.cause_span.unwrap_or(closure_span);
429 self.report_arg_count_mismatch(
438 let error_sig = self.error_sig_of_closure(decl);
440 self.closure_sigs(expr_def_id, body, error_sig)
443 /// Enforce the user's types against the expectation. See
444 /// `sig_of_closure_with_expectation` for details on the overall
446 fn check_supplied_sig_against_expectation(
449 decl: &hir::FnDecl<'_>,
450 body: &hir::Body<'_>,
451 expected_sigs: &ClosureSignatures<'tcx>,
452 ) -> InferResult<'tcx, ()> {
453 // Get the signature S that the user gave.
455 // (See comment on `sig_of_closure_with_expectation` for the
456 // meaning of these letters.)
457 let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
459 debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig);
461 // FIXME(#45727): As discussed in [this comment][c1], naively
462 // forcing equality here actually results in suboptimal error
463 // messages in some cases. For now, if there would have been
464 // an obvious error, we fallback to declaring the type of the
465 // closure to be the one the user gave, which allows other
466 // error message code to trigger.
468 // However, I think [there is potential to do even better
469 // here][c2], since in *this* code we have the precise span of
470 // the type parameter in question in hand when we report the
473 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
474 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
475 self.infcx.commit_if_ok(|_| {
476 let mut all_obligations = vec![];
478 // The liberated version of this signature should be a subtype
479 // of the liberated form of the expectation.
480 for ((hir_ty, &supplied_ty), expected_ty) in decl
483 .zip(*supplied_sig.inputs().skip_binder()) // binder moved to (*) below
484 .zip(expected_sigs.liberated_sig.inputs())
485 // `liberated_sig` is E'.
487 // Instantiate (this part of..) S to S', i.e., with fresh variables.
488 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
490 LateBoundRegionConversionTime::FnCall,
491 &ty::Binder::bind(supplied_ty),
492 ); // recreated from (*) above
494 // Check that E' = S'.
495 let cause = self.misc(hir_ty.span);
496 let InferOk { value: (), obligations } =
497 self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
498 all_obligations.extend(obligations);
500 // Also, require that the supplied type must outlive
502 let closure_body_region = self.tcx.mk_region(ty::ReScope(region::Scope {
503 id: body.value.hir_id.local_id,
504 data: region::ScopeData::Node,
506 all_obligations.push(Obligation::new(
509 ty::Predicate::TypeOutlives(ty::Binder::dummy(ty::OutlivesPredicate(
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::Return(ref output) => astconv.ast_ty_to_ty(&output),
552 hir::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.tables.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,
612 self.tcx.def_span(expr_def_id),
613 "async fn generator return type not an inference variable"
617 // Search for a pending obligation like
619 // `<R as Future>::Output = T`
621 // where R is the return type we are expecting. This type `T`
622 // will be our output.
623 let output_ty = self.obligations_for_self_ty(ret_vid).find_map(|(_, obligation)| {
624 if let ty::Predicate::Projection(ref proj_predicate) = obligation.predicate {
625 self.deduce_future_output_from_projection(obligation.cause.span, proj_predicate)
631 debug!("deduce_future_output_from_obligations: output_ty={:?}", output_ty);
635 /// Given a projection like
637 /// `<X as Future>::Output = T`
639 /// where `X` is some type that has no late-bound regions, returns
640 /// `Some(T)`. If the projection is for some other trait, returns
642 fn deduce_future_output_from_projection(
645 predicate: &ty::PolyProjectionPredicate<'tcx>,
646 ) -> Option<Ty<'tcx>> {
647 debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
649 // We do not expect any bound regions in our predicate, so
650 // skip past the bound vars.
651 let predicate = match predicate.no_bound_vars() {
654 debug!("deduce_future_output_from_projection: has late-bound regions");
659 // Check that this is a projection from the `Future` trait.
660 let trait_ref = predicate.projection_ty.trait_ref(self.tcx);
661 let future_trait = self.tcx.lang_items().future_trait().unwrap();
662 if trait_ref.def_id != future_trait {
663 debug!("deduce_future_output_from_projection: not a future");
667 // The `Future` trait has only one associted item, `Output`,
668 // so check that this is what we see.
669 let output_assoc_item = self.tcx.associated_items(future_trait).nth(0).unwrap().def_id;
670 if output_assoc_item != predicate.projection_ty.item_def_id {
673 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
674 predicate.projection_ty.item_def_id,
679 // Extract the type from the projection. Note that there can
680 // be no bound variables in this type because the "self type"
681 // does not have any regions in it.
682 let output_ty = self.resolve_vars_if_possible(&predicate.ty);
683 debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
687 /// Converts the types that the user supplied, in case that doing
688 /// so should yield an error, but returns back a signature where
689 /// all parameters are of type `TyErr`.
690 fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
691 let astconv: &dyn AstConv<'_> = self;
693 let supplied_arguments = decl.inputs.iter().map(|a| {
694 // Convert the types that the user supplied (if any), but ignore them.
695 astconv.ast_ty_to_ty(a);
699 if let hir::Return(ref output) = decl.output {
700 astconv.ast_ty_to_ty(&output);
703 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
707 hir::Unsafety::Normal,
711 debug!("supplied_sig_of_closure: result={:?}", result);
719 body: &hir::Body<'_>,
720 bound_sig: ty::PolyFnSig<'tcx>,
721 ) -> ClosureSignatures<'tcx> {
722 let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, &bound_sig);
723 let liberated_sig = self.inh.normalize_associated_types_in(
729 ClosureSignatures { bound_sig, liberated_sig }