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};
7 use rustc::ty::fold::TypeFoldable;
8 use rustc::ty::subst::InternalSubsts;
9 use rustc::ty::{self, GenericParamDefKind, Ty};
11 use rustc_hir::def_id::DefId;
12 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
13 use rustc_infer::infer::LateBoundRegionConversionTime;
14 use rustc_infer::infer::{InferOk, InferResult};
15 use rustc_infer::traits::error_reporting::ArgKind;
16 use rustc_infer::traits::Obligation;
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 { resume_ty, yield_ty, interior, movability }) = generator_types
97 let generator_substs = substs.as_generator();
101 generator_substs.resume_ty(expr_def_id, self.tcx),
106 generator_substs.yield_ty(expr_def_id, self.tcx),
110 liberated_sig.output(),
111 generator_substs.return_ty(expr_def_id, self.tcx),
116 generator_substs.witness(expr_def_id, self.tcx),
118 return self.tcx.mk_generator(expr_def_id, substs, movability);
121 let closure_type = self.tcx.mk_closure(expr_def_id, substs);
123 debug!("check_closure: expr.hir_id={:?} closure_type={:?}", expr.hir_id, closure_type);
125 // Tuple up the arguments and insert the resulting function type into
126 // the `closures` table.
127 let sig = bound_sig.map_bound(|sig| {
129 iter::once(self.tcx.intern_tup(sig.inputs())),
138 "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
139 expr_def_id, sig, opt_kind
142 let sig_fn_ptr_ty = self.tcx.mk_fn_ptr(sig);
146 substs.as_closure().sig_ty(expr_def_id, self.tcx),
149 if let Some(kind) = opt_kind {
152 kind.to_ty(self.tcx),
153 substs.as_closure().kind_ty(expr_def_id, self.tcx),
160 /// Given the expected type, figures out what it can about this closure we
161 /// are about to type check:
162 fn deduce_expectations_from_expected_type(
164 expected_ty: Ty<'tcx>,
165 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
166 debug!("deduce_expectations_from_expected_type(expected_ty={:?})", expected_ty);
168 match expected_ty.kind {
169 ty::Dynamic(ref object_type, ..) => {
170 let sig = object_type
173 let pb = pb.with_self_ty(self.tcx, self.tcx.types.err);
174 self.deduce_sig_from_projection(None, &pb)
177 let kind = object_type
179 .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did));
182 ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
184 let expected_sig = ExpectedSig { cause_span: None, sig: *sig.skip_binder() };
185 (Some(expected_sig), Some(ty::ClosureKind::Fn))
191 fn deduce_expectations_from_obligations(
193 expected_vid: ty::TyVid,
194 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
196 self.obligations_for_self_ty(expected_vid).find_map(|(_, obligation)| {
198 "deduce_expectations_from_obligations: obligation.predicate={:?}",
202 if let ty::Predicate::Projection(ref proj_predicate) = obligation.predicate {
203 // Given a Projection predicate, we can potentially infer
204 // the complete signature.
205 self.deduce_sig_from_projection(Some(obligation.cause.span), proj_predicate)
211 // Even if we can't infer the full signature, we may be able to
212 // infer the kind. This can occur if there is a trait-reference
213 // like `F : Fn<A>`. Note that due to subtyping we could encounter
214 // many viable options, so pick the most restrictive.
215 let expected_kind = self
216 .obligations_for_self_ty(expected_vid)
217 .filter_map(|(tr, _)| self.tcx.fn_trait_kind_from_lang_item(tr.def_id()))
218 .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
220 (expected_sig, expected_kind)
223 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
224 /// everything we need to know about a closure or generator.
226 /// The `cause_span` should be the span that caused us to
227 /// have this expected signature, or `None` if we can't readily
229 fn deduce_sig_from_projection(
231 cause_span: Option<Span>,
232 projection: &ty::PolyProjectionPredicate<'tcx>,
233 ) -> Option<ExpectedSig<'tcx>> {
236 debug!("deduce_sig_from_projection({:?})", projection);
238 let trait_ref = projection.to_poly_trait_ref(tcx);
240 let is_fn = tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some();
241 let gen_trait = tcx.require_lang_item(lang_items::GeneratorTraitLangItem, cause_span);
242 let is_gen = gen_trait == trait_ref.def_id();
243 if !is_fn && !is_gen {
244 debug!("deduce_sig_from_projection: not fn or generator");
249 // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
250 // associated item and not yield.
251 let return_assoc_item =
252 self.tcx.associated_items(gen_trait).in_definition_order().nth(1).unwrap().def_id;
253 if return_assoc_item != projection.projection_def_id() {
254 debug!("deduce_sig_from_projection: not return assoc item of generator");
259 let input_tys = if is_fn {
260 let arg_param_ty = trait_ref.skip_binder().substs.type_at(1);
261 let arg_param_ty = self.resolve_vars_if_possible(&arg_param_ty);
262 debug!("deduce_sig_from_projection: arg_param_ty={:?}", arg_param_ty);
264 match arg_param_ty.kind {
265 ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(),
269 // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
270 // else they must have exactly 1 argument. For now though, just give up in this case.
274 let ret_param_ty = projection.skip_binder().ty;
275 let ret_param_ty = self.resolve_vars_if_possible(&ret_param_ty);
276 debug!("deduce_sig_from_projection: ret_param_ty={:?}", ret_param_ty);
278 let sig = self.tcx.mk_fn_sig(
282 hir::Unsafety::Normal,
285 debug!("deduce_sig_from_projection: sig={:?}", sig);
287 Some(ExpectedSig { cause_span, sig })
293 decl: &hir::FnDecl<'_>,
294 body: &hir::Body<'_>,
295 expected_sig: Option<ExpectedSig<'tcx>>,
296 ) -> ClosureSignatures<'tcx> {
297 if let Some(e) = expected_sig {
298 self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
300 self.sig_of_closure_no_expectation(expr_def_id, decl, body)
304 /// If there is no expected signature, then we will convert the
305 /// types that the user gave into a signature.
306 fn sig_of_closure_no_expectation(
309 decl: &hir::FnDecl<'_>,
310 body: &hir::Body<'_>,
311 ) -> ClosureSignatures<'tcx> {
312 debug!("sig_of_closure_no_expectation()");
314 let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
316 self.closure_sigs(expr_def_id, body, bound_sig)
319 /// Invoked to compute the signature of a closure expression. This
320 /// combines any user-provided type annotations (e.g., `|x: u32|
321 /// -> u32 { .. }`) with the expected signature.
323 /// The approach is as follows:
325 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
326 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
327 /// - If we have no expectation `E`, then the signature of the closure is `S`.
328 /// - Otherwise, the signature of the closure is E. Moreover:
329 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
330 /// - Instantiate all the late-bound regions bound in the closure within `S`
331 /// with fresh (existential) variables, yielding `S'`
332 /// - Require that `E' = S'`
333 /// - We could use some kind of subtyping relationship here,
334 /// I imagine, but equality is easier and works fine for
337 /// The key intuition here is that the user's types must be valid
338 /// from "the inside" of the closure, but the expectation
339 /// ultimately drives the overall signature.
344 /// fn with_closure<F>(_: F)
345 /// where F: Fn(&u32) -> &u32 { .. }
347 /// with_closure(|x: &u32| { ... })
351 /// - E would be `fn(&u32) -> &u32`.
352 /// - S would be `fn(&u32) ->
353 /// - E' is `&'!0 u32 -> &'!0 u32`
354 /// - S' is `&'?0 u32 -> ?T`
356 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
360 /// - `expr_def_id`: the `DefId` of the closure expression
361 /// - `decl`: the HIR declaration of the closure
362 /// - `body`: the body of the closure
363 /// - `expected_sig`: the expected signature (if any). Note that
364 /// this is missing a binder: that is, there may be late-bound
365 /// regions with depth 1, which are bound then by the closure.
366 fn sig_of_closure_with_expectation(
369 decl: &hir::FnDecl<'_>,
370 body: &hir::Body<'_>,
371 expected_sig: ExpectedSig<'tcx>,
372 ) -> ClosureSignatures<'tcx> {
373 debug!("sig_of_closure_with_expectation(expected_sig={:?})", expected_sig);
375 // Watch out for some surprises and just ignore the
376 // expectation if things don't see to match up with what we
378 if expected_sig.sig.c_variadic != decl.c_variadic {
379 return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
380 } else if expected_sig.sig.inputs_and_output.len() != decl.inputs.len() + 1 {
381 return self.sig_of_closure_with_mismatched_number_of_arguments(
389 // Create a `PolyFnSig`. Note the oddity that late bound
390 // regions appearing free in `expected_sig` are now bound up
391 // in this binder we are creating.
392 assert!(!expected_sig.sig.has_vars_bound_above(ty::INNERMOST));
393 let bound_sig = ty::Binder::bind(self.tcx.mk_fn_sig(
394 expected_sig.sig.inputs().iter().cloned(),
395 expected_sig.sig.output(),
397 hir::Unsafety::Normal,
401 // `deduce_expectations_from_expected_type` introduces
402 // late-bound lifetimes defined elsewhere, which we now
403 // anonymize away, so as not to confuse the user.
404 let bound_sig = self.tcx.anonymize_late_bound_regions(&bound_sig);
406 let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
408 // Up till this point, we have ignored the annotations that the user
409 // gave. This function will check that they unify successfully.
410 // Along the way, it also writes out entries for types that the user
411 // wrote into our tables, which are then later used by the privacy
413 match self.check_supplied_sig_against_expectation(expr_def_id, decl, body, &closure_sigs) {
414 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
415 Err(_) => return self.sig_of_closure_no_expectation(expr_def_id, decl, body),
421 fn sig_of_closure_with_mismatched_number_of_arguments(
424 decl: &hir::FnDecl<'_>,
425 body: &hir::Body<'_>,
426 expected_sig: ExpectedSig<'tcx>,
427 ) -> ClosureSignatures<'tcx> {
428 let expr_map_node = self.tcx.hir().get_if_local(expr_def_id).unwrap();
429 let expected_args: Vec<_> = expected_sig
433 .map(|ty| ArgKind::from_expected_ty(ty, None))
435 let (closure_span, found_args) = self.get_fn_like_arguments(expr_map_node);
436 let expected_span = expected_sig.cause_span.unwrap_or(closure_span);
437 self.report_arg_count_mismatch(
446 let error_sig = self.error_sig_of_closure(decl);
448 self.closure_sigs(expr_def_id, body, error_sig)
451 /// Enforce the user's types against the expectation. See
452 /// `sig_of_closure_with_expectation` for details on the overall
454 fn check_supplied_sig_against_expectation(
457 decl: &hir::FnDecl<'_>,
458 body: &hir::Body<'_>,
459 expected_sigs: &ClosureSignatures<'tcx>,
460 ) -> InferResult<'tcx, ()> {
461 // Get the signature S that the user gave.
463 // (See comment on `sig_of_closure_with_expectation` for the
464 // meaning of these letters.)
465 let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
467 debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig);
469 // FIXME(#45727): As discussed in [this comment][c1], naively
470 // forcing equality here actually results in suboptimal error
471 // messages in some cases. For now, if there would have been
472 // an obvious error, we fallback to declaring the type of the
473 // closure to be the one the user gave, which allows other
474 // error message code to trigger.
476 // However, I think [there is potential to do even better
477 // here][c2], since in *this* code we have the precise span of
478 // the type parameter in question in hand when we report the
481 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
482 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
483 self.infcx.commit_if_ok(|_| {
484 let mut all_obligations = vec![];
486 // The liberated version of this signature should be a subtype
487 // of the liberated form of the expectation.
488 for ((hir_ty, &supplied_ty), expected_ty) in decl
491 .zip(*supplied_sig.inputs().skip_binder()) // binder moved to (*) below
492 .zip(expected_sigs.liberated_sig.inputs())
493 // `liberated_sig` is E'.
495 // Instantiate (this part of..) S to S', i.e., with fresh variables.
496 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
498 LateBoundRegionConversionTime::FnCall,
499 &ty::Binder::bind(supplied_ty),
500 ); // recreated from (*) above
502 // Check that E' = S'.
503 let cause = self.misc(hir_ty.span);
504 let InferOk { value: (), obligations } =
505 self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
506 all_obligations.extend(obligations);
508 // Also, require that the supplied type must outlive
510 let closure_body_region = self.tcx.mk_region(ty::ReScope(region::Scope {
511 id: body.value.hir_id.local_id,
512 data: region::ScopeData::Node,
514 all_obligations.push(Obligation::new(
517 ty::Predicate::TypeOutlives(ty::Binder::dummy(ty::OutlivesPredicate(
524 let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
526 LateBoundRegionConversionTime::FnCall,
527 &supplied_sig.output(),
529 let cause = &self.misc(decl.output.span());
530 let InferOk { value: (), obligations } = self
531 .at(cause, self.param_env)
532 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
533 all_obligations.extend(obligations);
535 Ok(InferOk { value: (), obligations: all_obligations })
539 /// If there is no expected signature, then we will convert the
540 /// types that the user gave into a signature.
542 /// Also, record this closure signature for later.
543 fn supplied_sig_of_closure(
546 decl: &hir::FnDecl<'_>,
547 body: &hir::Body<'_>,
548 ) -> ty::PolyFnSig<'tcx> {
549 let astconv: &dyn AstConv<'_> = self;
552 "supplied_sig_of_closure(decl={:?}, body.generator_kind={:?})",
553 decl, body.generator_kind,
556 // First, convert the types that the user supplied (if any).
557 let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
558 let supplied_return = match decl.output {
559 hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
560 hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
561 // In the case of the async block that we create for a function body,
562 // we expect the return type of the block to match that of the enclosing
564 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
565 debug!("supplied_sig_of_closure: closure is async fn body");
566 self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| {
567 // AFAIK, deducing the future output
568 // always succeeds *except* in error cases
569 // like #65159. I'd like to return Error
570 // here, but I can't because I can't
571 // easily (and locally) prove that we
572 // *have* reported an
573 // error. --nikomatsakis
574 astconv.ty_infer(None, decl.output.span())
578 _ => astconv.ty_infer(None, decl.output.span()),
582 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
586 hir::Unsafety::Normal,
590 debug!("supplied_sig_of_closure: result={:?}", result);
592 let c_result = self.inh.infcx.canonicalize_response(&result);
593 self.tables.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
598 /// Invoked when we are translating the generator that results
599 /// from desugaring an `async fn`. Returns the "sugared" return
600 /// type of the `async fn` -- that is, the return type that the
601 /// user specified. The "desugared" return type is a `impl
602 /// Future<Output = T>`, so we do this by searching through the
603 /// obligations to extract the `T`.
604 fn deduce_future_output_from_obligations(&self, expr_def_id: DefId) -> Option<Ty<'tcx>> {
605 debug!("deduce_future_output_from_obligations(expr_def_id={:?})", expr_def_id);
607 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
608 span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
611 // In practice, the return type of the surrounding function is
612 // always a (not yet resolved) inference variable, because it
613 // is the hidden type for an `impl Trait` that we are going to
615 let ret_ty = ret_coercion.borrow().expected_ty();
616 let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
617 let ret_vid = match ret_ty.kind {
618 ty::Infer(ty::TyVar(ret_vid)) => ret_vid,
620 self.tcx.def_span(expr_def_id),
621 "async fn generator return type not an inference variable"
625 // Search for a pending obligation like
627 // `<R as Future>::Output = T`
629 // where R is the return type we are expecting. This type `T`
630 // will be our output.
631 let output_ty = self.obligations_for_self_ty(ret_vid).find_map(|(_, obligation)| {
632 if let ty::Predicate::Projection(ref proj_predicate) = obligation.predicate {
633 self.deduce_future_output_from_projection(obligation.cause.span, proj_predicate)
639 debug!("deduce_future_output_from_obligations: output_ty={:?}", output_ty);
643 /// Given a projection like
645 /// `<X as Future>::Output = T`
647 /// where `X` is some type that has no late-bound regions, returns
648 /// `Some(T)`. If the projection is for some other trait, returns
650 fn deduce_future_output_from_projection(
653 predicate: &ty::PolyProjectionPredicate<'tcx>,
654 ) -> Option<Ty<'tcx>> {
655 debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
657 // We do not expect any bound regions in our predicate, so
658 // skip past the bound vars.
659 let predicate = match predicate.no_bound_vars() {
662 debug!("deduce_future_output_from_projection: has late-bound regions");
667 // Check that this is a projection from the `Future` trait.
668 let trait_ref = predicate.projection_ty.trait_ref(self.tcx);
669 let future_trait = self.tcx.lang_items().future_trait().unwrap();
670 if trait_ref.def_id != future_trait {
671 debug!("deduce_future_output_from_projection: not a future");
675 // The `Future` trait has only one associted item, `Output`,
676 // so check that this is what we see.
677 let output_assoc_item =
678 self.tcx.associated_items(future_trait).in_definition_order().next().unwrap().def_id;
679 if output_assoc_item != predicate.projection_ty.item_def_id {
682 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
683 predicate.projection_ty.item_def_id,
688 // Extract the type from the projection. Note that there can
689 // be no bound variables in this type because the "self type"
690 // does not have any regions in it.
691 let output_ty = self.resolve_vars_if_possible(&predicate.ty);
692 debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
696 /// Converts the types that the user supplied, in case that doing
697 /// so should yield an error, but returns back a signature where
698 /// all parameters are of type `TyErr`.
699 fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
700 let astconv: &dyn AstConv<'_> = self;
702 let supplied_arguments = decl.inputs.iter().map(|a| {
703 // Convert the types that the user supplied (if any), but ignore them.
704 astconv.ast_ty_to_ty(a);
708 if let hir::FnRetTy::Return(ref output) = decl.output {
709 astconv.ast_ty_to_ty(&output);
712 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
716 hir::Unsafety::Normal,
720 debug!("supplied_sig_of_closure: result={:?}", result);
728 body: &hir::Body<'_>,
729 bound_sig: ty::PolyFnSig<'tcx>,
730 ) -> ClosureSignatures<'tcx> {
731 let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, &bound_sig);
732 let liberated_sig = self.inh.normalize_associated_types_in(
738 ClosureSignatures { bound_sig, liberated_sig }