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, TypeVariableOriginKind};
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 lifetime param")
104 GenericParamDefKind::Type { .. } => {
105 self.infcx.next_ty_var(TypeVariableOrigin {
106 kind: TypeVariableOriginKind::ClosureSynthetic,
110 GenericParamDefKind::Const => {
111 span_bug!(expr.span, "closure has const param")
115 if let Some(GeneratorTypes { yield_ty, interior, movability }) = generator_types {
116 let substs = ty::GeneratorSubsts { substs };
120 substs.yield_ty(expr_def_id, self.tcx),
124 liberated_sig.output(),
125 substs.return_ty(expr_def_id, self.tcx),
130 substs.witness(expr_def_id, self.tcx),
132 return self.tcx.mk_generator(expr_def_id, substs, movability);
135 let substs = ty::ClosureSubsts { substs };
136 let closure_type = self.tcx.mk_closure(expr_def_id, substs);
139 "check_closure: expr.hir_id={:?} closure_type={:?}",
140 expr.hir_id, closure_type
143 // Tuple up the arguments and insert the resulting function type into
144 // the `closures` table.
145 let sig = bound_sig.map_bound(|sig| {
147 iter::once(self.tcx.intern_tup(sig.inputs())),
156 "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
157 expr_def_id, sig, opt_kind
160 let sig_fn_ptr_ty = self.tcx.mk_fn_ptr(sig);
164 substs.closure_sig_ty(expr_def_id, self.tcx),
167 if let Some(kind) = opt_kind {
170 kind.to_ty(self.tcx),
171 substs.closure_kind_ty(expr_def_id, self.tcx),
178 /// Given the expected type, figures out what it can about this closure we
179 /// are about to type check:
180 fn deduce_expectations_from_expected_type(
182 expected_ty: Ty<'tcx>,
183 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
185 "deduce_expectations_from_expected_type(expected_ty={:?})",
189 match expected_ty.sty {
190 ty::Dynamic(ref object_type, ..) => {
191 let sig = object_type
194 let pb = pb.with_self_ty(self.tcx, self.tcx.types.err);
195 self.deduce_sig_from_projection(None, &pb)
198 let kind = object_type.principal_def_id().and_then(|did| {
199 self.tcx.lang_items().fn_trait_kind(did)
203 ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
205 let expected_sig = ExpectedSig {
207 sig: sig.skip_binder().clone(),
209 (Some(expected_sig), Some(ty::ClosureKind::Fn))
215 fn deduce_expectations_from_obligations(
217 expected_vid: ty::TyVid,
218 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
219 let expected_sig = self.obligations_for_self_ty(expected_vid)
220 .find_map(|(_, obligation)| {
222 "deduce_expectations_from_obligations: obligation.predicate={:?}",
226 if let ty::Predicate::Projection(ref proj_predicate) = obligation.predicate {
227 // Given a Projection predicate, we can potentially infer
228 // the complete signature.
229 self.deduce_sig_from_projection(
230 Some(obligation.cause.span),
238 // Even if we can't infer the full signature, we may be able to
239 // infer the kind. This can occur if there is a trait-reference
240 // like `F : Fn<A>`. Note that due to subtyping we could encounter
241 // many viable options, so pick the most restrictive.
242 let expected_kind = self.obligations_for_self_ty(expected_vid)
243 .filter_map(|(tr, _)| self.tcx.lang_items().fn_trait_kind(tr.def_id()))
244 .fold(None, |best, cur| {
245 Some(best.map_or(cur, |best| cmp::min(best, cur)))
248 (expected_sig, expected_kind)
251 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
252 /// everything we need to know about a closure or generator.
254 /// The `cause_span` should be the span that caused us to
255 /// have this expected signature, or `None` if we can't readily
257 fn deduce_sig_from_projection(
259 cause_span: Option<Span>,
260 projection: &ty::PolyProjectionPredicate<'tcx>,
261 ) -> Option<ExpectedSig<'tcx>> {
264 debug!("deduce_sig_from_projection({:?})", projection);
266 let trait_ref = projection.to_poly_trait_ref(tcx);
268 let is_fn = tcx.lang_items().fn_trait_kind(trait_ref.def_id()).is_some();
269 let gen_trait = tcx.lang_items().gen_trait().unwrap();
270 let is_gen = gen_trait == trait_ref.def_id();
271 if !is_fn && !is_gen {
272 debug!("deduce_sig_from_projection: not fn or generator");
277 // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
278 // associated item and not yield.
279 let return_assoc_item = self.tcx.associated_items(gen_trait).nth(1).unwrap().def_id;
280 if return_assoc_item != projection.projection_def_id() {
281 debug!("deduce_sig_from_projection: not return assoc item of generator");
286 let input_tys = if is_fn {
287 let arg_param_ty = trait_ref.skip_binder().substs.type_at(1);
288 let arg_param_ty = self.resolve_vars_if_possible(&arg_param_ty);
289 debug!("deduce_sig_from_projection: arg_param_ty={:?}", arg_param_ty);
291 match arg_param_ty.sty {
292 ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(),
296 // Generators cannot have explicit arguments.
300 let ret_param_ty = projection.skip_binder().ty;
301 let ret_param_ty = self.resolve_vars_if_possible(&ret_param_ty);
302 debug!("deduce_sig_from_projection: ret_param_ty={:?}", ret_param_ty);
304 let sig = self.tcx.mk_fn_sig(
308 hir::Unsafety::Normal,
311 debug!("deduce_sig_from_projection: sig={:?}", sig);
313 Some(ExpectedSig { cause_span, sig })
321 expected_sig: Option<ExpectedSig<'tcx>>,
322 ) -> ClosureSignatures<'tcx> {
323 if let Some(e) = expected_sig {
324 self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
326 self.sig_of_closure_no_expectation(expr_def_id, decl, body)
330 /// If there is no expected signature, then we will convert the
331 /// types that the user gave into a signature.
332 fn sig_of_closure_no_expectation(
337 ) -> ClosureSignatures<'tcx> {
338 debug!("sig_of_closure_no_expectation()");
340 let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl);
342 self.closure_sigs(expr_def_id, body, bound_sig)
345 /// Invoked to compute the signature of a closure expression. This
346 /// combines any user-provided type annotations (e.g., `|x: u32|
347 /// -> u32 { .. }`) with the expected signature.
349 /// The approach is as follows:
351 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
352 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
353 /// - If we have no expectation `E`, then the signature of the closure is `S`.
354 /// - Otherwise, the signature of the closure is E. Moreover:
355 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
356 /// - Instantiate all the late-bound regions bound in the closure within `S`
357 /// with fresh (existential) variables, yielding `S'`
358 /// - Require that `E' = S'`
359 /// - We could use some kind of subtyping relationship here,
360 /// I imagine, but equality is easier and works fine for
363 /// The key intuition here is that the user's types must be valid
364 /// from "the inside" of the closure, but the expectation
365 /// ultimately drives the overall signature.
370 /// fn with_closure<F>(_: F)
371 /// where F: Fn(&u32) -> &u32 { .. }
373 /// with_closure(|x: &u32| { ... })
377 /// - E would be `fn(&u32) -> &u32`.
378 /// - S would be `fn(&u32) ->
379 /// - E' is `&'!0 u32 -> &'!0 u32`
380 /// - S' is `&'?0 u32 -> ?T`
382 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
386 /// - `expr_def_id`: the `DefId` of the closure expression
387 /// - `decl`: the HIR declaration of the closure
388 /// - `body`: the body of the closure
389 /// - `expected_sig`: the expected signature (if any). Note that
390 /// this is missing a binder: that is, there may be late-bound
391 /// regions with depth 1, which are bound then by the closure.
392 fn sig_of_closure_with_expectation(
397 expected_sig: ExpectedSig<'tcx>,
398 ) -> ClosureSignatures<'tcx> {
400 "sig_of_closure_with_expectation(expected_sig={:?})",
404 // Watch out for some surprises and just ignore the
405 // expectation if things don't see to match up with what we
407 if expected_sig.sig.c_variadic != decl.c_variadic {
408 return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
409 } else if expected_sig.sig.inputs_and_output.len() != decl.inputs.len() + 1 {
410 return self.sig_of_closure_with_mismatched_number_of_arguments(
418 // Create a `PolyFnSig`. Note the oddity that late bound
419 // regions appearing free in `expected_sig` are now bound up
420 // in this binder we are creating.
421 assert!(!expected_sig.sig.has_vars_bound_above(ty::INNERMOST));
422 let bound_sig = ty::Binder::bind(self.tcx.mk_fn_sig(
423 expected_sig.sig.inputs().iter().cloned(),
424 expected_sig.sig.output(),
426 hir::Unsafety::Normal,
430 // `deduce_expectations_from_expected_type` introduces
431 // late-bound lifetimes defined elsewhere, which we now
432 // anonymize away, so as not to confuse the user.
433 let bound_sig = self.tcx.anonymize_late_bound_regions(&bound_sig);
435 let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
437 // Up till this point, we have ignored the annotations that the user
438 // gave. This function will check that they unify successfully.
439 // Along the way, it also writes out entries for types that the user
440 // wrote into our tables, which are then later used by the privacy
442 match self.check_supplied_sig_against_expectation(expr_def_id, decl, body, &closure_sigs) {
443 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
444 Err(_) => return self.sig_of_closure_no_expectation(expr_def_id, decl, body),
450 fn sig_of_closure_with_mismatched_number_of_arguments(
455 expected_sig: ExpectedSig<'tcx>,
456 ) -> ClosureSignatures<'tcx> {
457 let expr_map_node = self.tcx.hir().get_if_local(expr_def_id).unwrap();
458 let expected_args: Vec<_> = expected_sig
462 .map(|ty| ArgKind::from_expected_ty(ty, None))
464 let (closure_span, found_args) = self.get_fn_like_arguments(expr_map_node);
465 let expected_span = expected_sig.cause_span.unwrap_or(closure_span);
466 self.report_arg_count_mismatch(
474 let error_sig = self.error_sig_of_closure(decl);
476 self.closure_sigs(expr_def_id, body, error_sig)
479 /// Enforce the user's types against the expectation. See
480 /// `sig_of_closure_with_expectation` for details on the overall
482 fn check_supplied_sig_against_expectation(
487 expected_sigs: &ClosureSignatures<'tcx>,
488 ) -> InferResult<'tcx, ()> {
489 // Get the signature S that the user gave.
491 // (See comment on `sig_of_closure_with_expectation` for the
492 // meaning of these letters.)
493 let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl);
496 "check_supplied_sig_against_expectation: supplied_sig={:?}",
500 // FIXME(#45727): As discussed in [this comment][c1], naively
501 // forcing equality here actually results in suboptimal error
502 // messages in some cases. For now, if there would have been
503 // an obvious error, we fallback to declaring the type of the
504 // closure to be the one the user gave, which allows other
505 // error message code to trigger.
507 // However, I think [there is potential to do even better
508 // here][c2], since in *this* code we have the precise span of
509 // the type parameter in question in hand when we report the
512 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
513 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
514 self.infcx.commit_if_ok(|_| {
515 let mut all_obligations = vec![];
517 // The liberated version of this signature should be a subtype
518 // of the liberated form of the expectation.
519 for ((hir_ty, &supplied_ty), expected_ty) in decl.inputs.iter()
520 .zip(*supplied_sig.inputs().skip_binder()) // binder moved to (*) below
521 .zip(expected_sigs.liberated_sig.inputs())
522 // `liberated_sig` is E'.
524 // Instantiate (this part of..) S to S', i.e., with fresh variables.
525 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
527 LateBoundRegionConversionTime::FnCall,
528 &ty::Binder::bind(supplied_ty),
529 ); // recreated from (*) above
531 // Check that E' = S'.
532 let cause = &self.misc(hir_ty.span);
536 } = self.at(cause, self.param_env)
537 .eq(*expected_ty, supplied_ty)?;
538 all_obligations.extend(obligations);
540 // Also, require that the supplied type must outlive
542 let closure_body_region = self.tcx.mk_region(
545 id: body.value.hir_id.local_id,
546 data: region::ScopeData::Node,
550 all_obligations.push(
554 ty::Predicate::TypeOutlives(
556 ty::OutlivesPredicate(
566 let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
568 LateBoundRegionConversionTime::FnCall,
569 &supplied_sig.output(),
571 let cause = &self.misc(decl.output.span());
575 } = self.at(cause, self.param_env)
576 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
577 all_obligations.extend(obligations);
581 obligations: all_obligations,
586 /// If there is no expected signature, then we will convert the
587 /// types that the user gave into a signature.
589 /// Also, record this closure signature for later.
590 fn supplied_sig_of_closure(
594 ) -> ty::PolyFnSig<'tcx> {
595 let astconv: &dyn AstConv<'_, '_> = self;
597 // First, convert the types that the user supplied (if any).
598 let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
599 let supplied_return = match decl.output {
600 hir::Return(ref output) => astconv.ast_ty_to_ty(&output),
601 hir::DefaultReturn(_) => astconv.ty_infer(None, decl.output.span()),
604 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
608 hir::Unsafety::Normal,
612 debug!("supplied_sig_of_closure: result={:?}", result);
614 let c_result = self.inh.infcx.canonicalize_response(&result);
615 self.tables.borrow_mut().user_provided_sigs.insert(
623 /// Converts the types that the user supplied, in case that doing
624 /// so should yield an error, but returns back a signature where
625 /// all parameters are of type `TyErr`.
626 fn error_sig_of_closure(&self, decl: &hir::FnDecl) -> ty::PolyFnSig<'tcx> {
627 let astconv: &dyn AstConv<'_, '_> = self;
629 let supplied_arguments = decl.inputs.iter().map(|a| {
630 // Convert the types that the user supplied (if any), but ignore them.
631 astconv.ast_ty_to_ty(a);
635 if let hir::Return(ref output) = decl.output {
636 astconv.ast_ty_to_ty(&output);
639 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
643 hir::Unsafety::Normal,
647 debug!("supplied_sig_of_closure: result={:?}", result);
656 bound_sig: ty::PolyFnSig<'tcx>,
657 ) -> ClosureSignatures<'tcx> {
658 let liberated_sig = self.tcx()
659 .liberate_late_bound_regions(expr_def_id, &bound_sig);
660 let liberated_sig = self.inh.normalize_associated_types_in(