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