1 //! Code for type-checking closure expressions.
3 use super::{check_fn, Expectation, FnCtxt, GeneratorTypes};
5 use crate::astconv::AstConv;
6 use crate::middle::region;
7 use rustc::hir::def_id::DefId;
8 use rustc::infer::{InferOk, InferResult};
9 use rustc::infer::LateBoundRegionConversionTime;
10 use rustc::infer::type_variable::TypeVariableOrigin;
11 use rustc::traits::Obligation;
12 use rustc::traits::error_reporting::ArgKind;
13 use rustc::ty::{self, Ty, GenericParamDefKind};
14 use rustc::ty::fold::TypeFoldable;
15 use rustc::ty::subst::InternalSubsts;
18 use rustc_target::spec::abi::Abi;
19 use syntax::source_map::Span;
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, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
36 pub fn check_expr_closure(
39 _capture: hir::CaptureClause,
40 decl: &'gcx hir::FnDecl,
42 gen: Option<hir::GeneratorMovability>,
43 expected: Expectation<'tcx>,
46 "check_expr_closure(expr={:?},expected={:?})",
50 // It's always helpful for inference if we know the kind of
51 // closure sooner rather than later, so first examine the expected
52 // type, and see if can glean a closure kind from there.
53 let (expected_sig, expected_kind) = match expected.to_option(self) {
54 Some(ty) => self.deduce_expectations_from_expected_type(ty),
57 let body = self.tcx.hir().body(body_id);
58 self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
64 opt_kind: Option<ty::ClosureKind>,
65 decl: &'gcx hir::FnDecl,
66 body: &'gcx hir::Body,
67 gen: Option<hir::GeneratorMovability>,
68 expected_sig: Option<ExpectedSig<'tcx>>,
71 "check_closure(opt_kind={:?}, expected_sig={:?})",
72 opt_kind, expected_sig
75 let expr_def_id = self.tcx.hir().local_def_id_from_hir_id(expr.hir_id);
77 let ClosureSignatures {
80 } = self.sig_of_closure(expr_def_id, decl, body, expected_sig);
82 debug!("check_closure: ty_of_closure returns {:?}", liberated_sig);
84 let generator_types = check_fn(
94 // Create type variables (for now) to represent the transformed
95 // types of upvars. These will be unified during the upvar
96 // inference phase (`upvar.rs`).
98 InternalSubsts::identity_for_item(self.tcx, self.tcx.closure_base_def_id(expr_def_id));
99 let substs = base_substs.extend_to(self.tcx,expr_def_id, |param, _| {
101 GenericParamDefKind::Lifetime => {
102 span_bug!(expr.span, "closure has region param")
104 GenericParamDefKind::Type {..} => {
106 .next_ty_var(TypeVariableOrigin::ClosureSynthetic(expr.span)).into()
110 if let Some(GeneratorTypes { yield_ty, interior, movability }) = generator_types {
111 let substs = ty::GeneratorSubsts { substs };
115 substs.yield_ty(expr_def_id, self.tcx),
119 liberated_sig.output(),
120 substs.return_ty(expr_def_id, self.tcx),
125 substs.witness(expr_def_id, self.tcx),
127 return self.tcx.mk_generator(expr_def_id, substs, movability);
130 let substs = ty::ClosureSubsts { substs };
131 let closure_type = self.tcx.mk_closure(expr_def_id, substs);
134 "check_closure: expr.hir_id={:?} closure_type={:?}",
135 expr.hir_id, closure_type
138 // Tuple up the arguments and insert the resulting function type into
139 // the `closures` table.
140 let sig = bound_sig.map_bound(|sig| {
142 iter::once(self.tcx.intern_tup(sig.inputs())),
151 "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
152 expr_def_id, sig, opt_kind
155 let sig_fn_ptr_ty = self.tcx.mk_fn_ptr(sig);
159 substs.closure_sig_ty(expr_def_id, self.tcx),
162 if let Some(kind) = opt_kind {
165 kind.to_ty(self.tcx),
166 substs.closure_kind_ty(expr_def_id, self.tcx),
173 /// Given the expected type, figures out what it can about this closure we
174 /// are about to type check:
175 fn deduce_expectations_from_expected_type(
177 expected_ty: Ty<'tcx>,
178 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
180 "deduce_expectations_from_expected_type(expected_ty={:?})",
184 match expected_ty.sty {
185 ty::Dynamic(ref object_type, ..) => {
186 let sig = object_type
189 let pb = pb.with_self_ty(self.tcx, self.tcx.types.err);
190 self.deduce_sig_from_projection(None, &pb)
193 let kind = object_type.principal_def_id().and_then(|did| {
194 self.tcx.lang_items().fn_trait_kind(did)
198 ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
200 let expected_sig = ExpectedSig {
202 sig: sig.skip_binder().clone(),
204 (Some(expected_sig), Some(ty::ClosureKind::Fn))
210 fn deduce_expectations_from_obligations(
212 expected_vid: ty::TyVid,
213 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
214 let expected_sig = self.obligations_for_self_ty(expected_vid)
215 .find_map(|(_, obligation)| {
217 "deduce_expectations_from_obligations: obligation.predicate={:?}",
221 if let ty::Predicate::Projection(ref proj_predicate) = obligation.predicate {
222 // Given a Projection predicate, we can potentially infer
223 // the complete signature.
224 self.deduce_sig_from_projection(
225 Some(obligation.cause.span),
233 // Even if we can't infer the full signature, we may be able to
234 // infer the kind. This can occur if there is a trait-reference
235 // like `F : Fn<A>`. Note that due to subtyping we could encounter
236 // many viable options, so pick the most restrictive.
237 let expected_kind = self.obligations_for_self_ty(expected_vid)
238 .filter_map(|(tr, _)| self.tcx.lang_items().fn_trait_kind(tr.def_id()))
239 .fold(None, |best, cur| {
240 Some(best.map_or(cur, |best| cmp::min(best, cur)))
243 (expected_sig, expected_kind)
246 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
247 /// everything we need to know about a closure.
249 /// The `cause_span` should be the span that caused us to
250 /// have this expected signature, or `None` if we can't readily
252 fn deduce_sig_from_projection(
254 cause_span: Option<Span>,
255 projection: &ty::PolyProjectionPredicate<'tcx>,
256 ) -> Option<ExpectedSig<'tcx>> {
259 debug!("deduce_sig_from_projection({:?})", projection);
261 let trait_ref = projection.to_poly_trait_ref(tcx);
263 if tcx.lang_items().fn_trait_kind(trait_ref.def_id()).is_none() {
267 let arg_param_ty = trait_ref.skip_binder().substs.type_at(1);
268 let arg_param_ty = self.resolve_type_vars_if_possible(&arg_param_ty);
270 "deduce_sig_from_projection: arg_param_ty {:?}",
274 let input_tys = match arg_param_ty.sty {
275 ty::Tuple(tys) => tys.into_iter(),
279 let ret_param_ty = projection.skip_binder().ty;
280 let ret_param_ty = self.resolve_type_vars_if_possible(&ret_param_ty);
282 "deduce_sig_from_projection: ret_param_ty {:?}",
286 let sig = self.tcx.mk_fn_sig(
290 hir::Unsafety::Normal,
293 debug!("deduce_sig_from_projection: sig {:?}", sig);
295 Some(ExpectedSig { cause_span, sig })
303 expected_sig: Option<ExpectedSig<'tcx>>,
304 ) -> ClosureSignatures<'tcx> {
305 if let Some(e) = expected_sig {
306 self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
308 self.sig_of_closure_no_expectation(expr_def_id, decl, body)
312 /// If there is no expected signature, then we will convert the
313 /// types that the user gave into a signature.
314 fn sig_of_closure_no_expectation(
319 ) -> ClosureSignatures<'tcx> {
320 debug!("sig_of_closure_no_expectation()");
322 let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl);
324 self.closure_sigs(expr_def_id, body, bound_sig)
327 /// Invoked to compute the signature of a closure expression. This
328 /// combines any user-provided type annotations (e.g., `|x: u32|
329 /// -> u32 { .. }`) with the expected signature.
331 /// The approach is as follows:
333 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
334 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
335 /// - If we have no expectation `E`, then the signature of the closure is `S`.
336 /// - Otherwise, the signature of the closure is E. Moreover:
337 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
338 /// - Instantiate all the late-bound regions bound in the closure within `S`
339 /// with fresh (existential) variables, yielding `S'`
340 /// - Require that `E' = S'`
341 /// - We could use some kind of subtyping relationship here,
342 /// I imagine, but equality is easier and works fine for
345 /// The key intuition here is that the user's types must be valid
346 /// from "the inside" of the closure, but the expectation
347 /// ultimately drives the overall signature.
352 /// fn with_closure<F>(_: F)
353 /// where F: Fn(&u32) -> &u32 { .. }
355 /// with_closure(|x: &u32| { ... })
359 /// - E would be `fn(&u32) -> &u32`.
360 /// - S would be `fn(&u32) ->
361 /// - E' is `&'!0 u32 -> &'!0 u32`
362 /// - S' is `&'?0 u32 -> ?T`
364 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
368 /// - `expr_def_id`: the `DefId` of the closure expression
369 /// - `decl`: the HIR declaration of the closure
370 /// - `body`: the body of the closure
371 /// - `expected_sig`: the expected signature (if any). Note that
372 /// this is missing a binder: that is, there may be late-bound
373 /// regions with depth 1, which are bound then by the closure.
374 fn sig_of_closure_with_expectation(
379 expected_sig: ExpectedSig<'tcx>,
380 ) -> ClosureSignatures<'tcx> {
382 "sig_of_closure_with_expectation(expected_sig={:?})",
386 // Watch out for some surprises and just ignore the
387 // expectation if things don't see to match up with what we
389 if expected_sig.sig.c_variadic != decl.c_variadic {
390 return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
391 } else if expected_sig.sig.inputs_and_output.len() != decl.inputs.len() + 1 {
392 return self.sig_of_closure_with_mismatched_number_of_arguments(
400 // Create a `PolyFnSig`. Note the oddity that late bound
401 // regions appearing free in `expected_sig` are now bound up
402 // in this binder we are creating.
403 assert!(!expected_sig.sig.has_vars_bound_above(ty::INNERMOST));
404 let bound_sig = ty::Binder::bind(self.tcx.mk_fn_sig(
405 expected_sig.sig.inputs().iter().cloned(),
406 expected_sig.sig.output(),
408 hir::Unsafety::Normal,
412 // `deduce_expectations_from_expected_type` introduces
413 // late-bound lifetimes defined elsewhere, which we now
414 // anonymize away, so as not to confuse the user.
415 let bound_sig = self.tcx.anonymize_late_bound_regions(&bound_sig);
417 let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
419 // Up till this point, we have ignored the annotations that the user
420 // gave. This function will check that they unify successfully.
421 // Along the way, it also writes out entries for types that the user
422 // wrote into our tables, which are then later used by the privacy
424 match self.check_supplied_sig_against_expectation(expr_def_id, decl, body, &closure_sigs) {
425 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
426 Err(_) => return self.sig_of_closure_no_expectation(expr_def_id, decl, body),
432 fn sig_of_closure_with_mismatched_number_of_arguments(
437 expected_sig: ExpectedSig<'tcx>,
438 ) -> ClosureSignatures<'tcx> {
439 let expr_map_node = self.tcx.hir().get_if_local(expr_def_id).unwrap();
440 let expected_args: Vec<_> = expected_sig
444 .map(|ty| ArgKind::from_expected_ty(ty, None))
446 let (closure_span, found_args) = self.get_fn_like_arguments(expr_map_node);
447 let expected_span = expected_sig.cause_span.unwrap_or(closure_span);
448 self.report_arg_count_mismatch(
456 let error_sig = self.error_sig_of_closure(decl);
458 self.closure_sigs(expr_def_id, body, error_sig)
461 /// Enforce the user's types against the expectation. See
462 /// `sig_of_closure_with_expectation` for details on the overall
464 fn check_supplied_sig_against_expectation(
469 expected_sigs: &ClosureSignatures<'tcx>,
470 ) -> InferResult<'tcx, ()> {
471 // Get the signature S that the user gave.
473 // (See comment on `sig_of_closure_with_expectation` for the
474 // meaning of these letters.)
475 let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl);
478 "check_supplied_sig_against_expectation: supplied_sig={:?}",
482 // FIXME(#45727): As discussed in [this comment][c1], naively
483 // forcing equality here actually results in suboptimal error
484 // messages in some cases. For now, if there would have been
485 // an obvious error, we fallback to declaring the type of the
486 // closure to be the one the user gave, which allows other
487 // error message code to trigger.
489 // However, I think [there is potential to do even better
490 // here][c2], since in *this* code we have the precise span of
491 // the type parameter in question in hand when we report the
494 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
495 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
496 self.infcx.commit_if_ok(|_| {
497 let mut all_obligations = vec![];
499 // The liberated version of this signature should be a subtype
500 // of the liberated form of the expectation.
501 for ((hir_ty, &supplied_ty), expected_ty) in decl.inputs.iter()
502 .zip(*supplied_sig.inputs().skip_binder()) // binder moved to (*) below
503 .zip(expected_sigs.liberated_sig.inputs())
504 // `liberated_sig` is E'.
506 // Instantiate (this part of..) S to S', i.e., with fresh variables.
507 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
509 LateBoundRegionConversionTime::FnCall,
510 &ty::Binder::bind(supplied_ty),
511 ); // recreated from (*) above
513 // Check that E' = S'.
514 let cause = &self.misc(hir_ty.span);
518 } = self.at(cause, self.param_env)
519 .eq(*expected_ty, supplied_ty)?;
520 all_obligations.extend(obligations);
522 // Also, require that the supplied type must outlive
524 let closure_body_region = self.tcx.mk_region(
527 id: body.value.hir_id.local_id,
528 data: region::ScopeData::Node,
532 all_obligations.push(
536 ty::Predicate::TypeOutlives(
538 ty::OutlivesPredicate(
548 let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
550 LateBoundRegionConversionTime::FnCall,
551 &supplied_sig.output(),
553 let cause = &self.misc(decl.output.span());
557 } = self.at(cause, self.param_env)
558 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
559 all_obligations.extend(obligations);
563 obligations: all_obligations,
568 /// If there is no expected signature, then we will convert the
569 /// types that the user gave into a signature.
571 /// Also, record this closure signature for later.
572 fn supplied_sig_of_closure(
576 ) -> ty::PolyFnSig<'tcx> {
577 let astconv: &dyn AstConv<'_, '_> = self;
579 // First, convert the types that the user supplied (if any).
580 let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
581 let supplied_return = match decl.output {
582 hir::Return(ref output) => astconv.ast_ty_to_ty(&output),
583 hir::DefaultReturn(_) => astconv.ty_infer(decl.output.span()),
586 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
590 hir::Unsafety::Normal,
594 debug!("supplied_sig_of_closure: result={:?}", result);
596 let c_result = self.inh.infcx.canonicalize_response(&result);
597 self.tables.borrow_mut().user_provided_sigs.insert(
605 /// Converts the types that the user supplied, in case that doing
606 /// so should yield an error, but returns back a signature where
607 /// all parameters are of type `TyErr`.
608 fn error_sig_of_closure(&self, decl: &hir::FnDecl) -> ty::PolyFnSig<'tcx> {
609 let astconv: &dyn AstConv<'_, '_> = self;
611 let supplied_arguments = decl.inputs.iter().map(|a| {
612 // Convert the types that the user supplied (if any), but ignore them.
613 astconv.ast_ty_to_ty(a);
617 if let hir::Return(ref output) = decl.output {
618 astconv.ast_ty_to_ty(&output);
621 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
625 hir::Unsafety::Normal,
629 debug!("supplied_sig_of_closure: result={:?}", result);
638 bound_sig: ty::PolyFnSig<'tcx>,
639 ) -> ClosureSignatures<'tcx> {
640 let liberated_sig = self.tcx()
641 .liberate_late_bound_regions(expr_def_id, &bound_sig);
642 let liberated_sig = self.inh.normalize_associated_types_in(