]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/closure.rs
Rollup merge of #93751 - eholk:issue-93648-drop-tracking-projection, r=tmiasko
[rust.git] / compiler / rustc_typeck / src / 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::rustc_middle::ty::subst::Subst;
7 use hir::OpaqueTyOrigin;
8 use rustc_hir as hir;
9 use rustc_hir::def_id::DefId;
10 use rustc_hir::lang_items::LangItem;
11 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
12 use rustc_infer::infer::LateBoundRegionConversionTime;
13 use rustc_infer::infer::{InferOk, InferResult};
14 use rustc_infer::traits::ObligationCause;
15 use rustc_middle::ty::fold::TypeFoldable;
16 use rustc_middle::ty::subst::InternalSubsts;
17 use rustc_middle::ty::{self, Ty};
18 use rustc_span::source_map::Span;
19 use rustc_span::DUMMY_SP;
20 use rustc_target::spec::abi::Abi;
21 use rustc_trait_selection::traits::error_reporting::ArgKind;
22 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
23 use std::cmp;
24 use std::iter;
25
26 /// What signature do we *expect* the closure to have from context?
27 #[derive(Debug)]
28 struct ExpectedSig<'tcx> {
29     /// Span that gave us this expectation, if we know that.
30     cause_span: Option<Span>,
31     sig: ty::PolyFnSig<'tcx>,
32 }
33
34 struct ClosureSignatures<'tcx> {
35     bound_sig: ty::PolyFnSig<'tcx>,
36     liberated_sig: ty::FnSig<'tcx>,
37 }
38
39 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40     #[instrument(skip(self, expr, _capture, decl, body_id), level = "debug")]
41     pub fn check_expr_closure(
42         &self,
43         expr: &hir::Expr<'_>,
44         _capture: hir::CaptureBy,
45         decl: &'tcx hir::FnDecl<'tcx>,
46         body_id: hir::BodyId,
47         gen: Option<hir::Movability>,
48         expected: Expectation<'tcx>,
49     ) -> Ty<'tcx> {
50         trace!("decl = {:#?}", decl);
51         trace!("expr = {:#?}", expr);
52
53         // It's always helpful for inference if we know the kind of
54         // closure sooner rather than later, so first examine the expected
55         // type, and see if can glean a closure kind from there.
56         let (expected_sig, expected_kind) = match expected.to_option(self) {
57             Some(ty) => self.deduce_expectations_from_expected_type(ty),
58             None => (None, None),
59         };
60         let body = self.tcx.hir().body(body_id);
61         self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
62     }
63
64     #[instrument(skip(self, expr, body, decl), level = "debug")]
65     fn check_closure(
66         &self,
67         expr: &hir::Expr<'_>,
68         opt_kind: Option<ty::ClosureKind>,
69         decl: &'tcx hir::FnDecl<'tcx>,
70         body: &'tcx hir::Body<'tcx>,
71         gen: Option<hir::Movability>,
72         expected_sig: Option<ExpectedSig<'tcx>>,
73     ) -> Ty<'tcx> {
74         trace!("decl = {:#?}", decl);
75         let expr_def_id = self.tcx.hir().local_def_id(expr.hir_id);
76         debug!(?expr_def_id);
77
78         let ClosureSignatures { bound_sig, liberated_sig } =
79             self.sig_of_closure(expr.hir_id, expr_def_id.to_def_id(), decl, body, expected_sig);
80
81         debug!(?bound_sig, ?liberated_sig);
82
83         let return_type_pre_known = !liberated_sig.output().is_ty_infer();
84
85         let generator_types = check_fn(
86             self,
87             self.param_env.without_const(),
88             liberated_sig,
89             decl,
90             expr.hir_id,
91             body,
92             gen,
93             return_type_pre_known,
94         )
95         .1;
96
97         let parent_substs = InternalSubsts::identity_for_item(
98             self.tcx,
99             self.tcx.typeck_root_def_id(expr_def_id.to_def_id()),
100         );
101
102         let tupled_upvars_ty = self.infcx.next_ty_var(TypeVariableOrigin {
103             kind: TypeVariableOriginKind::ClosureSynthetic,
104             span: self.tcx.hir().span(expr.hir_id),
105         });
106
107         if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types
108         {
109             let generator_substs = ty::GeneratorSubsts::new(
110                 self.tcx,
111                 ty::GeneratorSubstsParts {
112                     parent_substs,
113                     resume_ty,
114                     yield_ty,
115                     return_ty: liberated_sig.output(),
116                     witness: interior,
117                     tupled_upvars_ty,
118                 },
119             );
120
121             return self.tcx.mk_generator(
122                 expr_def_id.to_def_id(),
123                 generator_substs.substs,
124                 movability,
125             );
126         }
127
128         // Tuple up the arguments and insert the resulting function type into
129         // the `closures` table.
130         let sig = bound_sig.map_bound(|sig| {
131             self.tcx.mk_fn_sig(
132                 iter::once(self.tcx.intern_tup(sig.inputs())),
133                 sig.output(),
134                 sig.c_variadic,
135                 sig.unsafety,
136                 sig.abi,
137             )
138         });
139
140         debug!(?sig, ?opt_kind);
141
142         let closure_kind_ty = match opt_kind {
143             Some(kind) => kind.to_ty(self.tcx),
144
145             // Create a type variable (for now) to represent the closure kind.
146             // It will be unified during the upvar inference phase (`upvar.rs`)
147             None => self.infcx.next_ty_var(TypeVariableOrigin {
148                 // FIXME(eddyb) distinguish closure kind inference variables from the rest.
149                 kind: TypeVariableOriginKind::ClosureSynthetic,
150                 span: expr.span,
151             }),
152         };
153
154         let closure_substs = ty::ClosureSubsts::new(
155             self.tcx,
156             ty::ClosureSubstsParts {
157                 parent_substs,
158                 closure_kind_ty,
159                 closure_sig_as_fn_ptr_ty: self.tcx.mk_fn_ptr(sig),
160                 tupled_upvars_ty,
161             },
162         );
163
164         let closure_type = self.tcx.mk_closure(expr_def_id.to_def_id(), closure_substs.substs);
165
166         debug!(?expr.hir_id, ?closure_type);
167
168         closure_type
169     }
170
171     /// Given the expected type, figures out what it can about this closure we
172     /// are about to type check:
173     #[instrument(skip(self), level = "debug")]
174     fn deduce_expectations_from_expected_type(
175         &self,
176         expected_ty: Ty<'tcx>,
177     ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
178         match *expected_ty.kind() {
179             ty::Opaque(def_id, substs) => {
180                 let bounds = self.tcx.explicit_item_bounds(def_id);
181                 let sig = bounds.iter().find_map(|(pred, span)| match pred.kind().skip_binder() {
182                     ty::PredicateKind::Projection(proj_predicate) => self
183                         .deduce_sig_from_projection(
184                             Some(*span),
185                             pred.kind().rebind(proj_predicate.subst(self.tcx, substs)),
186                         ),
187                     _ => None,
188                 });
189
190                 let kind = bounds
191                     .iter()
192                     .filter_map(|(pred, _)| match pred.kind().skip_binder() {
193                         ty::PredicateKind::Trait(tp) => {
194                             self.tcx.fn_trait_kind_from_lang_item(tp.def_id())
195                         }
196                         _ => None,
197                     })
198                     .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
199                 trace!(?sig, ?kind);
200                 (sig, kind)
201             }
202             ty::Dynamic(ref object_type, ..) => {
203                 let sig = object_type.projection_bounds().find_map(|pb| {
204                     let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
205                     self.deduce_sig_from_projection(None, pb)
206                 });
207                 let kind = object_type
208                     .principal_def_id()
209                     .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did));
210                 (sig, kind)
211             }
212             ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
213             ty::FnPtr(sig) => {
214                 let expected_sig = ExpectedSig { cause_span: None, sig };
215                 (Some(expected_sig), Some(ty::ClosureKind::Fn))
216             }
217             _ => (None, None),
218         }
219     }
220
221     fn deduce_expectations_from_obligations(
222         &self,
223         expected_vid: ty::TyVid,
224     ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
225         let expected_sig =
226             self.obligations_for_self_ty(expected_vid).find_map(|(_, obligation)| {
227                 debug!(?obligation.predicate);
228
229                 let bound_predicate = obligation.predicate.kind();
230                 if let ty::PredicateKind::Projection(proj_predicate) =
231                     obligation.predicate.kind().skip_binder()
232                 {
233                     // Given a Projection predicate, we can potentially infer
234                     // the complete signature.
235                     self.deduce_sig_from_projection(
236                         Some(obligation.cause.span),
237                         bound_predicate.rebind(proj_predicate),
238                     )
239                 } else {
240                     None
241                 }
242             });
243
244         // Even if we can't infer the full signature, we may be able to
245         // infer the kind. This can occur when we elaborate a predicate
246         // like `F : Fn<A>`. Note that due to subtyping we could encounter
247         // many viable options, so pick the most restrictive.
248         let expected_kind = self
249             .obligations_for_self_ty(expected_vid)
250             .filter_map(|(tr, _)| self.tcx.fn_trait_kind_from_lang_item(tr.def_id()))
251             .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
252
253         (expected_sig, expected_kind)
254     }
255
256     /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
257     /// everything we need to know about a closure or generator.
258     ///
259     /// The `cause_span` should be the span that caused us to
260     /// have this expected signature, or `None` if we can't readily
261     /// know that.
262     #[instrument(level = "debug", skip(self, cause_span))]
263     fn deduce_sig_from_projection(
264         &self,
265         cause_span: Option<Span>,
266         projection: ty::PolyProjectionPredicate<'tcx>,
267     ) -> Option<ExpectedSig<'tcx>> {
268         let tcx = self.tcx;
269
270         let trait_def_id = projection.trait_def_id(tcx);
271
272         let is_fn = tcx.fn_trait_kind_from_lang_item(trait_def_id).is_some();
273         let gen_trait = tcx.require_lang_item(LangItem::Generator, cause_span);
274         let is_gen = gen_trait == trait_def_id;
275         if !is_fn && !is_gen {
276             debug!("not fn or generator");
277             return None;
278         }
279
280         if is_gen {
281             // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
282             // associated item and not yield.
283             let return_assoc_item = self.tcx.associated_item_def_ids(gen_trait)[1];
284             if return_assoc_item != projection.projection_def_id() {
285                 debug!("not return assoc item of generator");
286                 return None;
287             }
288         }
289
290         let input_tys = if is_fn {
291             let arg_param_ty = projection.skip_binder().projection_ty.substs.type_at(1);
292             let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty);
293             debug!(?arg_param_ty);
294
295             match arg_param_ty.kind() {
296                 ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(),
297                 _ => return None,
298             }
299         } else {
300             // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
301             // else they must have exactly 1 argument. For now though, just give up in this case.
302             return None;
303         };
304
305         // Since this is a return parameter type it is safe to unwrap.
306         let ret_param_ty = projection.skip_binder().term.ty().unwrap();
307         let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty);
308         debug!(?ret_param_ty);
309
310         let sig = projection.rebind(self.tcx.mk_fn_sig(
311             input_tys.iter(),
312             &ret_param_ty,
313             false,
314             hir::Unsafety::Normal,
315             Abi::Rust,
316         ));
317         debug!(?sig);
318
319         Some(ExpectedSig { cause_span, sig })
320     }
321
322     fn sig_of_closure(
323         &self,
324         hir_id: hir::HirId,
325         expr_def_id: DefId,
326         decl: &hir::FnDecl<'_>,
327         body: &hir::Body<'_>,
328         expected_sig: Option<ExpectedSig<'tcx>>,
329     ) -> ClosureSignatures<'tcx> {
330         if let Some(e) = expected_sig {
331             self.sig_of_closure_with_expectation(hir_id, expr_def_id, decl, body, e)
332         } else {
333             self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body)
334         }
335     }
336
337     /// If there is no expected signature, then we will convert the
338     /// types that the user gave into a signature.
339     #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")]
340     fn sig_of_closure_no_expectation(
341         &self,
342         hir_id: hir::HirId,
343         expr_def_id: DefId,
344         decl: &hir::FnDecl<'_>,
345         body: &hir::Body<'_>,
346     ) -> ClosureSignatures<'tcx> {
347         let bound_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
348
349         self.closure_sigs(expr_def_id, body, bound_sig)
350     }
351
352     /// Invoked to compute the signature of a closure expression. This
353     /// combines any user-provided type annotations (e.g., `|x: u32|
354     /// -> u32 { .. }`) with the expected signature.
355     ///
356     /// The approach is as follows:
357     ///
358     /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
359     /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
360     ///   - If we have no expectation `E`, then the signature of the closure is `S`.
361     ///   - Otherwise, the signature of the closure is E. Moreover:
362     ///     - Skolemize the late-bound regions in `E`, yielding `E'`.
363     ///     - Instantiate all the late-bound regions bound in the closure within `S`
364     ///       with fresh (existential) variables, yielding `S'`
365     ///     - Require that `E' = S'`
366     ///       - We could use some kind of subtyping relationship here,
367     ///         I imagine, but equality is easier and works fine for
368     ///         our purposes.
369     ///
370     /// The key intuition here is that the user's types must be valid
371     /// from "the inside" of the closure, but the expectation
372     /// ultimately drives the overall signature.
373     ///
374     /// # Examples
375     ///
376     /// ```
377     /// fn with_closure<F>(_: F)
378     ///   where F: Fn(&u32) -> &u32 { .. }
379     ///
380     /// with_closure(|x: &u32| { ... })
381     /// ```
382     ///
383     /// Here:
384     /// - E would be `fn(&u32) -> &u32`.
385     /// - S would be `fn(&u32) ->
386     /// - E' is `&'!0 u32 -> &'!0 u32`
387     /// - S' is `&'?0 u32 -> ?T`
388     ///
389     /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
390     ///
391     /// # Arguments
392     ///
393     /// - `expr_def_id`: the `DefId` of the closure expression
394     /// - `decl`: the HIR declaration of the closure
395     /// - `body`: the body of the closure
396     /// - `expected_sig`: the expected signature (if any). Note that
397     ///   this is missing a binder: that is, there may be late-bound
398     ///   regions with depth 1, which are bound then by the closure.
399     #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")]
400     fn sig_of_closure_with_expectation(
401         &self,
402         hir_id: hir::HirId,
403         expr_def_id: DefId,
404         decl: &hir::FnDecl<'_>,
405         body: &hir::Body<'_>,
406         expected_sig: ExpectedSig<'tcx>,
407     ) -> ClosureSignatures<'tcx> {
408         // Watch out for some surprises and just ignore the
409         // expectation if things don't see to match up with what we
410         // expect.
411         if expected_sig.sig.c_variadic() != decl.c_variadic {
412             return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body);
413         } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 {
414             return self.sig_of_closure_with_mismatched_number_of_arguments(
415                 expr_def_id,
416                 decl,
417                 body,
418                 expected_sig,
419             );
420         }
421
422         // Create a `PolyFnSig`. Note the oddity that late bound
423         // regions appearing free in `expected_sig` are now bound up
424         // in this binder we are creating.
425         assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST));
426         let bound_sig = expected_sig.sig.map_bound(|sig| {
427             let output = self.hide_parent_opaque_types(
428                 sig.output(),
429                 expected_sig.cause_span.unwrap_or(DUMMY_SP),
430                 body.id().hir_id,
431             );
432             self.tcx.mk_fn_sig(
433                 sig.inputs().iter().cloned(),
434                 output,
435                 sig.c_variadic,
436                 hir::Unsafety::Normal,
437                 Abi::RustCall,
438             )
439         });
440
441         // `deduce_expectations_from_expected_type` introduces
442         // late-bound lifetimes defined elsewhere, which we now
443         // anonymize away, so as not to confuse the user.
444         let bound_sig = self.tcx.anonymize_late_bound_regions(bound_sig);
445
446         let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
447
448         // Up till this point, we have ignored the annotations that the user
449         // gave. This function will check that they unify successfully.
450         // Along the way, it also writes out entries for types that the user
451         // wrote into our typeck results, which are then later used by the privacy
452         // check.
453         match self.check_supplied_sig_against_expectation(
454             hir_id,
455             expr_def_id,
456             decl,
457             body,
458             &closure_sigs,
459         ) {
460             Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
461             Err(_) => return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body),
462         }
463
464         closure_sigs
465     }
466
467     fn sig_of_closure_with_mismatched_number_of_arguments(
468         &self,
469         expr_def_id: DefId,
470         decl: &hir::FnDecl<'_>,
471         body: &hir::Body<'_>,
472         expected_sig: ExpectedSig<'tcx>,
473     ) -> ClosureSignatures<'tcx> {
474         let hir = self.tcx.hir();
475         let expr_map_node = hir.get_if_local(expr_def_id).unwrap();
476         let expected_args: Vec<_> = expected_sig
477             .sig
478             .skip_binder()
479             .inputs()
480             .iter()
481             .map(|ty| ArgKind::from_expected_ty(ty, None))
482             .collect();
483         let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) {
484             Some((sp, args)) => (Some(sp), args),
485             None => (None, Vec::new()),
486         };
487         let expected_span =
488             expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap());
489         self.report_arg_count_mismatch(
490             expected_span,
491             closure_span,
492             expected_args,
493             found_args,
494             true,
495         )
496         .emit();
497
498         let error_sig = self.error_sig_of_closure(decl);
499
500         self.closure_sigs(expr_def_id, body, error_sig)
501     }
502
503     /// Enforce the user's types against the expectation. See
504     /// `sig_of_closure_with_expectation` for details on the overall
505     /// strategy.
506     fn check_supplied_sig_against_expectation(
507         &self,
508         hir_id: hir::HirId,
509         expr_def_id: DefId,
510         decl: &hir::FnDecl<'_>,
511         body: &hir::Body<'_>,
512         expected_sigs: &ClosureSignatures<'tcx>,
513     ) -> InferResult<'tcx, ()> {
514         // Get the signature S that the user gave.
515         //
516         // (See comment on `sig_of_closure_with_expectation` for the
517         // meaning of these letters.)
518         let supplied_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
519
520         debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig);
521
522         // FIXME(#45727): As discussed in [this comment][c1], naively
523         // forcing equality here actually results in suboptimal error
524         // messages in some cases.  For now, if there would have been
525         // an obvious error, we fallback to declaring the type of the
526         // closure to be the one the user gave, which allows other
527         // error message code to trigger.
528         //
529         // However, I think [there is potential to do even better
530         // here][c2], since in *this* code we have the precise span of
531         // the type parameter in question in hand when we report the
532         // error.
533         //
534         // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
535         // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
536         self.infcx.commit_if_ok(|_| {
537             let mut all_obligations = vec![];
538
539             // The liberated version of this signature should be a subtype
540             // of the liberated form of the expectation.
541             for ((hir_ty, &supplied_ty), expected_ty) in iter::zip(
542                 iter::zip(
543                     decl.inputs,
544                     supplied_sig.inputs().skip_binder(), // binder moved to (*) below
545                 ),
546                 expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'.
547             ) {
548                 // Instantiate (this part of..) S to S', i.e., with fresh variables.
549                 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
550                     hir_ty.span,
551                     LateBoundRegionConversionTime::FnCall,
552                     supplied_sig.inputs().rebind(supplied_ty),
553                 ); // recreated from (*) above
554
555                 // Check that E' = S'.
556                 let cause = self.misc(hir_ty.span);
557                 let InferOk { value: (), obligations } =
558                     self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
559                 all_obligations.extend(obligations);
560             }
561
562             let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
563                 decl.output.span(),
564                 LateBoundRegionConversionTime::FnCall,
565                 supplied_sig.output(),
566             );
567             let cause = &self.misc(decl.output.span());
568             let InferOk { value: (), obligations } = self
569                 .at(cause, self.param_env)
570                 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
571             all_obligations.extend(obligations);
572
573             Ok(InferOk { value: (), obligations: all_obligations })
574         })
575     }
576
577     /// If there is no expected signature, then we will convert the
578     /// types that the user gave into a signature.
579     ///
580     /// Also, record this closure signature for later.
581     #[instrument(skip(self, decl, body), level = "debug")]
582     fn supplied_sig_of_closure(
583         &self,
584         hir_id: hir::HirId,
585         expr_def_id: DefId,
586         decl: &hir::FnDecl<'_>,
587         body: &hir::Body<'_>,
588     ) -> ty::PolyFnSig<'tcx> {
589         let astconv: &dyn AstConv<'_> = self;
590
591         trace!("decl = {:#?}", decl);
592         debug!(?body.generator_kind);
593
594         let bound_vars = self.tcx.late_bound_vars(hir_id);
595
596         // First, convert the types that the user supplied (if any).
597         let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
598         let supplied_return = match decl.output {
599             hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
600             hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
601                 // In the case of the async block that we create for a function body,
602                 // we expect the return type of the block to match that of the enclosing
603                 // function.
604                 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
605                     debug!("closure is async fn body");
606                     self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| {
607                         // AFAIK, deducing the future output
608                         // always succeeds *except* in error cases
609                         // like #65159. I'd like to return Error
610                         // here, but I can't because I can't
611                         // easily (and locally) prove that we
612                         // *have* reported an
613                         // error. --nikomatsakis
614                         astconv.ty_infer(None, decl.output.span())
615                     })
616                 }
617
618                 _ => astconv.ty_infer(None, decl.output.span()),
619             },
620         };
621         let supplied_return =
622             self.hide_parent_opaque_types(supplied_return, decl.output.span(), body.id().hir_id);
623
624         let result = ty::Binder::bind_with_vars(
625             self.tcx.mk_fn_sig(
626                 supplied_arguments,
627                 supplied_return,
628                 decl.c_variadic,
629                 hir::Unsafety::Normal,
630                 Abi::RustCall,
631             ),
632             bound_vars,
633         );
634
635         debug!(?result);
636
637         let c_result = self.inh.infcx.canonicalize_response(result);
638         self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
639
640         result
641     }
642
643     fn hide_parent_opaque_types(&self, ty: Ty<'tcx>, span: Span, body_id: hir::HirId) -> Ty<'tcx> {
644         ty.fold_with(&mut ty::fold::BottomUpFolder {
645             tcx: self.infcx.tcx,
646             lt_op: |lt| lt,
647             ct_op: |ct| ct,
648             ty_op: |ty| match *ty.kind() {
649                 // Closures can't create hidden types for opaque types of their parent, as they
650                 // do not have all the outlives information available. Also `type_of` looks for
651                 // hidden types in the owner (so the closure's parent), so it would not find these
652                 // definitions.
653                 ty::Opaque(def_id, _substs)
654                     if matches!(
655                         self.infcx.opaque_type_origin(def_id, DUMMY_SP),
656                         Some(OpaqueTyOrigin::FnReturn(..))
657                     ) =>
658                 {
659                     let ty_var = self.next_ty_var(TypeVariableOrigin {
660                         kind: TypeVariableOriginKind::TypeInference,
661                         span,
662                     });
663                     let cause = ObligationCause::misc(span, body_id);
664                     self.register_predicates(vec![self.infcx.opaque_ty_obligation(
665                         ty,
666                         ty_var,
667                         true,
668                         self.param_env,
669                         cause,
670                     )]);
671                     ty_var
672                 }
673                 _ => ty,
674             },
675         })
676     }
677
678     /// Invoked when we are translating the generator that results
679     /// from desugaring an `async fn`. Returns the "sugared" return
680     /// type of the `async fn` -- that is, the return type that the
681     /// user specified. The "desugared" return type is an `impl
682     /// Future<Output = T>`, so we do this by searching through the
683     /// obligations to extract the `T`.
684     #[instrument(skip(self), level = "debug")]
685     fn deduce_future_output_from_obligations(&self, expr_def_id: DefId) -> Option<Ty<'tcx>> {
686         let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
687             span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
688         });
689
690         let ret_ty = ret_coercion.borrow().expected_ty();
691         let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
692         let (def_id, substs) = match *ret_ty.kind() {
693             ty::Opaque(def_id, substs) => (def_id, substs),
694             ty::Error(_) => return None,
695             _ => span_bug!(
696                 self.tcx.def_span(expr_def_id),
697                 "async fn generator return type not an inference variable"
698             ),
699         };
700
701         let item_bounds = self.tcx.explicit_item_bounds(def_id);
702
703         // Search for a pending obligation like
704         //
705         // `<R as Future>::Output = T`
706         //
707         // where R is the return type we are expecting. This type `T`
708         // will be our output.
709         let output_ty = item_bounds.iter().find_map(|&(predicate, span)| {
710             let bound_predicate = predicate.subst(self.tcx, substs).kind();
711             if let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder() {
712                 self.deduce_future_output_from_projection(
713                     span,
714                     bound_predicate.rebind(proj_predicate),
715                 )
716             } else {
717                 None
718             }
719         });
720
721         debug!("deduce_future_output_from_obligations: output_ty={:?}", output_ty);
722         output_ty
723     }
724
725     /// Given a projection like
726     ///
727     /// `<X as Future>::Output = T`
728     ///
729     /// where `X` is some type that has no late-bound regions, returns
730     /// `Some(T)`. If the projection is for some other trait, returns
731     /// `None`.
732     fn deduce_future_output_from_projection(
733         &self,
734         cause_span: Span,
735         predicate: ty::PolyProjectionPredicate<'tcx>,
736     ) -> Option<Ty<'tcx>> {
737         debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
738
739         // We do not expect any bound regions in our predicate, so
740         // skip past the bound vars.
741         let predicate = match predicate.no_bound_vars() {
742             Some(p) => p,
743             None => {
744                 debug!("deduce_future_output_from_projection: has late-bound regions");
745                 return None;
746             }
747         };
748
749         // Check that this is a projection from the `Future` trait.
750         let trait_def_id = predicate.projection_ty.trait_def_id(self.tcx);
751         let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span));
752         if trait_def_id != future_trait {
753             debug!("deduce_future_output_from_projection: not a future");
754             return None;
755         }
756
757         // The `Future` trait has only one associted item, `Output`,
758         // so check that this is what we see.
759         let output_assoc_item = self.tcx.associated_item_def_ids(future_trait)[0];
760         if output_assoc_item != predicate.projection_ty.item_def_id {
761             span_bug!(
762                 cause_span,
763                 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
764                 predicate.projection_ty.item_def_id,
765                 output_assoc_item,
766             );
767         }
768
769         // Extract the type from the projection. Note that there can
770         // be no bound variables in this type because the "self type"
771         // does not have any regions in it.
772         let output_ty = self.resolve_vars_if_possible(predicate.term);
773         debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
774         // This is a projection on a Fn trait so will always be a type.
775         Some(output_ty.ty().unwrap())
776     }
777
778     /// Converts the types that the user supplied, in case that doing
779     /// so should yield an error, but returns back a signature where
780     /// all parameters are of type `TyErr`.
781     fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
782         let astconv: &dyn AstConv<'_> = self;
783
784         let supplied_arguments = decl.inputs.iter().map(|a| {
785             // Convert the types that the user supplied (if any), but ignore them.
786             astconv.ast_ty_to_ty(a);
787             self.tcx.ty_error()
788         });
789
790         if let hir::FnRetTy::Return(ref output) = decl.output {
791             astconv.ast_ty_to_ty(&output);
792         }
793
794         let result = ty::Binder::dummy(self.tcx.mk_fn_sig(
795             supplied_arguments,
796             self.tcx.ty_error(),
797             decl.c_variadic,
798             hir::Unsafety::Normal,
799             Abi::RustCall,
800         ));
801
802         debug!("supplied_sig_of_closure: result={:?}", result);
803
804         result
805     }
806
807     fn closure_sigs(
808         &self,
809         expr_def_id: DefId,
810         body: &hir::Body<'_>,
811         bound_sig: ty::PolyFnSig<'tcx>,
812     ) -> ClosureSignatures<'tcx> {
813         let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, bound_sig);
814         let liberated_sig = self.inh.normalize_associated_types_in(
815             body.value.span,
816             body.value.hir_id,
817             self.param_env,
818             liberated_sig,
819         );
820         ClosureSignatures { bound_sig, liberated_sig }
821     }
822 }