Skip to main content

rustc_ast_lowering/expr/
closure.rs

1use rustc_ast::*;
2use rustc_attr_ir::find_attr;
3use rustc_attr_ir::target::Target;
4use rustc_hir as hir;
5use rustc_hir::HirId;
6use rustc_span::{Span, span_bug};
7
8use super::{LoweringContext, MoveExprState};
9use crate::FnDeclKind;
10use crate::diagnostics::{ClosureCannotBeStatic, CoroutineTooManyParameters};
11
12impl<'hir> LoweringContext<'_, 'hir> {
13    // Entry point for `ExprKind::Closure`. Plain closures go through
14    // `lower_expr_plain_closure_with_move_exprs`, which can wrap the lowered
15    // closure in `let` initializers for `move(...)`. Coroutine closures use the
16    // same wrapper after building their coroutine-specific body shape.
17    pub(super) fn lower_expr_closure_expr(
18        &mut self,
19        e: &Expr,
20        closure: &Closure,
21    ) -> hir::Expr<'hir> {
22        let expr_hir_id = self.lower_node_id(e.id);
23        let attrs = self.lower_attrs(expr_hir_id, &e.attrs, e.span, Target::from_expr(e));
24
25        match closure.coroutine_marker {
26            Some(coroutine_marker) => self.lower_expr_coroutine_closure_with_move_exprs(
27                expr_hir_id,
28                attrs,
29                &closure.binder,
30                closure.capture_clause,
31                e.id,
32                coroutine_marker,
33                closure.constness,
34                &closure.fn_decl,
35                &closure.body,
36                closure.fn_decl_span,
37                closure.fn_arg_span,
38                e.span,
39            ),
40            None => self.lower_expr_plain_closure_with_move_exprs(
41                expr_hir_id,
42                attrs,
43                &closure.binder,
44                closure.capture_clause,
45                e.id,
46                closure.constness,
47                closure.movability,
48                &closure.fn_decl,
49                &closure.body,
50                closure.fn_decl_span,
51                closure.fn_arg_span,
52                e.span,
53            ),
54        }
55    }
56
57    fn lower_expr_coroutine_closure_with_move_exprs(
58        &mut self,
59        expr_hir_id: HirId,
60        attrs: &[rustc_attr_ir::Attribute],
61        binder: &ClosureBinder,
62        capture_clause: CaptureBy,
63        closure_id: NodeId,
64        coroutine_marker: CoroutineMarker,
65        constness: Const,
66        decl: &FnDecl,
67        body: &Expr,
68        fn_decl_span: Span,
69        fn_arg_span: Span,
70        whole_span: Span,
71    ) -> hir::Expr<'hir> {
72        let (kind, move_expr_state) =
73            self.with_move_expr_bindings(Some(MoveExprState::default()), |this| {
74                this.lower_expr_coroutine_closure(
75                    binder,
76                    capture_clause,
77                    closure_id,
78                    expr_hir_id,
79                    coroutine_marker,
80                    constness,
81                    decl,
82                    body,
83                    fn_decl_span,
84                    fn_arg_span,
85                    attrs,
86                )
87            });
88        let Some(move_expr_state) = move_expr_state else {
89            ::rustc_span::macros::bug_impl(Some(fn_decl_span),
    format_args!("coroutine closure lowering did not return `move(...)` state"),
    Location::caller());span_bug!(fn_decl_span, "coroutine closure lowering did not return `move(...)` state");
90        };
91        let closure_expr =
92            hir::Expr { hir_id: expr_hir_id, kind, span: self.lower_span(whole_span) };
93
94        self.lower_expr_with_move_exprs(closure_expr, move_expr_state, body, whole_span)
95    }
96
97    /// Lowers a plain closure expression and wraps it in an outer block if the
98    /// closure body used `move(...)`.
99    ///
100    /// The lowering is split this way because `move(...)` initializers must be
101    /// evaluated before the closure is created, but the closure body must still
102    /// lower each `move(...)` occurrence as a use of the synthetic local that
103    /// will be introduced by that outer block. For example,
104    /// `|| move(foo.clone()).len()` becomes roughly:
105    ///
106    /// ```ignore (illustrative)
107    /// {
108    ///     let __move_expr_0 = foo.clone();
109    ///     || __move_expr_0.len()
110    /// }
111    /// ```
112    ///
113    /// If the initializer contains another `move(...)`, it is lowered after
114    /// this closure's state is popped and therefore belongs to the immediately
115    /// enclosing closure-like body.
116    fn lower_expr_plain_closure_with_move_exprs(
117        &mut self,
118        expr_hir_id: HirId,
119        attrs: &[rustc_attr_ir::Attribute],
120        binder: &ClosureBinder,
121        capture_clause: CaptureBy,
122        closure_id: NodeId,
123        constness: Const,
124        movability: Movability,
125        decl: &FnDecl,
126        body: &Expr,
127        fn_decl_span: Span,
128        fn_arg_span: Span,
129        whole_span: Span,
130    ) -> hir::Expr<'hir> {
131        let (closure_kind, move_expr_state) = self.lower_expr_closure(
132            attrs,
133            binder,
134            capture_clause,
135            closure_id,
136            constness,
137            movability,
138            decl,
139            body,
140            fn_decl_span,
141            fn_arg_span,
142        );
143
144        let closure_expr = hir::Expr {
145            hir_id: expr_hir_id,
146            kind: closure_kind,
147            span: self.lower_span(whole_span),
148        };
149
150        self.lower_expr_with_move_exprs(closure_expr, move_expr_state, body, whole_span)
151    }
152
153    // Lowers the actual plain closure node and body. The body is lowered while a
154    // `MoveExprState` is active, so `move(...)` occurrences become synthetic
155    // local uses and the caller can later add the matching initializers.
156    fn lower_expr_closure(
157        &mut self,
158        attrs: &[rustc_attr_ir::Attribute],
159        binder: &ClosureBinder,
160        capture_clause: CaptureBy,
161        closure_id: NodeId,
162        constness: Const,
163        movability: Movability,
164        decl: &FnDecl,
165        body: &Expr,
166        fn_decl_span: Span,
167        fn_arg_span: Span,
168    ) -> (hir::ExprKind<'hir>, MoveExprState<'hir>) {
169        let closure_def_id = self.local_def_id(closure_id);
170        let (binder_clause, generic_params) = self.lower_closure_binder(binder);
171
172        let ((body_id, closure_kind), move_expr_state) =
173            self.with_new_scopes(fn_decl_span, move |this| {
174                let mut coroutine_kind = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(Coroutine) => {
                    break 'done
                        Some(hir::CoroutineKind::Coroutine(Movability::Movable));
                }
                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(
175                    attrs,
176                    Coroutine => hir::CoroutineKind::Coroutine(Movability::Movable)
177                );
178
179                this.with_move_expr_bindings(Some(MoveExprState::default()), |this| {
180                    // FIXME(contracts): Support contracts on closures?
181                    let body_id = this.lower_fn_body(decl, None, |this| {
182                        this.coroutine_kind = coroutine_kind;
183                        let e = this.lower_expr_mut(body);
184                        coroutine_kind = this.coroutine_kind;
185                        e
186                    });
187                    let coroutine_option = this.closure_movability_for_fn(
188                        decl,
189                        fn_decl_span,
190                        coroutine_kind,
191                        movability,
192                    );
193                    (body_id, coroutine_option)
194                })
195            });
196        let Some(move_expr_state) = move_expr_state else {
197            ::rustc_span::macros::bug_impl(Some(fn_decl_span),
    format_args!("plain closure lowering did not return `move(...)` state"),
    Location::caller());span_bug!(fn_decl_span, "plain closure lowering did not return `move(...)` state");
198        };
199        let explicit_captures: &'hir [hir::ExplicitCapture] = self.arena.alloc_from_iter(
200            move_expr_state
201                .occurrences
202                .iter()
203                .map(|occurrence| hir::ExplicitCapture { var_hir_id: occurrence.binding }),
204        );
205
206        let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
207        // Lower outside new scope to preserve `is_in_loop_condition`.
208        let fn_decl = self.lower_fn_decl(decl, closure_id, FnDeclKind::Closure, None);
209
210        let c = self.arena.alloc(hir::Closure {
211            def_id: closure_def_id,
212            binder: binder_clause,
213            capture_clause: self.lower_capture_clause(capture_clause),
214            bound_generic_params,
215            fn_decl,
216            body: body_id,
217            fn_decl_span: self.lower_span(fn_decl_span),
218            fn_arg_span: Some(self.lower_span(fn_arg_span)),
219            kind: closure_kind,
220            constness: self.lower_constness(attrs, constness),
221            explicit_captures,
222        });
223
224        (hir::ExprKind::Closure(c), move_expr_state)
225    }
226
227    fn closure_movability_for_fn(
228        &mut self,
229        decl: &FnDecl,
230        fn_decl_span: Span,
231        coroutine_kind: Option<hir::CoroutineKind>,
232        movability: Movability,
233    ) -> hir::ClosureKind {
234        match coroutine_kind {
235            Some(hir::CoroutineKind::Coroutine(_)) => {
236                if decl.inputs.len() > 1 {
237                    self.dcx().emit_err(CoroutineTooManyParameters { fn_decl_span });
238                }
239                hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(movability))
240            }
241            Some(
242                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
243                | hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)
244                | hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _),
245            ) => {
246                {
    ::core::panicking::panic_fmt(format_args!("non-`async`/`gen` closure body turned `async`/`gen` during lowering"));
};panic!("non-`async`/`gen` closure body turned `async`/`gen` during lowering");
247            }
248            None => {
249                if movability == Movability::Static {
250                    self.dcx().emit_err(ClosureCannotBeStatic { fn_decl_span });
251                }
252                hir::ClosureKind::Closure
253            }
254        }
255    }
256
257    fn lower_closure_binder<'c>(
258        &mut self,
259        binder: &'c ClosureBinder,
260    ) -> (hir::ClosureBinder, &'c [GenericParam]) {
261        let (binder, params) = match binder {
262            ClosureBinder::NotPresent => (hir::ClosureBinder::Default, &[][..]),
263            ClosureBinder::For { span, generic_params } => {
264                let span = self.lower_span(*span);
265                (hir::ClosureBinder::For { span }, &**generic_params)
266            }
267        };
268
269        (binder, params)
270    }
271
272    // Coroutine closures are lowered separately because they build a different
273    // body shape. The source body is lowered with the caller's `MoveExprState`
274    // active, so `move(...)` occurrences are collected and hoisted into a block
275    // around the outer closure expression.
276    fn lower_expr_coroutine_closure(
277        &mut self,
278        binder: &ClosureBinder,
279        capture_clause: CaptureBy,
280        closure_id: NodeId,
281        closure_hir_id: HirId,
282        coroutine_marker: CoroutineMarker,
283        constness: Const,
284        decl: &FnDecl,
285        body: &Expr,
286        fn_decl_span: Span,
287        fn_arg_span: Span,
288        attrs: &[rustc_attr_ir::Attribute],
289    ) -> hir::ExprKind<'hir> {
290        let closure_def_id = self.local_def_id(closure_id);
291        let (binder_clause, generic_params) = self.lower_closure_binder(binder);
292
293        let coroutine_desugaring = match coroutine_marker.kind {
294            CoroutineKind::Async => hir::CoroutineDesugaring::Async,
295            CoroutineKind::Gen => hir::CoroutineDesugaring::Gen,
296            CoroutineKind::AsyncGen => {
297                ::rustc_span::macros::bug_impl(Some(coroutine_marker.span),
    format_args!("only async closures and `iter!` closures are supported currently"),
    Location::caller())span_bug!(
298                    coroutine_marker.span,
299                    "only async closures and `iter!` closures are supported currently"
300                )
301            }
302        };
303
304        let body = self.with_new_scopes(fn_decl_span, |this| {
305            let inner_decl =
306                FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
307
308            // Transform `async |x: u8| -> X { ... }` into
309            // `|x: u8| || -> X { ... }`.
310            let body_id = this.lower_body(|this| {
311                let (parameters, expr) = this.lower_coroutine_body_with_moved_arguments(
312                    &inner_decl,
313                    |this| this.with_new_scopes(fn_decl_span, |this| this.lower_expr_mut(body)),
314                    fn_decl_span,
315                    body.span,
316                    coroutine_marker,
317                    hir::CoroutineSource::Closure,
318                );
319
320                this.maybe_forward_track_caller(closure_hir_id, expr.hir_id);
321
322                (parameters, expr)
323            });
324            body_id
325        });
326
327        let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
328        // We need to lower the declaration outside the new scope, because we
329        // have to conserve the state of being inside a loop condition for the
330        // closure argument types.
331        let fn_decl = self.lower_fn_decl(&decl, closure_id, FnDeclKind::Closure, None);
332
333        if let Const::Yes(span) = constness {
334            self.dcx().span_err(span, "const coroutines are not supported");
335        }
336
337        let explicit_captures: &'hir [hir::ExplicitCapture] = self.arena.alloc_from_iter(
338            self.move_expr_bindings
339                .last()
340                .and_then(Option::as_ref)
341                .into_iter()
342                .flat_map(|state| &state.occurrences)
343                .map(|occurrence| hir::ExplicitCapture { var_hir_id: occurrence.binding }),
344        );
345
346        let c = self.arena.alloc(hir::Closure {
347            def_id: closure_def_id,
348            binder: binder_clause,
349            capture_clause: self.lower_capture_clause(capture_clause),
350            bound_generic_params,
351            fn_decl,
352            body,
353            fn_decl_span: self.lower_span(fn_decl_span),
354            fn_arg_span: Some(self.lower_span(fn_arg_span)),
355            // Lower this as a `CoroutineClosure`. That will ensure that HIR typeck
356            // knows that a `FnDecl` output type like `-> &str` actually means
357            // "coroutine that returns &str", rather than directly returning a `&str`.
358            kind: hir::ClosureKind::CoroutineClosure(coroutine_desugaring),
359            constness: self.lower_constness(attrs, constness),
360            explicit_captures,
361        });
362        hir::ExprKind::Closure(c)
363    }
364}