rustc_hir_typeck/closure.rs
1//! Code for type-checking closure expressions.
2
3use std::iter;
4use std::ops::ControlFlow;
5
6use rustc_abi::ExternAbi;
7use rustc_errors::ErrorGuaranteed;
8use rustc_hir as hir;
9use rustc_hir::lang_items::LangItem;
10use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
11use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk, InferResult};
12use rustc_infer::traits::{ObligationCauseCode, PredicateObligations};
13use rustc_macros::{TypeFoldable, TypeVisitable};
14use rustc_middle::span_bug;
15use rustc_middle::ty::{
16 self, ClosureKind, GenericArgs, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
17 TypeVisitableExt, TypeVisitor,
18};
19use rustc_span::def_id::LocalDefId;
20use rustc_span::{DUMMY_SP, Span};
21use rustc_trait_selection::error_reporting::traits::ArgKind;
22use rustc_trait_selection::traits;
23use tracing::{debug, instrument, trace};
24
25use super::{CoroutineTypes, Expectation, FnCtxt, check_fn};
26
27/// What signature do we *expect* the closure to have from context?
28#[derive(Debug, Clone, TypeFoldable, TypeVisitable)]
29struct ExpectedSig<'tcx> {
30 /// Span that gave us this expectation, if we know that.
31 cause_span: Option<Span>,
32 sig: ty::PolyFnSig<'tcx>,
33}
34
35#[derive(Debug)]
36struct ClosureSignatures<'tcx> {
37 /// The signature users of the closure see.
38 bound_sig: ty::PolyFnSig<'tcx>,
39 /// The signature within the function body.
40 /// This mostly differs in the sense that lifetimes are now early bound and any
41 /// opaque types from the signature expectation are overridden in case there are
42 /// explicit hidden types written by the user in the closure signature.
43 liberated_sig: ty::FnSig<'tcx>,
44}
45
46impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
47 #[instrument(skip(self, closure), level = "debug")]
48 pub(crate) fn check_expr_closure(
49 &self,
50 closure: &hir::Closure<'tcx>,
51 expr_span: Span,
52 expected: Expectation<'tcx>,
53 ) -> Ty<'tcx> {
54 let tcx = self.tcx;
55 let body = tcx.hir_body(closure.body);
56 let expr_def_id = closure.def_id;
57
58 // It's always helpful for inference if we know the kind of
59 // closure sooner rather than later, so first examine the expected
60 // type, and see if can glean a closure kind from there.
61 let (expected_sig, expected_kind) = match expected.to_option(self) {
62 Some(ty) => self.deduce_closure_signature(
63 self.try_structurally_resolve_type(expr_span, ty),
64 closure.kind,
65 ),
66 None => (None, None),
67 };
68
69 let ClosureSignatures { bound_sig, mut liberated_sig } =
70 self.sig_of_closure(expr_def_id, closure.fn_decl, closure.kind, expected_sig);
71
72 debug!(?bound_sig, ?liberated_sig);
73
74 let parent_args =
75 GenericArgs::identity_for_item(tcx, tcx.typeck_root_def_id(expr_def_id.to_def_id()));
76
77 let tupled_upvars_ty = self.next_ty_var(expr_span);
78
79 // FIXME: We could probably actually just unify this further --
80 // instead of having a `FnSig` and a `Option<CoroutineTypes>`,
81 // we can have a `ClosureSignature { Coroutine { .. }, Closure { .. } }`,
82 // similar to how `ty::GenSig` is a distinct data structure.
83 let (closure_ty, coroutine_types) = match closure.kind {
84 hir::ClosureKind::Closure => {
85 // Tuple up the arguments and insert the resulting function type into
86 // the `closures` table.
87 let sig = bound_sig.map_bound(|sig| {
88 tcx.mk_fn_sig(
89 [Ty::new_tup(tcx, sig.inputs())],
90 sig.output(),
91 sig.c_variadic,
92 sig.safety,
93 sig.abi,
94 )
95 });
96
97 debug!(?sig, ?expected_kind);
98
99 let closure_kind_ty = match expected_kind {
100 Some(kind) => Ty::from_closure_kind(tcx, kind),
101
102 // Create a type variable (for now) to represent the closure kind.
103 // It will be unified during the upvar inference phase (`upvar.rs`)
104 None => self.next_ty_var(expr_span),
105 };
106
107 let closure_args = ty::ClosureArgs::new(
108 tcx,
109 ty::ClosureArgsParts {
110 parent_args,
111 closure_kind_ty,
112 closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(tcx, sig),
113 tupled_upvars_ty,
114 },
115 );
116
117 (Ty::new_closure(tcx, expr_def_id.to_def_id(), closure_args.args), None)
118 }
119 hir::ClosureKind::Coroutine(kind) => {
120 let yield_ty = match kind {
121 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
122 | hir::CoroutineKind::Coroutine(_) => {
123 let yield_ty = self.next_ty_var(expr_span);
124 self.require_type_is_sized(
125 yield_ty,
126 expr_span,
127 ObligationCauseCode::SizedYieldType,
128 );
129 yield_ty
130 }
131 // HACK(-Ztrait-solver=next): In the *old* trait solver, we must eagerly
132 // guide inference on the yield type so that we can handle `AsyncIterator`
133 // in this block in projection correctly. In the new trait solver, it is
134 // not a problem.
135 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _) => {
136 let yield_ty = self.next_ty_var(expr_span);
137 self.require_type_is_sized(
138 yield_ty,
139 expr_span,
140 ObligationCauseCode::SizedYieldType,
141 );
142
143 Ty::new_adt(
144 tcx,
145 tcx.adt_def(
146 tcx.require_lang_item(hir::LangItem::Poll, Some(expr_span)),
147 ),
148 tcx.mk_args(&[Ty::new_adt(
149 tcx,
150 tcx.adt_def(
151 tcx.require_lang_item(hir::LangItem::Option, Some(expr_span)),
152 ),
153 tcx.mk_args(&[yield_ty.into()]),
154 )
155 .into()]),
156 )
157 }
158 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _) => {
159 tcx.types.unit
160 }
161 };
162
163 // Resume type defaults to `()` if the coroutine has no argument.
164 let resume_ty = liberated_sig.inputs().get(0).copied().unwrap_or(tcx.types.unit);
165
166 let interior = self.next_ty_var(expr_span);
167 self.deferred_coroutine_interiors.borrow_mut().push((expr_def_id, interior));
168
169 // Coroutines that come from coroutine closures have not yet determined
170 // their kind ty, so make a fresh infer var which will be constrained
171 // later during upvar analysis. Regular coroutines always have the kind
172 // ty of `().`
173 let kind_ty = match kind {
174 hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) => {
175 self.next_ty_var(expr_span)
176 }
177 _ => tcx.types.unit,
178 };
179
180 let coroutine_args = ty::CoroutineArgs::new(
181 tcx,
182 ty::CoroutineArgsParts {
183 parent_args,
184 kind_ty,
185 resume_ty,
186 yield_ty,
187 return_ty: liberated_sig.output(),
188 witness: interior,
189 tupled_upvars_ty,
190 },
191 );
192
193 (
194 Ty::new_coroutine(tcx, expr_def_id.to_def_id(), coroutine_args.args),
195 Some(CoroutineTypes { resume_ty, yield_ty }),
196 )
197 }
198 hir::ClosureKind::CoroutineClosure(kind) => {
199 // async closures always return the type ascribed after the `->` (if present),
200 // and yield `()`.
201 let (bound_return_ty, bound_yield_ty) = match kind {
202 hir::CoroutineDesugaring::Async => {
203 (bound_sig.skip_binder().output(), tcx.types.unit)
204 }
205 hir::CoroutineDesugaring::Gen | hir::CoroutineDesugaring::AsyncGen => {
206 todo!("`gen` and `async gen` closures not supported yet")
207 }
208 };
209 // Compute all of the variables that will be used to populate the coroutine.
210 let resume_ty = self.next_ty_var(expr_span);
211 let interior = self.next_ty_var(expr_span);
212
213 let closure_kind_ty = match expected_kind {
214 Some(kind) => Ty::from_closure_kind(tcx, kind),
215
216 // Create a type variable (for now) to represent the closure kind.
217 // It will be unified during the upvar inference phase (`upvar.rs`)
218 None => self.next_ty_var(expr_span),
219 };
220
221 let coroutine_captures_by_ref_ty = self.next_ty_var(expr_span);
222 let closure_args = ty::CoroutineClosureArgs::new(
223 tcx,
224 ty::CoroutineClosureArgsParts {
225 parent_args,
226 closure_kind_ty,
227 signature_parts_ty: Ty::new_fn_ptr(
228 tcx,
229 bound_sig.map_bound(|sig| {
230 tcx.mk_fn_sig(
231 [
232 resume_ty,
233 Ty::new_tup_from_iter(tcx, sig.inputs().iter().copied()),
234 ],
235 Ty::new_tup(tcx, &[bound_yield_ty, bound_return_ty]),
236 sig.c_variadic,
237 sig.safety,
238 sig.abi,
239 )
240 }),
241 ),
242 tupled_upvars_ty,
243 coroutine_captures_by_ref_ty,
244 coroutine_witness_ty: interior,
245 },
246 );
247
248 let coroutine_kind_ty = match expected_kind {
249 Some(kind) => Ty::from_coroutine_closure_kind(tcx, kind),
250
251 // Create a type variable (for now) to represent the closure kind.
252 // It will be unified during the upvar inference phase (`upvar.rs`)
253 None => self.next_ty_var(expr_span),
254 };
255
256 let coroutine_upvars_ty = self.next_ty_var(expr_span);
257
258 // We need to turn the liberated signature that we got from HIR, which
259 // looks something like `|Args...| -> T`, into a signature that is suitable
260 // for type checking the inner body of the closure, which always returns a
261 // coroutine. To do so, we use the `CoroutineClosureSignature` to compute
262 // the coroutine type, filling in the tupled_upvars_ty and kind_ty with infer
263 // vars which will get constrained during upvar analysis.
264 let coroutine_output_ty = tcx.liberate_late_bound_regions(
265 expr_def_id.to_def_id(),
266 closure_args.coroutine_closure_sig().map_bound(|sig| {
267 sig.to_coroutine(
268 tcx,
269 parent_args,
270 coroutine_kind_ty,
271 tcx.coroutine_for_closure(expr_def_id),
272 coroutine_upvars_ty,
273 )
274 }),
275 );
276 liberated_sig = tcx.mk_fn_sig(
277 liberated_sig.inputs().iter().copied(),
278 coroutine_output_ty,
279 liberated_sig.c_variadic,
280 liberated_sig.safety,
281 liberated_sig.abi,
282 );
283
284 (Ty::new_coroutine_closure(tcx, expr_def_id.to_def_id(), closure_args.args), None)
285 }
286 };
287
288 check_fn(
289 &mut FnCtxt::new(self, self.param_env, closure.def_id),
290 liberated_sig,
291 coroutine_types,
292 closure.fn_decl,
293 expr_def_id,
294 body,
295 // Closure "rust-call" ABI doesn't support unsized params
296 false,
297 );
298
299 closure_ty
300 }
301
302 /// Given the expected type, figures out what it can about this closure we
303 /// are about to type check:
304 #[instrument(skip(self), level = "debug", ret)]
305 fn deduce_closure_signature(
306 &self,
307 expected_ty: Ty<'tcx>,
308 closure_kind: hir::ClosureKind,
309 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
310 match *expected_ty.kind() {
311 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => self
312 .deduce_closure_signature_from_predicates(
313 expected_ty,
314 closure_kind,
315 self.tcx
316 .explicit_item_self_bounds(def_id)
317 .iter_instantiated_copied(self.tcx, args)
318 .map(|(c, s)| (c.as_predicate(), s)),
319 ),
320 ty::Dynamic(object_type, ..) => {
321 let sig = object_type.projection_bounds().find_map(|pb| {
322 let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
323 self.deduce_sig_from_projection(None, closure_kind, pb)
324 });
325 let kind = object_type
326 .principal_def_id()
327 .and_then(|did| self.tcx.fn_trait_kind_from_def_id(did));
328 (sig, kind)
329 }
330 ty::Infer(ty::TyVar(vid)) => self.deduce_closure_signature_from_predicates(
331 Ty::new_var(self.tcx, self.root_var(vid)),
332 closure_kind,
333 self.obligations_for_self_ty(vid)
334 .into_iter()
335 .map(|obl| (obl.predicate, obl.cause.span)),
336 ),
337 ty::FnPtr(sig_tys, hdr) => match closure_kind {
338 hir::ClosureKind::Closure => {
339 let expected_sig = ExpectedSig { cause_span: None, sig: sig_tys.with(hdr) };
340 (Some(expected_sig), Some(ty::ClosureKind::Fn))
341 }
342 hir::ClosureKind::Coroutine(_) | hir::ClosureKind::CoroutineClosure(_) => {
343 (None, None)
344 }
345 },
346 _ => (None, None),
347 }
348 }
349
350 fn deduce_closure_signature_from_predicates(
351 &self,
352 expected_ty: Ty<'tcx>,
353 closure_kind: hir::ClosureKind,
354 predicates: impl DoubleEndedIterator<Item = (ty::Predicate<'tcx>, Span)>,
355 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
356 let mut expected_sig = None;
357 let mut expected_kind = None;
358
359 for (pred, span) in traits::elaborate(
360 self.tcx,
361 // Reverse the obligations here, since `elaborate_*` uses a stack,
362 // and we want to keep inference generally in the same order of
363 // the registered obligations.
364 predicates.rev(),
365 )
366 // We only care about self bounds
367 .filter_only_self()
368 {
369 debug!(?pred);
370 let bound_predicate = pred.kind();
371
372 // Given a Projection predicate, we can potentially infer
373 // the complete signature.
374 if expected_sig.is_none()
375 && let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj_predicate)) =
376 bound_predicate.skip_binder()
377 {
378 let inferred_sig = self.normalize(
379 span,
380 self.deduce_sig_from_projection(
381 Some(span),
382 closure_kind,
383 bound_predicate.rebind(proj_predicate),
384 ),
385 );
386
387 // Make sure that we didn't infer a signature that mentions itself.
388 // This can happen when we elaborate certain supertrait bounds that
389 // mention projections containing the `Self` type. See #105401.
390 struct MentionsTy<'tcx> {
391 expected_ty: Ty<'tcx>,
392 }
393 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for MentionsTy<'tcx> {
394 type Result = ControlFlow<()>;
395
396 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
397 if t == self.expected_ty {
398 ControlFlow::Break(())
399 } else {
400 t.super_visit_with(self)
401 }
402 }
403 }
404
405 // Don't infer a closure signature from a goal that names the closure type as this will
406 // (almost always) lead to occurs check errors later in type checking.
407 if self.next_trait_solver()
408 && let Some(inferred_sig) = inferred_sig
409 {
410 // In the new solver it is difficult to explicitly normalize the inferred signature as we
411 // would have to manually handle universes and rewriting bound vars and placeholders back
412 // and forth.
413 //
414 // Instead we take advantage of the fact that we relating an inference variable with an alias
415 // will only instantiate the variable if the alias is rigid(*not quite). Concretely we:
416 // - Create some new variable `?sig`
417 // - Equate `?sig` with the unnormalized signature, e.g. `fn(<Foo<?x> as Trait>::Assoc)`
418 // - Depending on whether `<Foo<?x> as Trait>::Assoc` is rigid, ambiguous or normalizeable,
419 // we will either wind up with `?sig=<Foo<?x> as Trait>::Assoc/?y/ConcreteTy` respectively.
420 //
421 // *: In cases where there are ambiguous aliases in the signature that make use of bound vars
422 // they will wind up present in `?sig` even though they are non-rigid.
423 //
424 // This is a bit weird and means we may wind up discarding the goal due to it naming `expected_ty`
425 // even though the normalized form may not name `expected_ty`. However, this matches the existing
426 // behaviour of the old solver and would be technically a breaking change to fix.
427 let generalized_fnptr_sig = self.next_ty_var(span);
428 let inferred_fnptr_sig = Ty::new_fn_ptr(self.tcx, inferred_sig.sig);
429 self.demand_eqtype(span, inferred_fnptr_sig, generalized_fnptr_sig);
430
431 let resolved_sig = self.resolve_vars_if_possible(generalized_fnptr_sig);
432
433 if resolved_sig.visit_with(&mut MentionsTy { expected_ty }).is_continue() {
434 expected_sig = Some(ExpectedSig {
435 cause_span: inferred_sig.cause_span,
436 sig: resolved_sig.fn_sig(self.tcx),
437 });
438 }
439 } else {
440 if inferred_sig.visit_with(&mut MentionsTy { expected_ty }).is_continue() {
441 expected_sig = inferred_sig;
442 }
443 }
444 }
445
446 // Even if we can't infer the full signature, we may be able to
447 // infer the kind. This can occur when we elaborate a predicate
448 // like `F : Fn<A>`. Note that due to subtyping we could encounter
449 // many viable options, so pick the most restrictive.
450 let trait_def_id = match bound_predicate.skip_binder() {
451 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
452 Some(data.projection_term.trait_def_id(self.tcx))
453 }
454 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => Some(data.def_id()),
455 _ => None,
456 };
457
458 if let Some(trait_def_id) = trait_def_id {
459 let found_kind = match closure_kind {
460 hir::ClosureKind::Closure => self.tcx.fn_trait_kind_from_def_id(trait_def_id),
461 hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => self
462 .tcx
463 .async_fn_trait_kind_from_def_id(trait_def_id)
464 .or_else(|| self.tcx.fn_trait_kind_from_def_id(trait_def_id)),
465 _ => None,
466 };
467
468 if let Some(found_kind) = found_kind {
469 // always use the closure kind that is more permissive.
470 match (expected_kind, found_kind) {
471 (None, _) => expected_kind = Some(found_kind),
472 (Some(ClosureKind::FnMut), ClosureKind::Fn) => {
473 expected_kind = Some(ClosureKind::Fn)
474 }
475 (Some(ClosureKind::FnOnce), ClosureKind::Fn | ClosureKind::FnMut) => {
476 expected_kind = Some(found_kind)
477 }
478 _ => {}
479 }
480 }
481 }
482 }
483
484 (expected_sig, expected_kind)
485 }
486
487 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
488 /// everything we need to know about a closure or coroutine.
489 ///
490 /// The `cause_span` should be the span that caused us to
491 /// have this expected signature, or `None` if we can't readily
492 /// know that.
493 #[instrument(level = "debug", skip(self, cause_span), ret)]
494 fn deduce_sig_from_projection(
495 &self,
496 cause_span: Option<Span>,
497 closure_kind: hir::ClosureKind,
498 projection: ty::PolyProjectionPredicate<'tcx>,
499 ) -> Option<ExpectedSig<'tcx>> {
500 let def_id = projection.item_def_id();
501
502 // For now, we only do signature deduction based off of the `Fn` and `AsyncFn` traits,
503 // for closures and async closures, respectively.
504 match closure_kind {
505 hir::ClosureKind::Closure if self.tcx.is_lang_item(def_id, LangItem::FnOnceOutput) => {
506 self.extract_sig_from_projection(cause_span, projection)
507 }
508 hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
509 if self.tcx.is_lang_item(def_id, LangItem::AsyncFnOnceOutput) =>
510 {
511 self.extract_sig_from_projection(cause_span, projection)
512 }
513 // It's possible we've passed the closure to a (somewhat out-of-fashion)
514 // `F: FnOnce() -> Fut, Fut: Future<Output = T>` style bound. Let's still
515 // guide inference here, since it's beneficial for the user.
516 hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
517 if self.tcx.is_lang_item(def_id, LangItem::FnOnceOutput) =>
518 {
519 self.extract_sig_from_projection_and_future_bound(cause_span, projection)
520 }
521 _ => None,
522 }
523 }
524
525 /// Given an `FnOnce::Output` or `AsyncFn::Output` projection, extract the args
526 /// and return type to infer a [`ty::PolyFnSig`] for the closure.
527 fn extract_sig_from_projection(
528 &self,
529 cause_span: Option<Span>,
530 projection: ty::PolyProjectionPredicate<'tcx>,
531 ) -> Option<ExpectedSig<'tcx>> {
532 let projection = self.resolve_vars_if_possible(projection);
533
534 let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1);
535 debug!(?arg_param_ty);
536
537 let ty::Tuple(input_tys) = *arg_param_ty.kind() else {
538 return None;
539 };
540
541 // Since this is a return parameter type it is safe to unwrap.
542 let ret_param_ty = projection.skip_binder().term.expect_type();
543 debug!(?ret_param_ty);
544
545 let sig = projection.rebind(self.tcx.mk_fn_sig(
546 input_tys,
547 ret_param_ty,
548 false,
549 hir::Safety::Safe,
550 ExternAbi::Rust,
551 ));
552
553 Some(ExpectedSig { cause_span, sig })
554 }
555
556 /// When an async closure is passed to a function that has a "two-part" `Fn`
557 /// and `Future` trait bound, like:
558 ///
559 /// ```rust
560 /// use std::future::Future;
561 ///
562 /// fn not_exactly_an_async_closure<F, Fut>(_f: F)
563 /// where
564 /// F: FnOnce(String, u32) -> Fut,
565 /// Fut: Future<Output = i32>,
566 /// {}
567 /// ```
568 ///
569 /// The we want to be able to extract the signature to guide inference in the async
570 /// closure. We will have two projection predicates registered in this case. First,
571 /// we identify the `FnOnce<Args, Output = ?Fut>` bound, and if the output type is
572 /// an inference variable `?Fut`, we check if that is bounded by a `Future<Output = Ty>`
573 /// projection.
574 ///
575 /// This function is actually best-effort with the return type; if we don't find a
576 /// `Future` projection, we still will return arguments that we extracted from the `FnOnce`
577 /// projection, and the output will be an unconstrained type variable instead.
578 fn extract_sig_from_projection_and_future_bound(
579 &self,
580 cause_span: Option<Span>,
581 projection: ty::PolyProjectionPredicate<'tcx>,
582 ) -> Option<ExpectedSig<'tcx>> {
583 let projection = self.resolve_vars_if_possible(projection);
584
585 let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1);
586 debug!(?arg_param_ty);
587
588 let ty::Tuple(input_tys) = *arg_param_ty.kind() else {
589 return None;
590 };
591
592 // If the return type is a type variable, look for bounds on it.
593 // We could theoretically support other kinds of return types here,
594 // but none of them would be useful, since async closures return
595 // concrete anonymous future types, and their futures are not coerced
596 // into any other type within the body of the async closure.
597 let ty::Infer(ty::TyVar(return_vid)) = *projection.skip_binder().term.expect_type().kind()
598 else {
599 return None;
600 };
601
602 // FIXME: We may want to elaborate here, though I assume this will be exceedingly rare.
603 let mut return_ty = None;
604 for bound in self.obligations_for_self_ty(return_vid) {
605 if let Some(ret_projection) = bound.predicate.as_projection_clause()
606 && let Some(ret_projection) = ret_projection.no_bound_vars()
607 && self.tcx.is_lang_item(ret_projection.def_id(), LangItem::FutureOutput)
608 {
609 return_ty = Some(ret_projection.term.expect_type());
610 break;
611 }
612 }
613
614 // SUBTLE: If we didn't find a `Future<Output = ...>` bound for the return
615 // vid, we still want to attempt to provide inference guidance for the async
616 // closure's arguments. Instantiate a new vid to plug into the output type.
617 //
618 // You may be wondering, what if it's higher-ranked? Well, given that we
619 // found a type variable for the `FnOnce::Output` projection above, we know
620 // that the output can't mention any of the vars.
621 //
622 // Also note that we use a fresh var here for the signature since the signature
623 // records the output of the *future*, and `return_vid` above is the type
624 // variable of the future, not its output.
625 //
626 // FIXME: We probably should store this signature inference output in a way
627 // that does not misuse a `FnSig` type, but that can be done separately.
628 let return_ty =
629 return_ty.unwrap_or_else(|| self.next_ty_var(cause_span.unwrap_or(DUMMY_SP)));
630
631 let sig = projection.rebind(self.tcx.mk_fn_sig(
632 input_tys,
633 return_ty,
634 false,
635 hir::Safety::Safe,
636 ExternAbi::Rust,
637 ));
638
639 Some(ExpectedSig { cause_span, sig })
640 }
641
642 fn sig_of_closure(
643 &self,
644 expr_def_id: LocalDefId,
645 decl: &hir::FnDecl<'tcx>,
646 closure_kind: hir::ClosureKind,
647 expected_sig: Option<ExpectedSig<'tcx>>,
648 ) -> ClosureSignatures<'tcx> {
649 if let Some(e) = expected_sig {
650 self.sig_of_closure_with_expectation(expr_def_id, decl, closure_kind, e)
651 } else {
652 self.sig_of_closure_no_expectation(expr_def_id, decl, closure_kind)
653 }
654 }
655
656 /// If there is no expected signature, then we will convert the
657 /// types that the user gave into a signature.
658 #[instrument(skip(self, expr_def_id, decl), level = "debug")]
659 fn sig_of_closure_no_expectation(
660 &self,
661 expr_def_id: LocalDefId,
662 decl: &hir::FnDecl<'tcx>,
663 closure_kind: hir::ClosureKind,
664 ) -> ClosureSignatures<'tcx> {
665 let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl, closure_kind);
666
667 self.closure_sigs(expr_def_id, bound_sig)
668 }
669
670 /// Invoked to compute the signature of a closure expression. This
671 /// combines any user-provided type annotations (e.g., `|x: u32|
672 /// -> u32 { .. }`) with the expected signature.
673 ///
674 /// The approach is as follows:
675 ///
676 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
677 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
678 /// - If we have no expectation `E`, then the signature of the closure is `S`.
679 /// - Otherwise, the signature of the closure is E. Moreover:
680 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
681 /// - Instantiate all the late-bound regions bound in the closure within `S`
682 /// with fresh (existential) variables, yielding `S'`
683 /// - Require that `E' = S'`
684 /// - We could use some kind of subtyping relationship here,
685 /// I imagine, but equality is easier and works fine for
686 /// our purposes.
687 ///
688 /// The key intuition here is that the user's types must be valid
689 /// from "the inside" of the closure, but the expectation
690 /// ultimately drives the overall signature.
691 ///
692 /// # Examples
693 ///
694 /// ```ignore (illustrative)
695 /// fn with_closure<F>(_: F)
696 /// where F: Fn(&u32) -> &u32 { .. }
697 ///
698 /// with_closure(|x: &u32| { ... })
699 /// ```
700 ///
701 /// Here:
702 /// - E would be `fn(&u32) -> &u32`.
703 /// - S would be `fn(&u32) -> ?T`
704 /// - E' is `&'!0 u32 -> &'!0 u32`
705 /// - S' is `&'?0 u32 -> ?T`
706 ///
707 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
708 ///
709 /// # Arguments
710 ///
711 /// - `expr_def_id`: the `LocalDefId` of the closure expression
712 /// - `decl`: the HIR declaration of the closure
713 /// - `body`: the body of the closure
714 /// - `expected_sig`: the expected signature (if any). Note that
715 /// this is missing a binder: that is, there may be late-bound
716 /// regions with depth 1, which are bound then by the closure.
717 #[instrument(skip(self, expr_def_id, decl), level = "debug")]
718 fn sig_of_closure_with_expectation(
719 &self,
720 expr_def_id: LocalDefId,
721 decl: &hir::FnDecl<'tcx>,
722 closure_kind: hir::ClosureKind,
723 expected_sig: ExpectedSig<'tcx>,
724 ) -> ClosureSignatures<'tcx> {
725 // Watch out for some surprises and just ignore the
726 // expectation if things don't see to match up with what we
727 // expect.
728 if expected_sig.sig.c_variadic() != decl.c_variadic {
729 return self.sig_of_closure_no_expectation(expr_def_id, decl, closure_kind);
730 } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 {
731 return self.sig_of_closure_with_mismatched_number_of_arguments(
732 expr_def_id,
733 decl,
734 expected_sig,
735 );
736 }
737
738 // Create a `PolyFnSig`. Note the oddity that late bound
739 // regions appearing free in `expected_sig` are now bound up
740 // in this binder we are creating.
741 assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST));
742 let bound_sig = expected_sig.sig.map_bound(|sig| {
743 self.tcx.mk_fn_sig(
744 sig.inputs().iter().cloned(),
745 sig.output(),
746 sig.c_variadic,
747 hir::Safety::Safe,
748 ExternAbi::RustCall,
749 )
750 });
751
752 // `deduce_expectations_from_expected_type` introduces
753 // late-bound lifetimes defined elsewhere, which we now
754 // anonymize away, so as not to confuse the user.
755 let bound_sig = self.tcx.anonymize_bound_vars(bound_sig);
756
757 let closure_sigs = self.closure_sigs(expr_def_id, bound_sig);
758
759 // Up till this point, we have ignored the annotations that the user
760 // gave. This function will check that they unify successfully.
761 // Along the way, it also writes out entries for types that the user
762 // wrote into our typeck results, which are then later used by the privacy
763 // check.
764 match self.merge_supplied_sig_with_expectation(
765 expr_def_id,
766 decl,
767 closure_kind,
768 closure_sigs,
769 ) {
770 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
771 Err(_) => self.sig_of_closure_no_expectation(expr_def_id, decl, closure_kind),
772 }
773 }
774
775 fn sig_of_closure_with_mismatched_number_of_arguments(
776 &self,
777 expr_def_id: LocalDefId,
778 decl: &hir::FnDecl<'tcx>,
779 expected_sig: ExpectedSig<'tcx>,
780 ) -> ClosureSignatures<'tcx> {
781 let expr_map_node = self.tcx.hir_node_by_def_id(expr_def_id);
782 let expected_args: Vec<_> = expected_sig
783 .sig
784 .skip_binder()
785 .inputs()
786 .iter()
787 .map(|ty| ArgKind::from_expected_ty(*ty, None))
788 .collect();
789 let (closure_span, closure_arg_span, found_args) =
790 match self.err_ctxt().get_fn_like_arguments(expr_map_node) {
791 Some((sp, arg_sp, args)) => (Some(sp), arg_sp, args),
792 None => (None, None, Vec::new()),
793 };
794 let expected_span =
795 expected_sig.cause_span.unwrap_or_else(|| self.tcx.def_span(expr_def_id));
796 let guar = self
797 .err_ctxt()
798 .report_arg_count_mismatch(
799 expected_span,
800 closure_span,
801 expected_args,
802 found_args,
803 true,
804 closure_arg_span,
805 )
806 .emit();
807
808 let error_sig = self.error_sig_of_closure(decl, guar);
809
810 self.closure_sigs(expr_def_id, error_sig)
811 }
812
813 /// Enforce the user's types against the expectation. See
814 /// `sig_of_closure_with_expectation` for details on the overall
815 /// strategy.
816 #[instrument(level = "debug", skip(self, expr_def_id, decl, expected_sigs))]
817 fn merge_supplied_sig_with_expectation(
818 &self,
819 expr_def_id: LocalDefId,
820 decl: &hir::FnDecl<'tcx>,
821 closure_kind: hir::ClosureKind,
822 mut expected_sigs: ClosureSignatures<'tcx>,
823 ) -> InferResult<'tcx, ClosureSignatures<'tcx>> {
824 // Get the signature S that the user gave.
825 //
826 // (See comment on `sig_of_closure_with_expectation` for the
827 // meaning of these letters.)
828 let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl, closure_kind);
829
830 debug!(?supplied_sig);
831
832 // FIXME(#45727): As discussed in [this comment][c1], naively
833 // forcing equality here actually results in suboptimal error
834 // messages in some cases. For now, if there would have been
835 // an obvious error, we fallback to declaring the type of the
836 // closure to be the one the user gave, which allows other
837 // error message code to trigger.
838 //
839 // However, I think [there is potential to do even better
840 // here][c2], since in *this* code we have the precise span of
841 // the type parameter in question in hand when we report the
842 // error.
843 //
844 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
845 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
846 self.commit_if_ok(|_| {
847 let mut all_obligations = PredicateObligations::new();
848 let supplied_sig = self.instantiate_binder_with_fresh_vars(
849 self.tcx.def_span(expr_def_id),
850 BoundRegionConversionTime::FnCall,
851 supplied_sig,
852 );
853
854 // The liberated version of this signature should be a subtype
855 // of the liberated form of the expectation.
856 for ((hir_ty, &supplied_ty), expected_ty) in iter::zip(
857 iter::zip(decl.inputs, supplied_sig.inputs()),
858 expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'.
859 ) {
860 // Check that E' = S'.
861 let cause = self.misc(hir_ty.span);
862 let InferOk { value: (), obligations } = self.at(&cause, self.param_env).eq(
863 DefineOpaqueTypes::Yes,
864 *expected_ty,
865 supplied_ty,
866 )?;
867 all_obligations.extend(obligations);
868 }
869
870 let supplied_output_ty = supplied_sig.output();
871 let cause = &self.misc(decl.output.span());
872 let InferOk { value: (), obligations } = self.at(cause, self.param_env).eq(
873 DefineOpaqueTypes::Yes,
874 expected_sigs.liberated_sig.output(),
875 supplied_output_ty,
876 )?;
877 all_obligations.extend(obligations);
878
879 let inputs =
880 supplied_sig.inputs().into_iter().map(|&ty| self.resolve_vars_if_possible(ty));
881
882 expected_sigs.liberated_sig = self.tcx.mk_fn_sig(
883 inputs,
884 supplied_output_ty,
885 expected_sigs.liberated_sig.c_variadic,
886 hir::Safety::Safe,
887 ExternAbi::RustCall,
888 );
889
890 Ok(InferOk { value: expected_sigs, obligations: all_obligations })
891 })
892 }
893
894 /// If there is no expected signature, then we will convert the
895 /// types that the user gave into a signature.
896 ///
897 /// Also, record this closure signature for later.
898 #[instrument(skip(self, decl), level = "debug", ret)]
899 fn supplied_sig_of_closure(
900 &self,
901 expr_def_id: LocalDefId,
902 decl: &hir::FnDecl<'tcx>,
903 closure_kind: hir::ClosureKind,
904 ) -> ty::PolyFnSig<'tcx> {
905 let lowerer = self.lowerer();
906
907 trace!("decl = {:#?}", decl);
908 debug!(?closure_kind);
909
910 let hir_id = self.tcx.local_def_id_to_hir_id(expr_def_id);
911 let bound_vars = self.tcx.late_bound_vars(hir_id);
912
913 // First, convert the types that the user supplied (if any).
914 let supplied_arguments = decl.inputs.iter().map(|a| lowerer.lower_ty(a));
915 let supplied_return = match decl.output {
916 hir::FnRetTy::Return(ref output) => lowerer.lower_ty(output),
917 hir::FnRetTy::DefaultReturn(_) => match closure_kind {
918 // In the case of the async block that we create for a function body,
919 // we expect the return type of the block to match that of the enclosing
920 // function.
921 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
922 hir::CoroutineDesugaring::Async,
923 hir::CoroutineSource::Fn,
924 )) => {
925 debug!("closure is async fn body");
926 self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| {
927 // AFAIK, deducing the future output
928 // always succeeds *except* in error cases
929 // like #65159. I'd like to return Error
930 // here, but I can't because I can't
931 // easily (and locally) prove that we
932 // *have* reported an
933 // error. --nikomatsakis
934 lowerer.ty_infer(None, decl.output.span())
935 })
936 }
937 // All `gen {}` and `async gen {}` must return unit.
938 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
939 hir::CoroutineDesugaring::Gen | hir::CoroutineDesugaring::AsyncGen,
940 _,
941 )) => self.tcx.types.unit,
942
943 // For async blocks, we just fall back to `_` here.
944 // For closures/coroutines, we know nothing about the return
945 // type unless it was supplied.
946 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
947 hir::CoroutineDesugaring::Async,
948 _,
949 ))
950 | hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_))
951 | hir::ClosureKind::Closure
952 | hir::ClosureKind::CoroutineClosure(_) => {
953 lowerer.ty_infer(None, decl.output.span())
954 }
955 },
956 };
957
958 let result = ty::Binder::bind_with_vars(
959 self.tcx.mk_fn_sig(
960 supplied_arguments,
961 supplied_return,
962 decl.c_variadic,
963 hir::Safety::Safe,
964 ExternAbi::RustCall,
965 ),
966 bound_vars,
967 );
968
969 let c_result = self.infcx.canonicalize_response(result);
970 self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
971
972 // Normalize only after registering in `user_provided_sigs`.
973 self.normalize(self.tcx.hir().span(hir_id), result)
974 }
975
976 /// Invoked when we are translating the coroutine that results
977 /// from desugaring an `async fn`. Returns the "sugared" return
978 /// type of the `async fn` -- that is, the return type that the
979 /// user specified. The "desugared" return type is an `impl
980 /// Future<Output = T>`, so we do this by searching through the
981 /// obligations to extract the `T`.
982 #[instrument(skip(self), level = "debug", ret)]
983 fn deduce_future_output_from_obligations(&self, body_def_id: LocalDefId) -> Option<Ty<'tcx>> {
984 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
985 span_bug!(self.tcx.def_span(body_def_id), "async fn coroutine outside of a fn")
986 });
987
988 let closure_span = self.tcx.def_span(body_def_id);
989 let ret_ty = ret_coercion.borrow().expected_ty();
990 let ret_ty = self.try_structurally_resolve_type(closure_span, ret_ty);
991
992 let get_future_output = |predicate: ty::Predicate<'tcx>, span| {
993 // Search for a pending obligation like
994 //
995 // `<R as Future>::Output = T`
996 //
997 // where R is the return type we are expecting. This type `T`
998 // will be our output.
999 let bound_predicate = predicate.kind();
1000 if let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj_predicate)) =
1001 bound_predicate.skip_binder()
1002 {
1003 self.deduce_future_output_from_projection(
1004 span,
1005 bound_predicate.rebind(proj_predicate),
1006 )
1007 } else {
1008 None
1009 }
1010 };
1011
1012 let output_ty = match *ret_ty.kind() {
1013 ty::Infer(ty::TyVar(ret_vid)) => {
1014 self.obligations_for_self_ty(ret_vid).into_iter().find_map(|obligation| {
1015 get_future_output(obligation.predicate, obligation.cause.span)
1016 })?
1017 }
1018 ty::Alias(ty::Projection, _) => {
1019 return Some(Ty::new_error_with_message(
1020 self.tcx,
1021 closure_span,
1022 "this projection should have been projected to an opaque type",
1023 ));
1024 }
1025 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => self
1026 .tcx
1027 .explicit_item_self_bounds(def_id)
1028 .iter_instantiated_copied(self.tcx, args)
1029 .find_map(|(p, s)| get_future_output(p.as_predicate(), s))?,
1030 ty::Error(_) => return Some(ret_ty),
1031 _ => {
1032 span_bug!(closure_span, "invalid async fn coroutine return type: {ret_ty:?}")
1033 }
1034 };
1035
1036 let output_ty = self.normalize(closure_span, output_ty);
1037
1038 // async fn that have opaque types in their return type need to redo the conversion to inference variables
1039 // as they fetch the still opaque version from the signature.
1040 let InferOk { value: output_ty, obligations } = self
1041 .replace_opaque_types_with_inference_vars(
1042 output_ty,
1043 body_def_id,
1044 closure_span,
1045 self.param_env,
1046 );
1047 self.register_predicates(obligations);
1048
1049 Some(output_ty)
1050 }
1051
1052 /// Given a projection like
1053 ///
1054 /// `<X as Future>::Output = T`
1055 ///
1056 /// where `X` is some type that has no late-bound regions, returns
1057 /// `Some(T)`. If the projection is for some other trait, returns
1058 /// `None`.
1059 fn deduce_future_output_from_projection(
1060 &self,
1061 cause_span: Span,
1062 predicate: ty::PolyProjectionPredicate<'tcx>,
1063 ) -> Option<Ty<'tcx>> {
1064 debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
1065
1066 // We do not expect any bound regions in our predicate, so
1067 // skip past the bound vars.
1068 let Some(predicate) = predicate.no_bound_vars() else {
1069 debug!("deduce_future_output_from_projection: has late-bound regions");
1070 return None;
1071 };
1072
1073 // Check that this is a projection from the `Future` trait.
1074 let trait_def_id = predicate.projection_term.trait_def_id(self.tcx);
1075 let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span));
1076 if trait_def_id != future_trait {
1077 debug!("deduce_future_output_from_projection: not a future");
1078 return None;
1079 }
1080
1081 // The `Future` trait has only one associated item, `Output`,
1082 // so check that this is what we see.
1083 let output_assoc_item = self.tcx.associated_item_def_ids(future_trait)[0];
1084 if output_assoc_item != predicate.projection_term.def_id {
1085 span_bug!(
1086 cause_span,
1087 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
1088 predicate.projection_term.def_id,
1089 output_assoc_item,
1090 );
1091 }
1092
1093 // Extract the type from the projection. Note that there can
1094 // be no bound variables in this type because the "self type"
1095 // does not have any regions in it.
1096 let output_ty = self.resolve_vars_if_possible(predicate.term);
1097 debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
1098 // This is a projection on a Fn trait so will always be a type.
1099 Some(output_ty.expect_type())
1100 }
1101
1102 /// Converts the types that the user supplied, in case that doing
1103 /// so should yield an error, but returns back a signature where
1104 /// all parameters are of type `ty::Error`.
1105 fn error_sig_of_closure(
1106 &self,
1107 decl: &hir::FnDecl<'tcx>,
1108 guar: ErrorGuaranteed,
1109 ) -> ty::PolyFnSig<'tcx> {
1110 let lowerer = self.lowerer();
1111 let err_ty = Ty::new_error(self.tcx, guar);
1112
1113 let supplied_arguments = decl.inputs.iter().map(|a| {
1114 // Convert the types that the user supplied (if any), but ignore them.
1115 lowerer.lower_ty(a);
1116 err_ty
1117 });
1118
1119 if let hir::FnRetTy::Return(ref output) = decl.output {
1120 lowerer.lower_ty(output);
1121 }
1122
1123 let result = ty::Binder::dummy(self.tcx.mk_fn_sig(
1124 supplied_arguments,
1125 err_ty,
1126 decl.c_variadic,
1127 hir::Safety::Safe,
1128 ExternAbi::RustCall,
1129 ));
1130
1131 debug!("supplied_sig_of_closure: result={:?}", result);
1132
1133 result
1134 }
1135
1136 #[instrument(level = "debug", skip(self), ret)]
1137 fn closure_sigs(
1138 &self,
1139 expr_def_id: LocalDefId,
1140 bound_sig: ty::PolyFnSig<'tcx>,
1141 ) -> ClosureSignatures<'tcx> {
1142 let liberated_sig =
1143 self.tcx().liberate_late_bound_regions(expr_def_id.to_def_id(), bound_sig);
1144 let liberated_sig = self.normalize(self.tcx.def_span(expr_def_id), liberated_sig);
1145 ClosureSignatures { bound_sig, liberated_sig }
1146 }
1147}