]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/closure.rs
Rollup merge of #58802 - nnethercote:inline-record_layout, r=oli-obk
[rust.git] / src / librustc_typeck / check / closure.rs
1 //! Code for type-checking closure expressions.
2
3 use super::{check_fn, Expectation, FnCtxt, GeneratorTypes};
4
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;
16 use std::cmp;
17 use std::iter;
18 use rustc_target::spec::abi::Abi;
19 use syntax::source_map::Span;
20 use rustc::hir;
21
22 /// What signature do we *expect* the closure to have from context?
23 #[derive(Debug)]
24 struct ExpectedSig<'tcx> {
25     /// Span that gave us this expectation, if we know that.
26     cause_span: Option<Span>,
27     sig: ty::FnSig<'tcx>,
28 }
29
30 struct ClosureSignatures<'tcx> {
31     bound_sig: ty::PolyFnSig<'tcx>,
32     liberated_sig: ty::FnSig<'tcx>,
33 }
34
35 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
36     pub fn check_expr_closure(
37         &self,
38         expr: &hir::Expr,
39         _capture: hir::CaptureClause,
40         decl: &'gcx hir::FnDecl,
41         body_id: hir::BodyId,
42         gen: Option<hir::GeneratorMovability>,
43         expected: Expectation<'tcx>,
44     ) -> Ty<'tcx> {
45         debug!(
46             "check_expr_closure(expr={:?},expected={:?})",
47             expr, expected
48         );
49
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),
55             None => (None, None),
56         };
57         let body = self.tcx.hir().body(body_id);
58         self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
59     }
60
61     fn check_closure(
62         &self,
63         expr: &hir::Expr,
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>>,
69     ) -> Ty<'tcx> {
70         debug!(
71             "check_closure(opt_kind={:?}, expected_sig={:?})",
72             opt_kind, expected_sig
73         );
74
75         let expr_def_id = self.tcx.hir().local_def_id_from_hir_id(expr.hir_id);
76
77         let ClosureSignatures {
78             bound_sig,
79             liberated_sig,
80         } = self.sig_of_closure(expr_def_id, decl, body, expected_sig);
81
82         debug!("check_closure: ty_of_closure returns {:?}", liberated_sig);
83
84         let generator_types = check_fn(
85             self,
86             self.param_env,
87             liberated_sig,
88             decl,
89             expr.hir_id,
90             body,
91             gen,
92         ).1;
93
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`).
97         let base_substs =
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, _| {
100             match param.kind {
101                 GenericParamDefKind::Lifetime => {
102                     span_bug!(expr.span, "closure has region param")
103                 }
104                 GenericParamDefKind::Type {..} => {
105                     self.infcx
106                         .next_ty_var(TypeVariableOrigin::ClosureSynthetic(expr.span)).into()
107                 }
108             }
109         });
110         if let Some(GeneratorTypes { yield_ty, interior, movability }) = generator_types {
111             let substs = ty::GeneratorSubsts { substs };
112             self.demand_eqtype(
113                 expr.span,
114                 yield_ty,
115                 substs.yield_ty(expr_def_id, self.tcx),
116             );
117             self.demand_eqtype(
118                 expr.span,
119                 liberated_sig.output(),
120                 substs.return_ty(expr_def_id, self.tcx),
121             );
122             self.demand_eqtype(
123                 expr.span,
124                 interior,
125                 substs.witness(expr_def_id, self.tcx),
126             );
127             return self.tcx.mk_generator(expr_def_id, substs, movability);
128         }
129
130         let substs = ty::ClosureSubsts { substs };
131         let closure_type = self.tcx.mk_closure(expr_def_id, substs);
132
133         debug!(
134             "check_closure: expr.hir_id={:?} closure_type={:?}",
135             expr.hir_id, closure_type
136         );
137
138         // Tuple up the arguments and insert the resulting function type into
139         // the `closures` table.
140         let sig = bound_sig.map_bound(|sig| {
141             self.tcx.mk_fn_sig(
142                 iter::once(self.tcx.intern_tup(sig.inputs())),
143                 sig.output(),
144                 sig.c_variadic,
145                 sig.unsafety,
146                 sig.abi,
147             )
148         });
149
150         debug!(
151             "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
152             expr_def_id, sig, opt_kind
153         );
154
155         let sig_fn_ptr_ty = self.tcx.mk_fn_ptr(sig);
156         self.demand_eqtype(
157             expr.span,
158             sig_fn_ptr_ty,
159             substs.closure_sig_ty(expr_def_id, self.tcx),
160         );
161
162         if let Some(kind) = opt_kind {
163             self.demand_eqtype(
164                 expr.span,
165                 kind.to_ty(self.tcx),
166                 substs.closure_kind_ty(expr_def_id, self.tcx),
167             );
168         }
169
170         closure_type
171     }
172
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(
176         &self,
177         expected_ty: Ty<'tcx>,
178     ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
179         debug!(
180             "deduce_expectations_from_expected_type(expected_ty={:?})",
181             expected_ty
182         );
183
184         match expected_ty.sty {
185             ty::Dynamic(ref object_type, ..) => {
186                 let sig = object_type
187                     .projection_bounds()
188                     .filter_map(|pb| {
189                         let pb = pb.with_self_ty(self.tcx, self.tcx.types.err);
190                         self.deduce_sig_from_projection(None, &pb)
191                     })
192                     .next();
193                 let kind = object_type.principal_def_id().and_then(|did| {
194                     self.tcx.lang_items().fn_trait_kind(did)
195                 });
196                 (sig, kind)
197             }
198             ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
199             ty::FnPtr(sig) => {
200                 let expected_sig = ExpectedSig {
201                     cause_span: None,
202                     sig: sig.skip_binder().clone(),
203                 };
204                 (Some(expected_sig), Some(ty::ClosureKind::Fn))
205             }
206             _ => (None, None),
207         }
208     }
209
210     fn deduce_expectations_from_obligations(
211         &self,
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)| {
216                 debug!(
217                     "deduce_expectations_from_obligations: obligation.predicate={:?}",
218                     obligation.predicate
219                 );
220
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),
226                         proj_predicate
227                     )
228                 } else {
229                     None
230                 }
231             });
232
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)))
241             });
242
243         (expected_sig, expected_kind)
244     }
245
246     /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
247     /// everything we need to know about a closure.
248     ///
249     /// The `cause_span` should be the span that caused us to
250     /// have this expected signature, or `None` if we can't readily
251     /// know that.
252     fn deduce_sig_from_projection(
253         &self,
254         cause_span: Option<Span>,
255         projection: &ty::PolyProjectionPredicate<'tcx>,
256     ) -> Option<ExpectedSig<'tcx>> {
257         let tcx = self.tcx;
258
259         debug!("deduce_sig_from_projection({:?})", projection);
260
261         let trait_ref = projection.to_poly_trait_ref(tcx);
262
263         if tcx.lang_items().fn_trait_kind(trait_ref.def_id()).is_none() {
264             return None;
265         }
266
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);
269         debug!(
270             "deduce_sig_from_projection: arg_param_ty {:?}",
271             arg_param_ty
272         );
273
274         let input_tys = match arg_param_ty.sty {
275             ty::Tuple(tys) => tys.into_iter(),
276             _ => return None
277         };
278
279         let ret_param_ty = projection.skip_binder().ty;
280         let ret_param_ty = self.resolve_type_vars_if_possible(&ret_param_ty);
281         debug!(
282             "deduce_sig_from_projection: ret_param_ty {:?}",
283             ret_param_ty
284         );
285
286         let sig = self.tcx.mk_fn_sig(
287             input_tys.cloned(),
288             ret_param_ty,
289             false,
290             hir::Unsafety::Normal,
291             Abi::Rust,
292         );
293         debug!("deduce_sig_from_projection: sig {:?}", sig);
294
295         Some(ExpectedSig { cause_span, sig })
296     }
297
298     fn sig_of_closure(
299         &self,
300         expr_def_id: DefId,
301         decl: &hir::FnDecl,
302         body: &hir::Body,
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)
307         } else {
308             self.sig_of_closure_no_expectation(expr_def_id, decl, body)
309         }
310     }
311
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(
315         &self,
316         expr_def_id: DefId,
317         decl: &hir::FnDecl,
318         body: &hir::Body,
319     ) -> ClosureSignatures<'tcx> {
320         debug!("sig_of_closure_no_expectation()");
321
322         let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl);
323
324         self.closure_sigs(expr_def_id, body, bound_sig)
325     }
326
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.
330     ///
331     /// The approach is as follows:
332     ///
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
343     ///         our purposes.
344     ///
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.
348     ///
349     /// # Examples
350     ///
351     /// ```
352     /// fn with_closure<F>(_: F)
353     ///   where F: Fn(&u32) -> &u32 { .. }
354     ///
355     /// with_closure(|x: &u32| { ... })
356     /// ```
357     ///
358     /// Here:
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`
363     ///
364     /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
365     ///
366     /// # Arguments
367     ///
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(
375         &self,
376         expr_def_id: DefId,
377         decl: &hir::FnDecl,
378         body: &hir::Body,
379         expected_sig: ExpectedSig<'tcx>,
380     ) -> ClosureSignatures<'tcx> {
381         debug!(
382             "sig_of_closure_with_expectation(expected_sig={:?})",
383             expected_sig
384         );
385
386         // Watch out for some surprises and just ignore the
387         // expectation if things don't see to match up with what we
388         // expect.
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(
393                 expr_def_id,
394                 decl,
395                 body,
396                 expected_sig,
397             );
398         }
399
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(),
407             decl.c_variadic,
408             hir::Unsafety::Normal,
409             Abi::RustCall,
410         ));
411
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);
416
417         let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
418
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
423         // check.
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),
427         }
428
429         closure_sigs
430     }
431
432     fn sig_of_closure_with_mismatched_number_of_arguments(
433         &self,
434         expr_def_id: DefId,
435         decl: &hir::FnDecl,
436         body: &hir::Body,
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
441             .sig
442             .inputs()
443             .iter()
444             .map(|ty| ArgKind::from_expected_ty(ty, None))
445             .collect();
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(
449             expected_span,
450             Some(closure_span),
451             expected_args,
452             found_args,
453             true,
454         ).emit();
455
456         let error_sig = self.error_sig_of_closure(decl);
457
458         self.closure_sigs(expr_def_id, body, error_sig)
459     }
460
461     /// Enforce the user's types against the expectation. See
462     /// `sig_of_closure_with_expectation` for details on the overall
463     /// strategy.
464     fn check_supplied_sig_against_expectation(
465         &self,
466         expr_def_id: DefId,
467         decl: &hir::FnDecl,
468         body: &hir::Body,
469         expected_sigs: &ClosureSignatures<'tcx>,
470     ) -> InferResult<'tcx, ()> {
471         // Get the signature S that the user gave.
472         //
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);
476
477         debug!(
478             "check_supplied_sig_against_expectation: supplied_sig={:?}",
479             supplied_sig
480         );
481
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.
488         //
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
492         // error.
493         //
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![];
498
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'.
505             {
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(
508                     hir_ty.span,
509                     LateBoundRegionConversionTime::FnCall,
510                     &ty::Binder::bind(supplied_ty),
511                 ); // recreated from (*) above
512
513                 // Check that E' = S'.
514                 let cause = &self.misc(hir_ty.span);
515                 let InferOk {
516                     value: (),
517                     obligations,
518                 } = self.at(cause, self.param_env)
519                     .eq(*expected_ty, supplied_ty)?;
520                 all_obligations.extend(obligations);
521
522                 // Also, require that the supplied type must outlive
523                 // the closure body.
524                 let closure_body_region = self.tcx.mk_region(
525                     ty::ReScope(
526                         region::Scope {
527                             id: body.value.hir_id.local_id,
528                             data: region::ScopeData::Node,
529                         },
530                     ),
531                 );
532                 all_obligations.push(
533                     Obligation::new(
534                         cause.clone(),
535                         self.param_env,
536                         ty::Predicate::TypeOutlives(
537                             ty::Binder::dummy(
538                                 ty::OutlivesPredicate(
539                                     supplied_ty,
540                                     closure_body_region,
541                                 ),
542                             ),
543                         ),
544                     ),
545                 );
546             }
547
548             let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
549                 decl.output.span(),
550                 LateBoundRegionConversionTime::FnCall,
551                 &supplied_sig.output(),
552             );
553             let cause = &self.misc(decl.output.span());
554             let InferOk {
555                 value: (),
556                 obligations,
557             } = self.at(cause, self.param_env)
558                 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
559             all_obligations.extend(obligations);
560
561             Ok(InferOk {
562                 value: (),
563                 obligations: all_obligations,
564             })
565         })
566     }
567
568     /// If there is no expected signature, then we will convert the
569     /// types that the user gave into a signature.
570     ///
571     /// Also, record this closure signature for later.
572     fn supplied_sig_of_closure(
573         &self,
574         expr_def_id: DefId,
575         decl: &hir::FnDecl,
576     ) -> ty::PolyFnSig<'tcx> {
577         let astconv: &dyn AstConv<'_, '_> = self;
578
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()),
584         };
585
586         let result = ty::Binder::bind(self.tcx.mk_fn_sig(
587             supplied_arguments,
588             supplied_return,
589             decl.c_variadic,
590             hir::Unsafety::Normal,
591             Abi::RustCall,
592         ));
593
594         debug!("supplied_sig_of_closure: result={:?}", result);
595
596         let c_result = self.inh.infcx.canonicalize_response(&result);
597         self.tables.borrow_mut().user_provided_sigs.insert(
598             expr_def_id,
599             c_result,
600         );
601
602         result
603     }
604
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;
610
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);
614             self.tcx.types.err
615         });
616
617         if let hir::Return(ref output) = decl.output {
618             astconv.ast_ty_to_ty(&output);
619         }
620
621         let result = ty::Binder::bind(self.tcx.mk_fn_sig(
622             supplied_arguments,
623             self.tcx.types.err,
624             decl.c_variadic,
625             hir::Unsafety::Normal,
626             Abi::RustCall,
627         ));
628
629         debug!("supplied_sig_of_closure: result={:?}", result);
630
631         result
632     }
633
634     fn closure_sigs(
635         &self,
636         expr_def_id: DefId,
637         body: &hir::Body,
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(
643             body.value.span,
644             body.value.hir_id,
645             self.param_env,
646             &liberated_sig,
647         );
648         ClosureSignatures {
649             bound_sig,
650             liberated_sig,
651         }
652     }
653 }