]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/closure.rs
Rollup merge of #55630 - petrochenkov:noprelude, r=Centril
[rust.git] / src / librustc_typeck / check / closure.rs
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.
4 //
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.
10
11 //! Code for type-checking closure expressions.
12
13 use super::{check_fn, Expectation, FnCtxt, GeneratorTypes};
14
15 use astconv::AstConv;
16 use middle::region;
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;
26 use std::cmp;
27 use std::iter;
28 use rustc_target::spec::abi::Abi;
29 use syntax::source_map::Span;
30 use rustc::hir;
31
32 /// What signature do we *expect* the closure to have from context?
33 #[derive(Debug)]
34 struct ExpectedSig<'tcx> {
35     /// Span that gave us this expectation, if we know that.
36     cause_span: Option<Span>,
37     sig: ty::FnSig<'tcx>,
38 }
39
40 struct ClosureSignatures<'tcx> {
41     bound_sig: ty::PolyFnSig<'tcx>,
42     liberated_sig: ty::FnSig<'tcx>,
43 }
44
45 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
46     pub fn check_expr_closure(
47         &self,
48         expr: &hir::Expr,
49         _capture: hir::CaptureClause,
50         decl: &'gcx hir::FnDecl,
51         body_id: hir::BodyId,
52         gen: Option<hir::GeneratorMovability>,
53         expected: Expectation<'tcx>,
54     ) -> Ty<'tcx> {
55         debug!(
56             "check_expr_closure(expr={:?},expected={:?})",
57             expr, expected
58         );
59
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),
65             None => (None, None),
66         };
67         let body = self.tcx.hir.body(body_id);
68         self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
69     }
70
71     fn check_closure(
72         &self,
73         expr: &hir::Expr,
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>>,
79     ) -> Ty<'tcx> {
80         debug!(
81             "check_closure(opt_kind={:?}, expected_sig={:?})",
82             opt_kind, expected_sig
83         );
84
85         let expr_def_id = self.tcx.hir.local_def_id(expr.id);
86
87         let ClosureSignatures {
88             bound_sig,
89             liberated_sig,
90         } = self.sig_of_closure(expr_def_id, decl, body, expected_sig);
91
92         debug!("check_closure: ty_of_closure returns {:?}", liberated_sig);
93
94         let generator_types = check_fn(
95             self,
96             self.param_env,
97             liberated_sig,
98             decl,
99             expr.id,
100             body,
101             gen,
102         ).1;
103
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`).
107         let base_substs =
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, _| {
110             match param.kind {
111                 GenericParamDefKind::Lifetime => {
112                     span_bug!(expr.span, "closure has region param")
113                 }
114                 GenericParamDefKind::Type {..} => {
115                     self.infcx
116                         .next_ty_var(TypeVariableOrigin::ClosureSynthetic(expr.span)).into()
117                 }
118             }
119         });
120         if let Some(GeneratorTypes { yield_ty, interior, movability }) = generator_types {
121             let substs = ty::GeneratorSubsts { substs };
122             self.demand_eqtype(
123                 expr.span,
124                 yield_ty,
125                 substs.yield_ty(expr_def_id, self.tcx),
126             );
127             self.demand_eqtype(
128                 expr.span,
129                 liberated_sig.output(),
130                 substs.return_ty(expr_def_id, self.tcx),
131             );
132             self.demand_eqtype(
133                 expr.span,
134                 interior,
135                 substs.witness(expr_def_id, self.tcx),
136             );
137             return self.tcx.mk_generator(expr_def_id, substs, movability);
138         }
139
140         let substs = ty::ClosureSubsts { substs };
141         let closure_type = self.tcx.mk_closure(expr_def_id, substs);
142
143         debug!(
144             "check_closure: expr.id={:?} closure_type={:?}",
145             expr.id, closure_type
146         );
147
148         // Tuple up the arguments and insert the resulting function type into
149         // the `closures` table.
150         let sig = bound_sig.map_bound(|sig| {
151             self.tcx.mk_fn_sig(
152                 iter::once(self.tcx.intern_tup(sig.inputs())),
153                 sig.output(),
154                 sig.variadic,
155                 sig.unsafety,
156                 sig.abi,
157             )
158         });
159
160         debug!(
161             "check_closure: expr_def_id={:?}, sig={:?}, opt_kind={:?}",
162             expr_def_id, sig, opt_kind
163         );
164
165         let sig_fn_ptr_ty = self.tcx.mk_fn_ptr(sig);
166         self.demand_eqtype(
167             expr.span,
168             sig_fn_ptr_ty,
169             substs.closure_sig_ty(expr_def_id, self.tcx),
170         );
171
172         if let Some(kind) = opt_kind {
173             self.demand_eqtype(
174                 expr.span,
175                 kind.to_ty(self.tcx),
176                 substs.closure_kind_ty(expr_def_id, self.tcx),
177             );
178         }
179
180         closure_type
181     }
182
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(
186         &self,
187         expected_ty: Ty<'tcx>,
188     ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
189         debug!(
190             "deduce_expectations_from_expected_type(expected_ty={:?})",
191             expected_ty
192         );
193
194         match expected_ty.sty {
195             ty::Dynamic(ref object_type, ..) => {
196                 let sig = object_type
197                     .projection_bounds()
198                     .filter_map(|pb| {
199                         let pb = pb.with_self_ty(self.tcx, self.tcx.types.err);
200                         self.deduce_sig_from_projection(None, &pb)
201                     })
202                     .next();
203                 let kind = self.tcx.lang_items().fn_trait_kind(object_type.principal().def_id());
204                 (sig, kind)
205             }
206             ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
207             ty::FnPtr(sig) => {
208                 let expected_sig = ExpectedSig {
209                     cause_span: None,
210                     sig: sig.skip_binder().clone(),
211                 };
212                 (Some(expected_sig), Some(ty::ClosureKind::Fn))
213             }
214             _ => (None, None),
215         }
216     }
217
218     fn deduce_expectations_from_obligations(
219         &self,
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.
224
225         let expected_sig = fulfillment_cx
226             .pending_obligations()
227             .iter()
228             .filter_map(|obligation| {
229                 debug!(
230                     "deduce_expectations_from_obligations: obligation.predicate={:?}",
231                     obligation.predicate
232                 );
233
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)
239                         .and_then(|_| {
240                             self.deduce_sig_from_projection(
241                                 Some(obligation.cause.span),
242                                 proj_predicate
243                             )
244                         })
245                 } else {
246                     None
247                 }
248             })
249             .next();
250
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()
257             .iter()
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,
268
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,
278                 };
279                 opt_trait_ref
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()))
282             })
283             .fold(None, |best, cur| {
284                 Some(best.map_or(cur, |best| cmp::min(best, cur)))
285             });
286
287         (expected_sig, expected_kind)
288     }
289
290     /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
291     /// everything we need to know about a closure.
292     ///
293     /// The `cause_span` should be the span that caused us to
294     /// have this expected signature, or `None` if we can't readily
295     /// know that.
296     fn deduce_sig_from_projection(
297         &self,
298         cause_span: Option<Span>,
299         projection: &ty::PolyProjectionPredicate<'tcx>,
300     ) -> Option<ExpectedSig<'tcx>> {
301         let tcx = self.tcx;
302
303         debug!("deduce_sig_from_projection({:?})", projection);
304
305         let trait_ref = projection.to_poly_trait_ref(tcx);
306
307         if tcx.lang_items().fn_trait_kind(trait_ref.def_id()).is_none() {
308             return None;
309         }
310
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);
313         debug!(
314             "deduce_sig_from_projection: arg_param_ty {:?}",
315             arg_param_ty
316         );
317
318         let input_tys = match arg_param_ty.sty {
319             ty::Tuple(tys) => tys.into_iter(),
320             _ => return None
321         };
322
323         let ret_param_ty = projection.skip_binder().ty;
324         let ret_param_ty = self.resolve_type_vars_if_possible(&ret_param_ty);
325         debug!(
326             "deduce_sig_from_projection: ret_param_ty {:?}",
327             ret_param_ty
328         );
329
330         let sig = self.tcx.mk_fn_sig(
331             input_tys.cloned(),
332             ret_param_ty,
333             false,
334             hir::Unsafety::Normal,
335             Abi::Rust,
336         );
337         debug!("deduce_sig_from_projection: sig {:?}", sig);
338
339         Some(ExpectedSig { cause_span, sig })
340     }
341
342     fn self_type_matches_expected_vid(
343         &self,
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());
348         debug!(
349             "self_type_matches_expected_vid(trait_ref={:?}, self_ty={:?})",
350             trait_ref, self_ty
351         );
352         match self_ty.sty {
353             ty::Infer(ty::TyVar(v)) if expected_vid == v => Some(trait_ref),
354             _ => None,
355         }
356     }
357
358     fn sig_of_closure(
359         &self,
360         expr_def_id: DefId,
361         decl: &hir::FnDecl,
362         body: &hir::Body,
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)
367         } else {
368             self.sig_of_closure_no_expectation(expr_def_id, decl, body)
369         }
370     }
371
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(
375         &self,
376         expr_def_id: DefId,
377         decl: &hir::FnDecl,
378         body: &hir::Body,
379     ) -> ClosureSignatures<'tcx> {
380         debug!("sig_of_closure_no_expectation()");
381
382         let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl);
383
384         self.closure_sigs(expr_def_id, body, bound_sig)
385     }
386
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.
390     ///
391     /// The approach is as follows:
392     ///
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
403     ///         our purposes.
404     ///
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.
408     ///
409     /// # Examples
410     ///
411     /// ```
412     /// fn with_closure<F>(_: F)
413     ///   where F: Fn(&u32) -> &u32 { .. }
414     ///
415     /// with_closure(|x: &u32| { ... })
416     /// ```
417     ///
418     /// Here:
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`
423     ///
424     /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
425     ///
426     /// # Arguments
427     ///
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(
435         &self,
436         expr_def_id: DefId,
437         decl: &hir::FnDecl,
438         body: &hir::Body,
439         expected_sig: ExpectedSig<'tcx>,
440     ) -> ClosureSignatures<'tcx> {
441         debug!(
442             "sig_of_closure_with_expectation(expected_sig={:?})",
443             expected_sig
444         );
445
446         // Watch out for some surprises and just ignore the
447         // expectation if things don't see to match up with what we
448         // expect.
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(
453                 expr_def_id,
454                 decl,
455                 body,
456                 expected_sig,
457             );
458         }
459
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_vars_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(),
467             decl.variadic,
468             hir::Unsafety::Normal,
469             Abi::RustCall,
470         ));
471
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);
476
477         let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
478
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
483         // check.
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),
487         }
488
489         closure_sigs
490     }
491
492     fn sig_of_closure_with_mismatched_number_of_arguments(
493         &self,
494         expr_def_id: DefId,
495         decl: &hir::FnDecl,
496         body: &hir::Body,
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
501             .sig
502             .inputs()
503             .iter()
504             .map(|ty| ArgKind::from_expected_ty(ty, None))
505             .collect();
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(
509             expected_span,
510             Some(closure_span),
511             expected_args,
512             found_args,
513             true,
514         ).emit();
515
516         let error_sig = self.error_sig_of_closure(decl);
517
518         self.closure_sigs(expr_def_id, body, error_sig)
519     }
520
521     /// Enforce the user's types against the expectation.  See
522     /// `sig_of_closure_with_expectation` for details on the overall
523     /// strategy.
524     fn check_supplied_sig_against_expectation(
525         &self,
526         expr_def_id: DefId,
527         decl: &hir::FnDecl,
528         body: &hir::Body,
529         expected_sigs: &ClosureSignatures<'tcx>,
530     ) -> InferResult<'tcx, ()> {
531         // Get the signature S that the user gave.
532         //
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);
536
537         debug!(
538             "check_supplied_sig_against_expectation: supplied_sig={:?}",
539             supplied_sig
540         );
541
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.
548         //
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
552         // error.
553         //
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![];
558
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'.
565             {
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(
568                     hir_ty.span,
569                     LateBoundRegionConversionTime::FnCall,
570                     &ty::Binder::bind(supplied_ty),
571                 ); // recreated from (*) above
572
573                 // Check that E' = S'.
574                 let cause = &self.misc(hir_ty.span);
575                 let InferOk {
576                     value: (),
577                     obligations,
578                 } = self.at(cause, self.param_env)
579                     .eq(*expected_ty, supplied_ty)?;
580                 all_obligations.extend(obligations);
581
582                 // Also, require that the supplied type must outlive
583                 // the closure body.
584                 let closure_body_region = self.tcx.mk_region(
585                     ty::ReScope(
586                         region::Scope {
587                             id: body.value.hir_id.local_id,
588                             data: region::ScopeData::Node,
589                         },
590                     ),
591                 );
592                 all_obligations.push(
593                     Obligation::new(
594                         cause.clone(),
595                         self.param_env,
596                         ty::Predicate::TypeOutlives(
597                             ty::Binder::dummy(
598                                 ty::OutlivesPredicate(
599                                     supplied_ty,
600                                     closure_body_region,
601                                 ),
602                             ),
603                         ),
604                     ),
605                 );
606             }
607
608             let (supplied_output_ty, _) = self.infcx.replace_late_bound_regions_with_fresh_var(
609                 decl.output.span(),
610                 LateBoundRegionConversionTime::FnCall,
611                 &supplied_sig.output(),
612             );
613             let cause = &self.misc(decl.output.span());
614             let InferOk {
615                 value: (),
616                 obligations,
617             } = self.at(cause, self.param_env)
618                 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
619             all_obligations.extend(obligations);
620
621             Ok(InferOk {
622                 value: (),
623                 obligations: all_obligations,
624             })
625         })
626     }
627
628     /// If there is no expected signature, then we will convert the
629     /// types that the user gave into a signature.
630     ///
631     /// Also, record this closure signature for later.
632     fn supplied_sig_of_closure(
633         &self,
634         expr_def_id: DefId,
635         decl: &hir::FnDecl,
636     ) -> ty::PolyFnSig<'tcx> {
637         let astconv: &dyn AstConv = self;
638
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()),
644         };
645
646         let result = ty::Binder::bind(self.tcx.mk_fn_sig(
647             supplied_arguments,
648             supplied_return,
649             decl.variadic,
650             hir::Unsafety::Normal,
651             Abi::RustCall,
652         ));
653
654         debug!("supplied_sig_of_closure: result={:?}", result);
655
656         let c_result = self.inh.infcx.canonicalize_response(&result);
657         self.tables.borrow_mut().user_provided_sigs.insert(
658             expr_def_id,
659             c_result,
660         );
661
662         result
663     }
664
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;
670
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);
674             self.tcx.types.err
675         });
676
677         if let hir::Return(ref output) = decl.output {
678             astconv.ast_ty_to_ty(&output);
679         }
680
681         let result = ty::Binder::bind(self.tcx.mk_fn_sig(
682             supplied_arguments,
683             self.tcx.types.err,
684             decl.variadic,
685             hir::Unsafety::Normal,
686             Abi::RustCall,
687         ));
688
689         debug!("supplied_sig_of_closure: result={:?}", result);
690
691         result
692     }
693
694     fn closure_sigs(
695         &self,
696         expr_def_id: DefId,
697         body: &hir::Body,
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(
703             body.value.span,
704             body.value.id,
705             self.param_env,
706             &liberated_sig,
707         );
708         ClosureSignatures {
709             bound_sig,
710             liberated_sig,
711         }
712     }
713 }