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_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 _;
19 use rustc_trait_selection::traits::Obligation;
23 /// What signature do we *expect* the closure to have from context?
25 struct ExpectedSig<'tcx> {
26 /// Span that gave us this expectation, if we know that.
27 cause_span: Option<Span>,
31 struct ClosureSignatures<'tcx> {
32 bound_sig: ty::PolyFnSig<'tcx>,
33 liberated_sig: ty::FnSig<'tcx>,
36 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
37 pub fn check_expr_closure(
40 _capture: hir::CaptureBy,
41 decl: &'tcx hir::FnDecl<'tcx>,
43 gen: Option<hir::Movability>,
44 expected: Expectation<'tcx>,
46 debug!("check_expr_closure(expr={:?},expected={:?})", expr, expected);
48 // It's always helpful for inference if we know the kind of
49 // closure sooner rather than later, so first examine the expected
50 // type, and see if can glean a closure kind from there.
51 let (expected_sig, expected_kind) = match expected.to_option(self) {
52 Some(ty) => self.deduce_expectations_from_expected_type(ty),
55 let body = self.tcx.hir().body(body_id);
56 self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
62 opt_kind: Option<ty::ClosureKind>,
63 decl: &'tcx hir::FnDecl<'tcx>,
64 body: &'tcx hir::Body<'tcx>,
65 gen: Option<hir::Movability>,
66 expected_sig: Option<ExpectedSig<'tcx>>,
68 debug!("check_closure(opt_kind={:?}, expected_sig={:?})", opt_kind, expected_sig);
70 let expr_def_id = self.tcx.hir().local_def_id(expr.hir_id);
72 let ClosureSignatures { bound_sig, liberated_sig } =
73 self.sig_of_closure(expr_def_id, decl, body, expected_sig);
75 debug!("check_closure: ty_of_closure returns {:?}", liberated_sig);
78 check_fn(self, self.param_env, liberated_sig, decl, expr.hir_id, body, gen).1;
80 // Create type variables (for now) to represent the transformed
81 // types of upvars. These will be unified during the upvar
82 // inference phase (`upvar.rs`).
84 InternalSubsts::identity_for_item(self.tcx, self.tcx.closure_base_def_id(expr_def_id));
85 let substs = base_substs.extend_to(self.tcx, expr_def_id, |param, _| match param.kind {
86 GenericParamDefKind::Lifetime => span_bug!(expr.span, "closure has lifetime param"),
87 GenericParamDefKind::Type { .. } => self
89 .next_ty_var(TypeVariableOrigin {
90 kind: TypeVariableOriginKind::ClosureSynthetic,
94 GenericParamDefKind::Const => span_bug!(expr.span, "closure has const param"),
96 if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types
98 let generator_substs = substs.as_generator();
102 generator_substs.resume_ty(expr_def_id, self.tcx),
107 generator_substs.yield_ty(expr_def_id, self.tcx),
111 liberated_sig.output(),
112 generator_substs.return_ty(expr_def_id, self.tcx),
117 generator_substs.witness(expr_def_id, self.tcx),
119 return self.tcx.mk_generator(expr_def_id, substs, movability);
122 let closure_type = self.tcx.mk_closure(expr_def_id, substs);
124 debug!("check_closure: expr.hir_id={:?} closure_type={:?}", expr.hir_id, closure_type);
126 // Tuple up the arguments and insert the resulting function type into
127 // the `closures` table.
128 let sig = bound_sig.map_bound(|sig| {
130 iter::once(self.tcx.intern_tup(sig.inputs())),
139 "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
140 expr_def_id, sig, opt_kind
143 let sig_fn_ptr_ty = self.tcx.mk_fn_ptr(sig);
147 substs.as_closure().sig_ty(expr_def_id, self.tcx),
150 if let Some(kind) = opt_kind {
153 kind.to_ty(self.tcx),
154 substs.as_closure().kind_ty(expr_def_id, self.tcx),
161 /// Given the expected type, figures out what it can about this closure we
162 /// are about to type check:
163 fn deduce_expectations_from_expected_type(
165 expected_ty: Ty<'tcx>,
166 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
167 debug!("deduce_expectations_from_expected_type(expected_ty={:?})", expected_ty);
169 match expected_ty.kind {
170 ty::Dynamic(ref object_type, ..) => {
171 let sig = object_type
174 let pb = pb.with_self_ty(self.tcx, self.tcx.types.err);
175 self.deduce_sig_from_projection(None, &pb)
178 let kind = object_type
180 .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did));
183 ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
185 let expected_sig = ExpectedSig { cause_span: None, sig: *sig.skip_binder() };
186 (Some(expected_sig), Some(ty::ClosureKind::Fn))
192 fn deduce_expectations_from_obligations(
194 expected_vid: ty::TyVid,
195 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
197 self.obligations_for_self_ty(expected_vid).find_map(|(_, obligation)| {
199 "deduce_expectations_from_obligations: obligation.predicate={:?}",
203 if let ty::Predicate::Projection(ref proj_predicate) = obligation.predicate {
204 // Given a Projection predicate, we can potentially infer
205 // the complete signature.
206 self.deduce_sig_from_projection(Some(obligation.cause.span), proj_predicate)
212 // Even if we can't infer the full signature, we may be able to
213 // infer the kind. This can occur if there is a trait-reference
214 // like `F : Fn<A>`. Note that due to subtyping we could encounter
215 // many viable options, so pick the most restrictive.
216 let expected_kind = self
217 .obligations_for_self_ty(expected_vid)
218 .filter_map(|(tr, _)| self.tcx.fn_trait_kind_from_lang_item(tr.def_id()))
219 .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
221 (expected_sig, expected_kind)
224 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
225 /// everything we need to know about a closure or generator.
227 /// The `cause_span` should be the span that caused us to
228 /// have this expected signature, or `None` if we can't readily
230 fn deduce_sig_from_projection(
232 cause_span: Option<Span>,
233 projection: &ty::PolyProjectionPredicate<'tcx>,
234 ) -> Option<ExpectedSig<'tcx>> {
237 debug!("deduce_sig_from_projection({:?})", projection);
239 let trait_ref = projection.to_poly_trait_ref(tcx);
241 let is_fn = tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some();
242 let gen_trait = tcx.require_lang_item(lang_items::GeneratorTraitLangItem, cause_span);
243 let is_gen = gen_trait == trait_ref.def_id();
244 if !is_fn && !is_gen {
245 debug!("deduce_sig_from_projection: not fn or generator");
250 // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
251 // associated item and not yield.
252 let return_assoc_item =
253 self.tcx.associated_items(gen_trait).in_definition_order().nth(1).unwrap().def_id;
254 if return_assoc_item != projection.projection_def_id() {
255 debug!("deduce_sig_from_projection: not return assoc item of generator");
260 let input_tys = if is_fn {
261 let arg_param_ty = trait_ref.skip_binder().substs.type_at(1);
262 let arg_param_ty = self.resolve_vars_if_possible(&arg_param_ty);
263 debug!("deduce_sig_from_projection: arg_param_ty={:?}", arg_param_ty);
265 match arg_param_ty.kind {
266 ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(),
270 // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
271 // else they must have exactly 1 argument. For now though, just give up in this case.
275 let ret_param_ty = projection.skip_binder().ty;
276 let ret_param_ty = self.resolve_vars_if_possible(&ret_param_ty);
277 debug!("deduce_sig_from_projection: ret_param_ty={:?}", ret_param_ty);
279 let sig = self.tcx.mk_fn_sig(
283 hir::Unsafety::Normal,
286 debug!("deduce_sig_from_projection: sig={:?}", sig);
288 Some(ExpectedSig { cause_span, sig })
294 decl: &hir::FnDecl<'_>,
295 body: &hir::Body<'_>,
296 expected_sig: Option<ExpectedSig<'tcx>>,
297 ) -> ClosureSignatures<'tcx> {
298 if let Some(e) = expected_sig {
299 self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
301 self.sig_of_closure_no_expectation(expr_def_id, decl, body)
305 /// If there is no expected signature, then we will convert the
306 /// types that the user gave into a signature.
307 fn sig_of_closure_no_expectation(
310 decl: &hir::FnDecl<'_>,
311 body: &hir::Body<'_>,
312 ) -> ClosureSignatures<'tcx> {
313 debug!("sig_of_closure_no_expectation()");
315 let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
317 self.closure_sigs(expr_def_id, body, bound_sig)
320 /// Invoked to compute the signature of a closure expression. This
321 /// combines any user-provided type annotations (e.g., `|x: u32|
322 /// -> u32 { .. }`) with the expected signature.
324 /// The approach is as follows:
326 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
327 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
328 /// - If we have no expectation `E`, then the signature of the closure is `S`.
329 /// - Otherwise, the signature of the closure is E. Moreover:
330 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
331 /// - Instantiate all the late-bound regions bound in the closure within `S`
332 /// with fresh (existential) variables, yielding `S'`
333 /// - Require that `E' = S'`
334 /// - We could use some kind of subtyping relationship here,
335 /// I imagine, but equality is easier and works fine for
338 /// The key intuition here is that the user's types must be valid
339 /// from "the inside" of the closure, but the expectation
340 /// ultimately drives the overall signature.
345 /// fn with_closure<F>(_: F)
346 /// where F: Fn(&u32) -> &u32 { .. }
348 /// with_closure(|x: &u32| { ... })
352 /// - E would be `fn(&u32) -> &u32`.
353 /// - S would be `fn(&u32) ->
354 /// - E' is `&'!0 u32 -> &'!0 u32`
355 /// - S' is `&'?0 u32 -> ?T`
357 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
361 /// - `expr_def_id`: the `DefId` of the closure expression
362 /// - `decl`: the HIR declaration of the closure
363 /// - `body`: the body of the closure
364 /// - `expected_sig`: the expected signature (if any). Note that
365 /// this is missing a binder: that is, there may be late-bound
366 /// regions with depth 1, which are bound then by the closure.
367 fn sig_of_closure_with_expectation(
370 decl: &hir::FnDecl<'_>,
371 body: &hir::Body<'_>,
372 expected_sig: ExpectedSig<'tcx>,
373 ) -> ClosureSignatures<'tcx> {
374 debug!("sig_of_closure_with_expectation(expected_sig={:?})", expected_sig);
376 // Watch out for some surprises and just ignore the
377 // expectation if things don't see to match up with what we
379 if expected_sig.sig.c_variadic != decl.c_variadic {
380 return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
381 } else if expected_sig.sig.inputs_and_output.len() != decl.inputs.len() + 1 {
382 return self.sig_of_closure_with_mismatched_number_of_arguments(
390 // Create a `PolyFnSig`. Note the oddity that late bound
391 // regions appearing free in `expected_sig` are now bound up
392 // in this binder we are creating.
393 assert!(!expected_sig.sig.has_vars_bound_above(ty::INNERMOST));
394 let bound_sig = ty::Binder::bind(self.tcx.mk_fn_sig(
395 expected_sig.sig.inputs().iter().cloned(),
396 expected_sig.sig.output(),
398 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 tables, 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 expr_map_node = self.tcx.hir().get_if_local(expr_def_id).unwrap();
430 let expected_args: Vec<_> = expected_sig
434 .map(|ty| ArgKind::from_expected_ty(ty, None))
436 let (closure_span, found_args) = self.get_fn_like_arguments(expr_map_node);
437 let expected_span = expected_sig.cause_span.unwrap_or(closure_span);
438 self.report_arg_count_mismatch(
447 let error_sig = self.error_sig_of_closure(decl);
449 self.closure_sigs(expr_def_id, body, error_sig)
452 /// Enforce the user's types against the expectation. See
453 /// `sig_of_closure_with_expectation` for details on the overall
455 fn check_supplied_sig_against_expectation(
458 decl: &hir::FnDecl<'_>,
459 body: &hir::Body<'_>,
460 expected_sigs: &ClosureSignatures<'tcx>,
461 ) -> InferResult<'tcx, ()> {
462 // Get the signature S that the user gave.
464 // (See comment on `sig_of_closure_with_expectation` for the
465 // meaning of these letters.)
466 let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
468 debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig);
470 // FIXME(#45727): As discussed in [this comment][c1], naively
471 // forcing equality here actually results in suboptimal error
472 // messages in some cases. For now, if there would have been
473 // an obvious error, we fallback to declaring the type of the
474 // closure to be the one the user gave, which allows other
475 // error message code to trigger.
477 // However, I think [there is potential to do even better
478 // here][c2], since in *this* code we have the precise span of
479 // the type parameter in question in hand when we report the
482 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
483 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
484 self.infcx.commit_if_ok(|_| {
485 let mut all_obligations = vec![];
487 // The liberated version of this signature should be a subtype
488 // of the liberated form of the expectation.
489 for ((hir_ty, &supplied_ty), expected_ty) in decl
492 .zip(*supplied_sig.inputs().skip_binder()) // binder moved to (*) below
493 .zip(expected_sigs.liberated_sig.inputs())
494 // `liberated_sig` is E'.
496 // Instantiate (this part of..) S to S', i.e., with fresh variables.
497 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
499 LateBoundRegionConversionTime::FnCall,
500 &ty::Binder::bind(supplied_ty),
501 ); // recreated from (*) above
503 // Check that E' = S'.
504 let cause = self.misc(hir_ty.span);
505 let InferOk { value: (), obligations } =
506 self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
507 all_obligations.extend(obligations);
509 // Also, require that the supplied type must outlive
511 let closure_body_region = self.tcx.mk_region(ty::ReScope(region::Scope {
512 id: body.value.hir_id.local_id,
513 data: region::ScopeData::Node,
515 all_obligations.push(Obligation::new(
518 ty::Predicate::TypeOutlives(ty::Binder::dummy(ty::OutlivesPredicate(
525 let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
527 LateBoundRegionConversionTime::FnCall,
528 &supplied_sig.output(),
530 let cause = &self.misc(decl.output.span());
531 let InferOk { value: (), obligations } = self
532 .at(cause, self.param_env)
533 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
534 all_obligations.extend(obligations);
536 Ok(InferOk { value: (), obligations: all_obligations })
540 /// If there is no expected signature, then we will convert the
541 /// types that the user gave into a signature.
543 /// Also, record this closure signature for later.
544 fn supplied_sig_of_closure(
547 decl: &hir::FnDecl<'_>,
548 body: &hir::Body<'_>,
549 ) -> ty::PolyFnSig<'tcx> {
550 let astconv: &dyn AstConv<'_> = self;
553 "supplied_sig_of_closure(decl={:?}, body.generator_kind={:?})",
554 decl, body.generator_kind,
557 // First, convert the types that the user supplied (if any).
558 let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
559 let supplied_return = match decl.output {
560 hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
561 hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
562 // In the case of the async block that we create for a function body,
563 // we expect the return type of the block to match that of the enclosing
565 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
566 debug!("supplied_sig_of_closure: closure is async fn body");
567 self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| {
568 // AFAIK, deducing the future output
569 // always succeeds *except* in error cases
570 // like #65159. I'd like to return Error
571 // here, but I can't because I can't
572 // easily (and locally) prove that we
573 // *have* reported an
574 // error. --nikomatsakis
575 astconv.ty_infer(None, decl.output.span())
579 _ => astconv.ty_infer(None, decl.output.span()),
583 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
587 hir::Unsafety::Normal,
591 debug!("supplied_sig_of_closure: result={:?}", result);
593 let c_result = self.inh.infcx.canonicalize_response(&result);
594 self.tables.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
599 /// Invoked when we are translating the generator that results
600 /// from desugaring an `async fn`. Returns the "sugared" return
601 /// type of the `async fn` -- that is, the return type that the
602 /// user specified. The "desugared" return type is a `impl
603 /// Future<Output = T>`, so we do this by searching through the
604 /// obligations to extract the `T`.
605 fn deduce_future_output_from_obligations(&self, expr_def_id: DefId) -> Option<Ty<'tcx>> {
606 debug!("deduce_future_output_from_obligations(expr_def_id={:?})", expr_def_id);
608 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
609 span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
612 // In practice, the return type of the surrounding function is
613 // always a (not yet resolved) inference variable, because it
614 // is the hidden type for an `impl Trait` that we are going to
616 let ret_ty = ret_coercion.borrow().expected_ty();
617 let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
618 let ret_vid = match ret_ty.kind {
619 ty::Infer(ty::TyVar(ret_vid)) => ret_vid,
621 self.tcx.def_span(expr_def_id),
622 "async fn generator return type not an inference variable"
626 // Search for a pending obligation like
628 // `<R as Future>::Output = T`
630 // where R is the return type we are expecting. This type `T`
631 // will be our output.
632 let output_ty = self.obligations_for_self_ty(ret_vid).find_map(|(_, obligation)| {
633 if let ty::Predicate::Projection(ref proj_predicate) = obligation.predicate {
634 self.deduce_future_output_from_projection(obligation.cause.span, proj_predicate)
640 debug!("deduce_future_output_from_obligations: output_ty={:?}", output_ty);
644 /// Given a projection like
646 /// `<X as Future>::Output = T`
648 /// where `X` is some type that has no late-bound regions, returns
649 /// `Some(T)`. If the projection is for some other trait, returns
651 fn deduce_future_output_from_projection(
654 predicate: &ty::PolyProjectionPredicate<'tcx>,
655 ) -> Option<Ty<'tcx>> {
656 debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
658 // We do not expect any bound regions in our predicate, so
659 // skip past the bound vars.
660 let predicate = match predicate.no_bound_vars() {
663 debug!("deduce_future_output_from_projection: has late-bound regions");
668 // Check that this is a projection from the `Future` trait.
669 let trait_ref = predicate.projection_ty.trait_ref(self.tcx);
670 let future_trait = self.tcx.lang_items().future_trait().unwrap();
671 if trait_ref.def_id != future_trait {
672 debug!("deduce_future_output_from_projection: not a future");
676 // The `Future` trait has only one associted item, `Output`,
677 // so check that this is what we see.
678 let output_assoc_item =
679 self.tcx.associated_items(future_trait).in_definition_order().next().unwrap().def_id;
680 if output_assoc_item != predicate.projection_ty.item_def_id {
683 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
684 predicate.projection_ty.item_def_id,
689 // Extract the type from the projection. Note that there can
690 // be no bound variables in this type because the "self type"
691 // does not have any regions in it.
692 let output_ty = self.resolve_vars_if_possible(&predicate.ty);
693 debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
697 /// Converts the types that the user supplied, in case that doing
698 /// so should yield an error, but returns back a signature where
699 /// all parameters are of type `TyErr`.
700 fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
701 let astconv: &dyn AstConv<'_> = self;
703 let supplied_arguments = decl.inputs.iter().map(|a| {
704 // Convert the types that the user supplied (if any), but ignore them.
705 astconv.ast_ty_to_ty(a);
709 if let hir::FnRetTy::Return(ref output) = decl.output {
710 astconv.ast_ty_to_ty(&output);
713 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
717 hir::Unsafety::Normal,
721 debug!("supplied_sig_of_closure: result={:?}", result);
729 body: &hir::Body<'_>,
730 bound_sig: ty::PolyFnSig<'tcx>,
731 ) -> ClosureSignatures<'tcx> {
732 let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, &bound_sig);
733 let liberated_sig = self.inh.normalize_associated_types_in(
739 ClosureSignatures { bound_sig, liberated_sig }