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};
16 use rustc::hir::def_id::DefId;
17 use rustc::infer::{InferOk, InferResult};
18 use rustc::infer::LateBoundRegionConversionTime;
19 use rustc::infer::type_variable::TypeVariableOrigin;
20 use rustc::traits::error_reporting::ArgKind;
21 use rustc::ty::{self, ToPolyTraitRef, Ty};
22 use rustc::ty::subst::Substs;
23 use rustc::ty::TypeFoldable;
27 use syntax::codemap::Span;
30 /// What signature do we *expect* the closure to have from context?
32 struct ExpectedSig<'tcx> {
33 /// Span that gave us this expectation, if we know that.
34 cause_span: Option<Span>,
38 struct ClosureSignatures<'tcx> {
39 bound_sig: ty::PolyFnSig<'tcx>,
40 liberated_sig: ty::FnSig<'tcx>,
43 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
44 pub fn check_expr_closure(
47 _capture: hir::CaptureClause,
48 decl: &'gcx hir::FnDecl,
50 gen: Option<hir::GeneratorMovability>,
51 expected: Expectation<'tcx>,
54 "check_expr_closure(expr={:?},expected={:?})",
58 // It's always helpful for inference if we know the kind of
59 // closure sooner rather than later, so first examine the expected
60 // type, and see if can glean a closure kind from there.
61 let (expected_sig, expected_kind) = match expected.to_option(self) {
62 Some(ty) => self.deduce_expectations_from_expected_type(ty),
65 let body = self.tcx.hir.body(body_id);
66 self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
72 opt_kind: Option<ty::ClosureKind>,
73 decl: &'gcx hir::FnDecl,
74 body: &'gcx hir::Body,
75 gen: Option<hir::GeneratorMovability>,
76 expected_sig: Option<ExpectedSig<'tcx>>,
79 "check_closure(opt_kind={:?}, expected_sig={:?})",
80 opt_kind, expected_sig
83 let expr_def_id = self.tcx.hir.local_def_id(expr.id);
85 let ClosureSignatures {
88 } = self.sig_of_closure(expr_def_id, decl, body, expected_sig);
90 debug!("check_closure: ty_of_closure returns {:?}", liberated_sig);
92 let generator_types = check_fn(
102 // Create type variables (for now) to represent the transformed
103 // types of upvars. These will be unified during the upvar
104 // inference phase (`upvar.rs`).
106 Substs::identity_for_item(self.tcx, self.tcx.closure_base_def_id(expr_def_id));
107 let substs = base_substs.extend_to(
110 |_, _| span_bug!(expr.span, "closure has region param"),
113 .next_ty_var(ty::UniverseIndex::ROOT,
114 TypeVariableOrigin::ClosureSynthetic(expr.span))
117 let substs = ty::ClosureSubsts { substs };
118 let closure_type = self.tcx.mk_closure(expr_def_id, substs);
120 if let Some(GeneratorTypes { yield_ty, interior }) = generator_types {
124 substs.generator_yield_ty(expr_def_id, self.tcx),
128 liberated_sig.output(),
129 substs.generator_return_ty(expr_def_id, self.tcx),
131 return self.tcx.mk_generator(expr_def_id, substs, interior);
135 "check_closure: expr.id={:?} closure_type={:?}",
136 expr.id, closure_type
139 // Tuple up the arguments and insert the resulting function type into
140 // the `closures` table.
141 let sig = bound_sig.map_bound(|sig| {
143 iter::once(self.tcx.intern_tup(sig.inputs(), false)),
152 "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
153 expr_def_id, sig, opt_kind
156 let sig_fn_ptr_ty = self.tcx.mk_fn_ptr(sig);
160 substs.closure_sig_ty(expr_def_id, self.tcx),
163 if let Some(kind) = opt_kind {
166 kind.to_ty(self.tcx),
167 substs.closure_kind_ty(expr_def_id, self.tcx),
174 /// Given the expected type, figures out what it can about this closure we
175 /// are about to type check:
176 fn deduce_expectations_from_expected_type(
178 expected_ty: Ty<'tcx>,
179 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
181 "deduce_expectations_from_expected_type(expected_ty={:?})",
185 match expected_ty.sty {
186 ty::TyDynamic(ref object_type, ..) => {
187 let sig = object_type
190 let pb = pb.with_self_ty(self.tcx, self.tcx.types.err);
191 self.deduce_sig_from_projection(None, &pb)
194 let kind = object_type
196 .and_then(|p| self.tcx.lang_items().fn_trait_kind(p.def_id()));
199 ty::TyInfer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
200 ty::TyFnPtr(sig) => {
201 let expected_sig = ExpectedSig {
203 sig: sig.skip_binder().clone(),
205 (Some(expected_sig), Some(ty::ClosureKind::Fn))
211 fn deduce_expectations_from_obligations(
213 expected_vid: ty::TyVid,
214 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
215 let fulfillment_cx = self.fulfillment_cx.borrow();
216 // Here `expected_ty` is known to be a type inference variable.
218 let expected_sig = fulfillment_cx
219 .pending_obligations()
221 .map(|obligation| &obligation.obligation)
222 .filter_map(|obligation| {
224 "deduce_expectations_from_obligations: obligation.predicate={:?}",
228 match obligation.predicate {
229 // Given a Projection predicate, we can potentially infer
230 // the complete signature.
231 ty::Predicate::Projection(ref proj_predicate) => {
232 let trait_ref = proj_predicate.to_poly_trait_ref(self.tcx);
233 self.self_type_matches_expected_vid(trait_ref, expected_vid)
235 self.deduce_sig_from_projection(
236 Some(obligation.cause.span),
246 // Even if we can't infer the full signature, we may be able to
247 // infer the kind. This can occur if there is a trait-reference
248 // like `F : Fn<A>`. Note that due to subtyping we could encounter
249 // many viable options, so pick the most restrictive.
250 let expected_kind = fulfillment_cx
251 .pending_obligations()
253 .map(|obligation| &obligation.obligation)
254 .filter_map(|obligation| {
255 let opt_trait_ref = match obligation.predicate {
256 ty::Predicate::Projection(ref data) => Some(data.to_poly_trait_ref(self.tcx)),
257 ty::Predicate::Trait(ref data) => Some(data.to_poly_trait_ref()),
258 ty::Predicate::Equate(..) => None,
259 ty::Predicate::Subtype(..) => None,
260 ty::Predicate::RegionOutlives(..) => None,
261 ty::Predicate::TypeOutlives(..) => None,
262 ty::Predicate::WellFormed(..) => None,
263 ty::Predicate::ObjectSafe(..) => None,
264 ty::Predicate::ConstEvaluatable(..) => None,
266 // NB: This predicate is created by breaking down a
267 // `ClosureType: FnFoo()` predicate, where
268 // `ClosureType` represents some `TyClosure`. It can't
269 // possibly be referring to the current closure,
270 // because we haven't produced the `TyClosure` for
271 // this closure yet; this is exactly why the other
272 // code is looking for a self type of a unresolved
273 // inference variable.
274 ty::Predicate::ClosureKind(..) => None,
277 .and_then(|tr| self.self_type_matches_expected_vid(tr, expected_vid))
278 .and_then(|tr| self.tcx.lang_items().fn_trait_kind(tr.def_id()))
280 .fold(None, |best, cur| {
281 Some(best.map_or(cur, |best| cmp::min(best, cur)))
284 (expected_sig, expected_kind)
287 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
288 /// everything we need to know about a closure.
290 /// The `cause_span` should be the span that caused us to
291 /// have this expected signature, or `None` if we can't readily
293 fn deduce_sig_from_projection(
295 cause_span: Option<Span>,
296 projection: &ty::PolyProjectionPredicate<'tcx>,
297 ) -> Option<ExpectedSig<'tcx>> {
300 debug!("deduce_sig_from_projection({:?})", projection);
302 let trait_ref = projection.to_poly_trait_ref(tcx);
304 if tcx.lang_items().fn_trait_kind(trait_ref.def_id()).is_none() {
308 let arg_param_ty = trait_ref.substs().type_at(1);
309 let arg_param_ty = self.resolve_type_vars_if_possible(&arg_param_ty);
311 "deduce_sig_from_projection: arg_param_ty {:?}",
315 let input_tys = match arg_param_ty.sty {
316 ty::TyTuple(tys, _) => tys.into_iter(),
322 let ret_param_ty = projection.0.ty;
323 let ret_param_ty = self.resolve_type_vars_if_possible(&ret_param_ty);
325 "deduce_sig_from_projection: ret_param_ty {:?}",
329 let sig = self.tcx.mk_fn_sig(
333 hir::Unsafety::Normal,
336 debug!("deduce_sig_from_projection: sig {:?}", sig);
338 Some(ExpectedSig { cause_span, sig })
341 fn self_type_matches_expected_vid(
343 trait_ref: ty::PolyTraitRef<'tcx>,
344 expected_vid: ty::TyVid,
345 ) -> Option<ty::PolyTraitRef<'tcx>> {
346 let self_ty = self.shallow_resolve(trait_ref.self_ty());
348 "self_type_matches_expected_vid(trait_ref={:?}, self_ty={:?})",
352 ty::TyInfer(ty::TyVar(v)) if expected_vid == v => Some(trait_ref),
362 expected_sig: Option<ExpectedSig<'tcx>>,
363 ) -> ClosureSignatures<'tcx> {
364 if let Some(e) = expected_sig {
365 self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
367 self.sig_of_closure_no_expectation(expr_def_id, decl, body)
371 /// If there is no expected signature, then we will convert the
372 /// types that the user gave into a signature.
373 fn sig_of_closure_no_expectation(
378 ) -> ClosureSignatures<'tcx> {
379 debug!("sig_of_closure_no_expectation()");
381 let bound_sig = self.supplied_sig_of_closure(decl);
383 self.closure_sigs(expr_def_id, body, bound_sig)
386 /// Invoked to compute the signature of a closure expression. This
387 /// combines any user-provided type annotations (e.g., `|x: u32|
388 /// -> u32 { .. }`) with the expected signature.
390 /// The approach is as follows:
392 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
393 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
394 /// - If we have no expectation `E`, then the signature of the closure is `S`.
395 /// - Otherwise, the signature of the closure is E. Moreover:
396 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
397 /// - Instantiate all the late-bound regions bound in the closure within `S`
398 /// with fresh (existential) variables, yielding `S'`
399 /// - Require that `E' = S'`
400 /// - We could use some kind of subtyping relationship here,
401 /// I imagine, but equality is easier and works fine for
404 /// The key intuition here is that the user's types must be valid
405 /// from "the inside" of the closure, but the expectation
406 /// ultimately drives the overall signature.
411 /// fn with_closure<F>(_: F)
412 /// where F: Fn(&u32) -> &u32 { .. }
414 /// with_closure(|x: &u32| { ... })
418 /// - E would be `fn(&u32) -> &u32`.
419 /// - S would be `fn(&u32) ->
420 /// - E' is `&'!0 u32 -> &'!0 u32`
421 /// - S' is `&'?0 u32 -> ?T`
423 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
427 /// - `expr_def_id`: the def-id of the closure expression
428 /// - `decl`: the HIR declaration of the closure
429 /// - `body`: the body of the closure
430 /// - `expected_sig`: the expected signature (if any). Note that
431 /// this is missing a binder: that is, there may be late-bound
432 /// regions with depth 1, which are bound then by the closure.
433 fn sig_of_closure_with_expectation(
438 expected_sig: ExpectedSig<'tcx>,
439 ) -> ClosureSignatures<'tcx> {
441 "sig_of_closure_with_expectation(expected_sig={:?})",
445 // Watch out for some surprises and just ignore the
446 // expectation if things don't see to match up with what we
448 if expected_sig.sig.variadic != decl.variadic {
449 return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
450 } else if expected_sig.sig.inputs_and_output.len() != decl.inputs.len() + 1 {
451 return self.sig_of_closure_with_mismatched_number_of_arguments(
459 // Create a `PolyFnSig`. Note the oddity that late bound
460 // regions appearing free in `expected_sig` are now bound up
461 // in this binder we are creating.
462 assert!(!expected_sig.sig.has_regions_escaping_depth(1));
463 let bound_sig = ty::Binder(self.tcx.mk_fn_sig(
464 expected_sig.sig.inputs().iter().cloned(),
465 expected_sig.sig.output(),
467 hir::Unsafety::Normal,
471 // `deduce_expectations_from_expected_type` introduces
472 // late-bound lifetimes defined elsewhere, which we now
473 // anonymize away, so as not to confuse the user.
474 let bound_sig = self.tcx.anonymize_late_bound_regions(&bound_sig);
476 let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
478 // Up till this point, we have ignored the annotations that the user
479 // gave. This function will check that they unify successfully.
480 // Along the way, it also writes out entries for types that the user
481 // wrote into our tables, which are then later used by the privacy
483 match self.check_supplied_sig_against_expectation(decl, &closure_sigs) {
484 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
485 Err(_) => return self.sig_of_closure_no_expectation(expr_def_id, decl, body),
491 fn sig_of_closure_with_mismatched_number_of_arguments(
496 expected_sig: ExpectedSig<'tcx>,
497 ) -> ClosureSignatures<'tcx> {
498 let expr_map_node = self.tcx.hir.get_if_local(expr_def_id).unwrap();
499 let expected_args: Vec<_> = expected_sig
503 .map(|ty| ArgKind::from_expected_ty(ty))
505 let (closure_span, found_args) = self.get_fn_like_arguments(expr_map_node);
506 let expected_span = expected_sig.cause_span.unwrap_or(closure_span);
507 self.report_arg_count_mismatch(
515 let error_sig = self.error_sig_of_closure(decl);
517 self.closure_sigs(expr_def_id, body, error_sig)
520 /// Enforce the user's types against the expectation. See
521 /// `sig_of_closure_with_expectation` for details on the overall
523 fn check_supplied_sig_against_expectation(
526 expected_sigs: &ClosureSignatures<'tcx>,
527 ) -> InferResult<'tcx, ()> {
528 // Get the signature S that the user gave.
530 // (See comment on `sig_of_closure_with_expectation` for the
531 // meaning of these letters.)
532 let supplied_sig = self.supplied_sig_of_closure(decl);
535 "check_supplied_sig_against_expectation: supplied_sig={:?}",
539 // FIXME(#45727): As discussed in [this comment][c1], naively
540 // forcing equality here actually results in suboptimal error
541 // messages in some cases. For now, if there would have been
542 // an obvious error, we fallback to declaring the type of the
543 // closure to be the one the user gave, which allows other
544 // error message code to trigger.
546 // However, I think [there is potential to do even better
547 // here][c2], since in *this* code we have the precise span of
548 // the type parameter in question in hand when we report the
551 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
552 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
553 self.infcx.commit_if_ok(|_| {
554 let mut all_obligations = vec![];
556 // The liberated version of this signature should be be a subtype
557 // of the liberated form of the expectation.
558 for ((hir_ty, &supplied_ty), expected_ty) in decl.inputs.iter()
559 .zip(*supplied_sig.inputs().skip_binder()) // binder moved to (*) below
560 .zip(expected_sigs.liberated_sig.inputs())
561 // `liberated_sig` is E'.
563 // Instantiate (this part of..) S to S', i.e., with fresh variables.
564 let (supplied_ty, _) = self.infcx.replace_late_bound_regions_with_fresh_var(
566 LateBoundRegionConversionTime::FnCall,
567 &ty::Binder(supplied_ty),
568 ); // recreated from (*) above
570 // Check that E' = S'.
571 let cause = &self.misc(hir_ty.span);
575 } = self.at(cause, self.param_env)
576 .eq(*expected_ty, supplied_ty)?;
577 all_obligations.extend(obligations);
580 let (supplied_output_ty, _) = self.infcx.replace_late_bound_regions_with_fresh_var(
582 LateBoundRegionConversionTime::FnCall,
583 &supplied_sig.output(),
585 let cause = &self.misc(decl.output.span());
589 } = self.at(cause, self.param_env)
590 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
591 all_obligations.extend(obligations);
595 obligations: all_obligations,
600 /// If there is no expected signature, then we will convert the
601 /// types that the user gave into a signature.
602 fn supplied_sig_of_closure(&self, decl: &hir::FnDecl) -> ty::PolyFnSig<'tcx> {
603 let astconv: &AstConv = self;
605 // First, convert the types that the user supplied (if any).
606 let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
607 let supplied_return = match decl.output {
608 hir::Return(ref output) => astconv.ast_ty_to_ty(&output),
609 hir::DefaultReturn(_) => astconv.ty_infer(decl.output.span()),
612 let result = ty::Binder(self.tcx.mk_fn_sig(
616 hir::Unsafety::Normal,
620 debug!("supplied_sig_of_closure: result={:?}", result);
625 /// Converts the types that the user supplied, in case that doing
626 /// so should yield an error, but returns back a signature where
627 /// all parameters are of type `TyErr`.
628 fn error_sig_of_closure(&self, decl: &hir::FnDecl) -> ty::PolyFnSig<'tcx> {
629 let astconv: &AstConv = self;
631 let supplied_arguments = decl.inputs.iter().map(|a| {
632 // Convert the types that the user supplied (if any), but ignore them.
633 astconv.ast_ty_to_ty(a);
638 hir::Return(ref output) => {
639 astconv.ast_ty_to_ty(&output);
641 hir::DefaultReturn(_) => {}
644 let result = ty::Binder(self.tcx.mk_fn_sig(
648 hir::Unsafety::Normal,
652 debug!("supplied_sig_of_closure: result={:?}", result);
661 bound_sig: ty::PolyFnSig<'tcx>,
662 ) -> ClosureSignatures<'tcx> {
663 let liberated_sig = self.tcx()
664 .liberate_late_bound_regions(expr_def_id, &bound_sig);
665 let liberated_sig = self.inh.normalize_associated_types_in(