1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Code for type-checking closure expressions.
13 use super::{check_fn, Expectation, FnCtxt, GeneratorTypes};
17 use rustc::hir::def_id::DefId;
18 use rustc::infer::{InferOk, InferResult};
19 use rustc::infer::LateBoundRegionConversionTime;
20 use rustc::infer::type_variable::TypeVariableOrigin;
21 use rustc::traits::Obligation;
22 use rustc::traits::error_reporting::ArgKind;
23 use rustc::ty::{self, ToPolyTraitRef, Ty, GenericParamDefKind};
24 use rustc::ty::fold::TypeFoldable;
25 use rustc::ty::subst::Substs;
28 use rustc_target::spec::abi::Abi;
29 use syntax::source_map::Span;
32 /// What signature do we *expect* the closure to have from context?
34 struct ExpectedSig<'tcx> {
35 /// Span that gave us this expectation, if we know that.
36 cause_span: Option<Span>,
40 struct ClosureSignatures<'tcx> {
41 bound_sig: ty::PolyFnSig<'tcx>,
42 liberated_sig: ty::FnSig<'tcx>,
45 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
46 pub fn check_expr_closure(
49 _capture: hir::CaptureClause,
50 decl: &'gcx hir::FnDecl,
52 gen: Option<hir::GeneratorMovability>,
53 expected: Expectation<'tcx>,
56 "check_expr_closure(expr={:?},expected={:?})",
60 // It's always helpful for inference if we know the kind of
61 // closure sooner rather than later, so first examine the expected
62 // type, and see if can glean a closure kind from there.
63 let (expected_sig, expected_kind) = match expected.to_option(self) {
64 Some(ty) => self.deduce_expectations_from_expected_type(ty),
67 let body = self.tcx.hir.body(body_id);
68 self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
74 opt_kind: Option<ty::ClosureKind>,
75 decl: &'gcx hir::FnDecl,
76 body: &'gcx hir::Body,
77 gen: Option<hir::GeneratorMovability>,
78 expected_sig: Option<ExpectedSig<'tcx>>,
81 "check_closure(opt_kind={:?}, expected_sig={:?})",
82 opt_kind, expected_sig
85 let expr_def_id = self.tcx.hir.local_def_id(expr.id);
87 let ClosureSignatures {
90 } = self.sig_of_closure(expr_def_id, decl, body, expected_sig);
92 debug!("check_closure: ty_of_closure returns {:?}", liberated_sig);
94 let generator_types = check_fn(
104 // Create type variables (for now) to represent the transformed
105 // types of upvars. These will be unified during the upvar
106 // inference phase (`upvar.rs`).
108 Substs::identity_for_item(self.tcx, self.tcx.closure_base_def_id(expr_def_id));
109 let substs = base_substs.extend_to(self.tcx,expr_def_id, |param, _| {
111 GenericParamDefKind::Lifetime => {
112 span_bug!(expr.span, "closure has region param")
114 GenericParamDefKind::Type {..} => {
116 .next_ty_var(TypeVariableOrigin::ClosureSynthetic(expr.span)).into()
120 if let Some(GeneratorTypes { yield_ty, interior, movability }) = generator_types {
121 let substs = ty::GeneratorSubsts { substs };
125 substs.yield_ty(expr_def_id, self.tcx),
129 liberated_sig.output(),
130 substs.return_ty(expr_def_id, self.tcx),
135 substs.witness(expr_def_id, self.tcx),
137 return self.tcx.mk_generator(expr_def_id, substs, movability);
140 let substs = ty::ClosureSubsts { substs };
141 let closure_type = self.tcx.mk_closure(expr_def_id, substs);
144 "check_closure: expr.id={:?} closure_type={:?}",
145 expr.id, closure_type
148 // Tuple up the arguments and insert the resulting function type into
149 // the `closures` table.
150 let sig = bound_sig.map_bound(|sig| {
152 iter::once(self.tcx.intern_tup(sig.inputs())),
161 "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
162 expr_def_id, sig, opt_kind
165 let sig_fn_ptr_ty = self.tcx.mk_fn_ptr(sig);
169 substs.closure_sig_ty(expr_def_id, self.tcx),
172 if let Some(kind) = opt_kind {
175 kind.to_ty(self.tcx),
176 substs.closure_kind_ty(expr_def_id, self.tcx),
183 /// Given the expected type, figures out what it can about this closure we
184 /// are about to type check:
185 fn deduce_expectations_from_expected_type(
187 expected_ty: Ty<'tcx>,
188 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
190 "deduce_expectations_from_expected_type(expected_ty={:?})",
194 match expected_ty.sty {
195 ty::Dynamic(ref object_type, ..) => {
196 let sig = object_type
199 let pb = pb.with_self_ty(self.tcx, self.tcx.types.err);
200 self.deduce_sig_from_projection(None, &pb)
203 let kind = self.tcx.lang_items().fn_trait_kind(object_type.principal().def_id());
206 ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
208 let expected_sig = ExpectedSig {
210 sig: sig.skip_binder().clone(),
212 (Some(expected_sig), Some(ty::ClosureKind::Fn))
218 fn deduce_expectations_from_obligations(
220 expected_vid: ty::TyVid,
221 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
222 let fulfillment_cx = self.fulfillment_cx.borrow();
223 // Here `expected_ty` is known to be a type inference variable.
225 let expected_sig = fulfillment_cx
226 .pending_obligations()
228 .filter_map(|obligation| {
230 "deduce_expectations_from_obligations: obligation.predicate={:?}",
234 if let ty::Predicate::Projection(ref proj_predicate) = obligation.predicate {
235 // Given a Projection predicate, we can potentially infer
236 // the complete signature.
237 let trait_ref = proj_predicate.to_poly_trait_ref(self.tcx);
238 self.self_type_matches_expected_vid(trait_ref, expected_vid)
240 self.deduce_sig_from_projection(
241 Some(obligation.cause.span),
251 // Even if we can't infer the full signature, we may be able to
252 // infer the kind. This can occur if there is a trait-reference
253 // like `F : Fn<A>`. Note that due to subtyping we could encounter
254 // many viable options, so pick the most restrictive.
255 let expected_kind = fulfillment_cx
256 .pending_obligations()
258 .filter_map(|obligation| {
259 let opt_trait_ref = match obligation.predicate {
260 ty::Predicate::Projection(ref data) => Some(data.to_poly_trait_ref(self.tcx)),
261 ty::Predicate::Trait(ref data) => Some(data.to_poly_trait_ref()),
262 ty::Predicate::Subtype(..) => None,
263 ty::Predicate::RegionOutlives(..) => None,
264 ty::Predicate::TypeOutlives(..) => None,
265 ty::Predicate::WellFormed(..) => None,
266 ty::Predicate::ObjectSafe(..) => None,
267 ty::Predicate::ConstEvaluatable(..) => None,
269 // NB: This predicate is created by breaking down a
270 // `ClosureType: FnFoo()` predicate, where
271 // `ClosureType` represents some `Closure`. It can't
272 // possibly be referring to the current closure,
273 // because we haven't produced the `Closure` for
274 // this closure yet; this is exactly why the other
275 // code is looking for a self type of a unresolved
276 // inference variable.
277 ty::Predicate::ClosureKind(..) => None,
280 .and_then(|tr| self.self_type_matches_expected_vid(tr, expected_vid))
281 .and_then(|tr| self.tcx.lang_items().fn_trait_kind(tr.def_id()))
283 .fold(None, |best, cur| {
284 Some(best.map_or(cur, |best| cmp::min(best, cur)))
287 (expected_sig, expected_kind)
290 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
291 /// everything we need to know about a closure.
293 /// The `cause_span` should be the span that caused us to
294 /// have this expected signature, or `None` if we can't readily
296 fn deduce_sig_from_projection(
298 cause_span: Option<Span>,
299 projection: &ty::PolyProjectionPredicate<'tcx>,
300 ) -> Option<ExpectedSig<'tcx>> {
303 debug!("deduce_sig_from_projection({:?})", projection);
305 let trait_ref = projection.to_poly_trait_ref(tcx);
307 if tcx.lang_items().fn_trait_kind(trait_ref.def_id()).is_none() {
311 let arg_param_ty = trait_ref.skip_binder().substs.type_at(1);
312 let arg_param_ty = self.resolve_type_vars_if_possible(&arg_param_ty);
314 "deduce_sig_from_projection: arg_param_ty {:?}",
318 let input_tys = match arg_param_ty.sty {
319 ty::Tuple(tys) => tys.into_iter(),
323 let ret_param_ty = projection.skip_binder().ty;
324 let ret_param_ty = self.resolve_type_vars_if_possible(&ret_param_ty);
326 "deduce_sig_from_projection: ret_param_ty {:?}",
330 let sig = self.tcx.mk_fn_sig(
334 hir::Unsafety::Normal,
337 debug!("deduce_sig_from_projection: sig {:?}", sig);
339 Some(ExpectedSig { cause_span, sig })
342 fn self_type_matches_expected_vid(
344 trait_ref: ty::PolyTraitRef<'tcx>,
345 expected_vid: ty::TyVid,
346 ) -> Option<ty::PolyTraitRef<'tcx>> {
347 let self_ty = self.shallow_resolve(trait_ref.self_ty());
349 "self_type_matches_expected_vid(trait_ref={:?}, self_ty={:?})",
353 ty::Infer(ty::TyVar(v)) if expected_vid == v => Some(trait_ref),
363 expected_sig: Option<ExpectedSig<'tcx>>,
364 ) -> ClosureSignatures<'tcx> {
365 if let Some(e) = expected_sig {
366 self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
368 self.sig_of_closure_no_expectation(expr_def_id, decl, body)
372 /// If there is no expected signature, then we will convert the
373 /// types that the user gave into a signature.
374 fn sig_of_closure_no_expectation(
379 ) -> ClosureSignatures<'tcx> {
380 debug!("sig_of_closure_no_expectation()");
382 let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl);
384 self.closure_sigs(expr_def_id, body, bound_sig)
387 /// Invoked to compute the signature of a closure expression. This
388 /// combines any user-provided type annotations (e.g., `|x: u32|
389 /// -> u32 { .. }`) with the expected signature.
391 /// The approach is as follows:
393 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
394 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
395 /// - If we have no expectation `E`, then the signature of the closure is `S`.
396 /// - Otherwise, the signature of the closure is E. Moreover:
397 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
398 /// - Instantiate all the late-bound regions bound in the closure within `S`
399 /// with fresh (existential) variables, yielding `S'`
400 /// - Require that `E' = S'`
401 /// - We could use some kind of subtyping relationship here,
402 /// I imagine, but equality is easier and works fine for
405 /// The key intuition here is that the user's types must be valid
406 /// from "the inside" of the closure, but the expectation
407 /// ultimately drives the overall signature.
412 /// fn with_closure<F>(_: F)
413 /// where F: Fn(&u32) -> &u32 { .. }
415 /// with_closure(|x: &u32| { ... })
419 /// - E would be `fn(&u32) -> &u32`.
420 /// - S would be `fn(&u32) ->
421 /// - E' is `&'!0 u32 -> &'!0 u32`
422 /// - S' is `&'?0 u32 -> ?T`
424 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
428 /// - `expr_def_id`: the def-id of the closure expression
429 /// - `decl`: the HIR declaration of the closure
430 /// - `body`: the body of the closure
431 /// - `expected_sig`: the expected signature (if any). Note that
432 /// this is missing a binder: that is, there may be late-bound
433 /// regions with depth 1, which are bound then by the closure.
434 fn sig_of_closure_with_expectation(
439 expected_sig: ExpectedSig<'tcx>,
440 ) -> ClosureSignatures<'tcx> {
442 "sig_of_closure_with_expectation(expected_sig={:?})",
446 // Watch out for some surprises and just ignore the
447 // expectation if things don't see to match up with what we
449 if expected_sig.sig.variadic != decl.variadic {
450 return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
451 } else if expected_sig.sig.inputs_and_output.len() != decl.inputs.len() + 1 {
452 return self.sig_of_closure_with_mismatched_number_of_arguments(
460 // Create a `PolyFnSig`. Note the oddity that late bound
461 // regions appearing free in `expected_sig` are now bound up
462 // in this binder we are creating.
463 assert!(!expected_sig.sig.has_regions_bound_above(ty::INNERMOST));
464 let bound_sig = ty::Binder::bind(self.tcx.mk_fn_sig(
465 expected_sig.sig.inputs().iter().cloned(),
466 expected_sig.sig.output(),
468 hir::Unsafety::Normal,
472 // `deduce_expectations_from_expected_type` introduces
473 // late-bound lifetimes defined elsewhere, which we now
474 // anonymize away, so as not to confuse the user.
475 let bound_sig = self.tcx.anonymize_late_bound_regions(&bound_sig);
477 let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
479 // Up till this point, we have ignored the annotations that the user
480 // gave. This function will check that they unify successfully.
481 // Along the way, it also writes out entries for types that the user
482 // wrote into our tables, which are then later used by the privacy
484 match self.check_supplied_sig_against_expectation(expr_def_id, decl, body, &closure_sigs) {
485 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
486 Err(_) => return self.sig_of_closure_no_expectation(expr_def_id, decl, body),
492 fn sig_of_closure_with_mismatched_number_of_arguments(
497 expected_sig: ExpectedSig<'tcx>,
498 ) -> ClosureSignatures<'tcx> {
499 let expr_map_node = self.tcx.hir.get_if_local(expr_def_id).unwrap();
500 let expected_args: Vec<_> = expected_sig
504 .map(|ty| ArgKind::from_expected_ty(ty, None))
506 let (closure_span, found_args) = self.get_fn_like_arguments(expr_map_node);
507 let expected_span = expected_sig.cause_span.unwrap_or(closure_span);
508 self.report_arg_count_mismatch(
516 let error_sig = self.error_sig_of_closure(decl);
518 self.closure_sigs(expr_def_id, body, error_sig)
521 /// Enforce the user's types against the expectation. See
522 /// `sig_of_closure_with_expectation` for details on the overall
524 fn check_supplied_sig_against_expectation(
529 expected_sigs: &ClosureSignatures<'tcx>,
530 ) -> InferResult<'tcx, ()> {
531 // Get the signature S that the user gave.
533 // (See comment on `sig_of_closure_with_expectation` for the
534 // meaning of these letters.)
535 let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl);
538 "check_supplied_sig_against_expectation: supplied_sig={:?}",
542 // FIXME(#45727): As discussed in [this comment][c1], naively
543 // forcing equality here actually results in suboptimal error
544 // messages in some cases. For now, if there would have been
545 // an obvious error, we fallback to declaring the type of the
546 // closure to be the one the user gave, which allows other
547 // error message code to trigger.
549 // However, I think [there is potential to do even better
550 // here][c2], since in *this* code we have the precise span of
551 // the type parameter in question in hand when we report the
554 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
555 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
556 self.infcx.commit_if_ok(|_| {
557 let mut all_obligations = vec![];
559 // The liberated version of this signature should be be a subtype
560 // of the liberated form of the expectation.
561 for ((hir_ty, &supplied_ty), expected_ty) in decl.inputs.iter()
562 .zip(*supplied_sig.inputs().skip_binder()) // binder moved to (*) below
563 .zip(expected_sigs.liberated_sig.inputs())
564 // `liberated_sig` is E'.
566 // Instantiate (this part of..) S to S', i.e., with fresh variables.
567 let (supplied_ty, _) = self.infcx.replace_late_bound_regions_with_fresh_var(
569 LateBoundRegionConversionTime::FnCall,
570 &ty::Binder::bind(supplied_ty),
571 ); // recreated from (*) above
573 // Check that E' = S'.
574 let cause = &self.misc(hir_ty.span);
578 } = self.at(cause, self.param_env)
579 .eq(*expected_ty, supplied_ty)?;
580 all_obligations.extend(obligations);
582 // Also, require that the supplied type must outlive
584 let closure_body_region = self.tcx.mk_region(
587 id: body.value.hir_id.local_id,
588 data: region::ScopeData::Node,
592 all_obligations.push(
596 ty::Predicate::TypeOutlives(
598 ty::OutlivesPredicate(
608 let (supplied_output_ty, _) = self.infcx.replace_late_bound_regions_with_fresh_var(
610 LateBoundRegionConversionTime::FnCall,
611 &supplied_sig.output(),
613 let cause = &self.misc(decl.output.span());
617 } = self.at(cause, self.param_env)
618 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
619 all_obligations.extend(obligations);
623 obligations: all_obligations,
628 /// If there is no expected signature, then we will convert the
629 /// types that the user gave into a signature.
631 /// Also, record this closure signature for later.
632 fn supplied_sig_of_closure(
636 ) -> ty::PolyFnSig<'tcx> {
637 let astconv: &dyn AstConv = self;
639 // First, convert the types that the user supplied (if any).
640 let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
641 let supplied_return = match decl.output {
642 hir::Return(ref output) => astconv.ast_ty_to_ty(&output),
643 hir::DefaultReturn(_) => astconv.ty_infer(decl.output.span()),
646 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
650 hir::Unsafety::Normal,
654 debug!("supplied_sig_of_closure: result={:?}", result);
656 let c_result = self.inh.infcx.canonicalize_response(&result);
657 self.tables.borrow_mut().user_provided_sigs.insert(
665 /// Converts the types that the user supplied, in case that doing
666 /// so should yield an error, but returns back a signature where
667 /// all parameters are of type `TyErr`.
668 fn error_sig_of_closure(&self, decl: &hir::FnDecl) -> ty::PolyFnSig<'tcx> {
669 let astconv: &dyn AstConv = self;
671 let supplied_arguments = decl.inputs.iter().map(|a| {
672 // Convert the types that the user supplied (if any), but ignore them.
673 astconv.ast_ty_to_ty(a);
677 if let hir::Return(ref output) = decl.output {
678 astconv.ast_ty_to_ty(&output);
681 let result = ty::Binder::bind(self.tcx.mk_fn_sig(
685 hir::Unsafety::Normal,
689 debug!("supplied_sig_of_closure: result={:?}", result);
698 bound_sig: ty::PolyFnSig<'tcx>,
699 ) -> ClosureSignatures<'tcx> {
700 let liberated_sig = self.tcx()
701 .liberate_late_bound_regions(expr_def_id, &bound_sig);
702 let liberated_sig = self.inh.normalize_associated_types_in(