rustc_middle/ty/
closure.rs

1use std::fmt::Write;
2
3use rustc_data_structures::fx::FxIndexMap;
4use rustc_hir as hir;
5use rustc_hir::HirId;
6use rustc_hir::def_id::LocalDefId;
7use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
8use rustc_span::def_id::LocalDefIdMap;
9use rustc_span::{Ident, Span, Symbol};
10
11use super::TyCtxt;
12use crate::hir::place::{
13    Place as HirPlace, PlaceBase as HirPlaceBase, ProjectionKind as HirProjectionKind,
14};
15use crate::query::Providers;
16use crate::{mir, ty};
17
18/// Captures are represented using fields inside a structure.
19/// This represents accessing self in the closure structure
20pub const CAPTURE_STRUCT_LOCAL: mir::Local = mir::Local::from_u32(1);
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable)]
23#[derive(TypeFoldable, TypeVisitable)]
24pub struct UpvarPath {
25    pub hir_id: HirId,
26}
27
28/// Upvars do not get their own `NodeId`. Instead, we use the pair of
29/// the original var ID (that is, the root variable that is referenced
30/// by the upvar) and the ID of the closure expression.
31#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable)]
32#[derive(TypeFoldable, TypeVisitable)]
33pub struct UpvarId {
34    pub var_path: UpvarPath,
35    pub closure_expr_id: LocalDefId,
36}
37
38impl UpvarId {
39    pub fn new(var_hir_id: HirId, closure_def_id: LocalDefId) -> UpvarId {
40        UpvarId { var_path: UpvarPath { hir_id: var_hir_id }, closure_expr_id: closure_def_id }
41    }
42}
43
44/// Information describing the capture of an upvar. This is computed
45/// during `typeck`, specifically by `regionck`.
46#[derive(Eq, PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, HashStable, Hash)]
47#[derive(TypeFoldable, TypeVisitable)]
48pub enum UpvarCapture {
49    /// Upvar is captured by value. This is always true when the
50    /// closure is labeled `move`, but can also be true in other cases
51    /// depending on inference.
52    ByValue,
53
54    /// Upvar is captured by use. This is true when the closure is labeled `use`.
55    ByUse,
56
57    /// Upvar is captured by reference.
58    ByRef(BorrowKind),
59}
60
61/// Given the closure DefId this map provides a map of root variables to minimum
62/// set of `CapturedPlace`s that need to be tracked to support all captures of that closure.
63pub type MinCaptureInformationMap<'tcx> = LocalDefIdMap<RootVariableMinCaptureList<'tcx>>;
64
65/// Part of `MinCaptureInformationMap`; Maps a root variable to the list of `CapturedPlace`.
66/// Used to track the minimum set of `Place`s that need to be captured to support all
67/// Places captured by the closure starting at a given root variable.
68///
69/// This provides a convenient and quick way of checking if a variable being used within
70/// a closure is a capture of a local variable.
71pub type RootVariableMinCaptureList<'tcx> = FxIndexMap<HirId, MinCaptureList<'tcx>>;
72
73/// Part of `MinCaptureInformationMap`; List of `CapturePlace`s.
74pub type MinCaptureList<'tcx> = Vec<CapturedPlace<'tcx>>;
75
76/// A composite describing a `Place` that is captured by a closure.
77#[derive(Eq, PartialEq, Clone, Debug, TyEncodable, TyDecodable, HashStable, Hash)]
78#[derive(TypeFoldable, TypeVisitable)]
79pub struct CapturedPlace<'tcx> {
80    /// Name and span where the binding happens.
81    pub var_ident: Ident,
82
83    /// The `Place` that is captured.
84    pub place: HirPlace<'tcx>,
85
86    /// `CaptureKind` and expression(s) that resulted in such capture of `place`.
87    pub info: CaptureInfo,
88
89    /// Represents if `place` can be mutated or not.
90    pub mutability: hir::Mutability,
91}
92
93impl<'tcx> CapturedPlace<'tcx> {
94    pub fn to_string(&self, tcx: TyCtxt<'tcx>) -> String {
95        place_to_string_for_capture(tcx, &self.place)
96    }
97
98    /// Returns a symbol of the captured upvar, which looks like `name__field1__field2`.
99    pub fn to_symbol(&self) -> Symbol {
100        let mut symbol = self.var_ident.to_string();
101
102        let mut ty = self.place.base_ty;
103        for proj in self.place.projections.iter() {
104            match proj.kind {
105                HirProjectionKind::Field(idx, variant) => match ty.kind() {
106                    ty::Tuple(_) => write!(&mut symbol, "__{}", idx.index()).unwrap(),
107                    ty::Adt(def, ..) => {
108                        write!(
109                            &mut symbol,
110                            "__{}",
111                            def.variant(variant).fields[idx].name.as_str(),
112                        )
113                        .unwrap();
114                    }
115                    ty => {
116                        bug!("Unexpected type {:?} for `Field` projection", ty)
117                    }
118                },
119
120                // Ignore derefs for now, as they are likely caused by
121                // autoderefs that don't appear in the original code.
122                HirProjectionKind::Deref => {}
123                // Just change the type to the hidden type, so we can actually project.
124                HirProjectionKind::OpaqueCast => {}
125                proj => bug!("Unexpected projection {:?} in captured place", proj),
126            }
127            ty = proj.ty;
128        }
129
130        Symbol::intern(&symbol)
131    }
132
133    /// Returns the hir-id of the root variable for the captured place.
134    /// e.g., if `a.b.c` was captured, would return the hir-id for `a`.
135    pub fn get_root_variable(&self) -> HirId {
136        match self.place.base {
137            HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
138            base => bug!("Expected upvar, found={:?}", base),
139        }
140    }
141
142    /// Returns the `LocalDefId` of the closure that captured this Place
143    pub fn get_closure_local_def_id(&self) -> LocalDefId {
144        match self.place.base {
145            HirPlaceBase::Upvar(upvar_id) => upvar_id.closure_expr_id,
146            base => bug!("expected upvar, found={:?}", base),
147        }
148    }
149
150    /// Return span pointing to use that resulted in selecting the captured path
151    pub fn get_path_span(&self, tcx: TyCtxt<'tcx>) -> Span {
152        if let Some(path_expr_id) = self.info.path_expr_id {
153            tcx.hir().span(path_expr_id)
154        } else if let Some(capture_kind_expr_id) = self.info.capture_kind_expr_id {
155            tcx.hir().span(capture_kind_expr_id)
156        } else {
157            // Fallback on upvars mentioned if neither path or capture expr id is captured
158
159            // Safe to unwrap since we know this place is captured by the closure, therefore the closure must have upvars.
160            tcx.upvars_mentioned(self.get_closure_local_def_id()).unwrap()
161                [&self.get_root_variable()]
162                .span
163        }
164    }
165
166    /// Return span pointing to use that resulted in selecting the current capture kind
167    pub fn get_capture_kind_span(&self, tcx: TyCtxt<'tcx>) -> Span {
168        if let Some(capture_kind_expr_id) = self.info.capture_kind_expr_id {
169            tcx.hir().span(capture_kind_expr_id)
170        } else if let Some(path_expr_id) = self.info.path_expr_id {
171            tcx.hir().span(path_expr_id)
172        } else {
173            // Fallback on upvars mentioned if neither path or capture expr id is captured
174
175            // Safe to unwrap since we know this place is captured by the closure, therefore the closure must have upvars.
176            tcx.upvars_mentioned(self.get_closure_local_def_id()).unwrap()
177                [&self.get_root_variable()]
178                .span
179        }
180    }
181
182    pub fn is_by_ref(&self) -> bool {
183        match self.info.capture_kind {
184            ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => false,
185            ty::UpvarCapture::ByRef(..) => true,
186        }
187    }
188}
189
190#[derive(Copy, Clone, Debug, HashStable)]
191pub struct ClosureTypeInfo<'tcx> {
192    user_provided_sig: ty::CanonicalPolyFnSig<'tcx>,
193    captures: &'tcx ty::List<&'tcx ty::CapturedPlace<'tcx>>,
194    kind_origin: Option<&'tcx (Span, HirPlace<'tcx>)>,
195}
196
197fn closure_typeinfo<'tcx>(tcx: TyCtxt<'tcx>, def: LocalDefId) -> ClosureTypeInfo<'tcx> {
198    debug_assert!(tcx.is_closure_like(def.to_def_id()));
199    let typeck_results = tcx.typeck(def);
200    let user_provided_sig = typeck_results.user_provided_sigs[&def];
201    let captures = typeck_results.closure_min_captures_flattened(def);
202    let captures = tcx.mk_captures_from_iter(captures);
203    let hir_id = tcx.local_def_id_to_hir_id(def);
204    let kind_origin = typeck_results.closure_kind_origins().get(hir_id);
205    ClosureTypeInfo { user_provided_sig, captures, kind_origin }
206}
207
208impl<'tcx> TyCtxt<'tcx> {
209    pub fn closure_kind_origin(self, def_id: LocalDefId) -> Option<&'tcx (Span, HirPlace<'tcx>)> {
210        self.closure_typeinfo(def_id).kind_origin
211    }
212
213    pub fn closure_user_provided_sig(self, def_id: LocalDefId) -> ty::CanonicalPolyFnSig<'tcx> {
214        self.closure_typeinfo(def_id).user_provided_sig
215    }
216
217    pub fn closure_captures(self, def_id: LocalDefId) -> &'tcx [&'tcx ty::CapturedPlace<'tcx>] {
218        if !self.is_closure_like(def_id.to_def_id()) {
219            return &[];
220        }
221        self.closure_typeinfo(def_id).captures
222    }
223}
224
225/// Return true if the `proj_possible_ancestor` represents an ancestor path
226/// to `proj_capture` or `proj_possible_ancestor` is same as `proj_capture`,
227/// assuming they both start off of the same root variable.
228///
229/// **Note:** It's the caller's responsibility to ensure that both lists of projections
230///           start off of the same root variable.
231///
232/// Eg: 1. `foo.x` which is represented using `projections=[Field(x)]` is an ancestor of
233///        `foo.x.y` which is represented using `projections=[Field(x), Field(y)]`.
234///        Note both `foo.x` and `foo.x.y` start off of the same root variable `foo`.
235///     2. Since we only look at the projections here function will return `bar.x` as a valid
236///        ancestor of `foo.x.y`. It's the caller's responsibility to ensure that both projections
237///        list are being applied to the same root variable.
238pub fn is_ancestor_or_same_capture(
239    proj_possible_ancestor: &[HirProjectionKind],
240    proj_capture: &[HirProjectionKind],
241) -> bool {
242    // We want to make sure `is_ancestor_or_same_capture("x.0.0", "x.0")` to return false.
243    // Therefore we can't just check if all projections are same in the zipped iterator below.
244    if proj_possible_ancestor.len() > proj_capture.len() {
245        return false;
246    }
247
248    proj_possible_ancestor.iter().zip(proj_capture).all(|(a, b)| a == b)
249}
250
251/// Part of `MinCaptureInformationMap`; describes the capture kind (&, &mut, move)
252/// for a particular capture as well as identifying the part of the source code
253/// that triggered this capture to occur.
254#[derive(Eq, PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, HashStable, Hash)]
255#[derive(TypeFoldable, TypeVisitable)]
256pub struct CaptureInfo {
257    /// Expr Id pointing to use that resulted in selecting the current capture kind
258    ///
259    /// Eg:
260    /// ```rust,no_run
261    /// let mut t = (0,1);
262    ///
263    /// let c = || {
264    ///     println!("{t:?}"); // L1
265    ///     t.1 = 4; // L2
266    /// };
267    /// ```
268    /// `capture_kind_expr_id` will point to the use on L2 and `path_expr_id` will point to the
269    /// use on L1.
270    ///
271    /// If the user doesn't enable feature `capture_disjoint_fields` (RFC 2229) then, it is
272    /// possible that we don't see the use of a particular place resulting in capture_kind_expr_id being
273    /// None. In such case we fallback on uvpars_mentioned for span.
274    ///
275    /// Eg:
276    /// ```rust,no_run
277    /// let x = 5;
278    ///
279    /// let c = || {
280    ///     let _ = x;
281    /// };
282    /// ```
283    ///
284    /// In this example, if `capture_disjoint_fields` is **not** set, then x will be captured,
285    /// but we won't see it being used during capture analysis, since it's essentially a discard.
286    pub capture_kind_expr_id: Option<HirId>,
287    /// Expr Id pointing to use that resulted the corresponding place being captured
288    ///
289    /// See `capture_kind_expr_id` for example.
290    ///
291    pub path_expr_id: Option<HirId>,
292
293    /// Capture mode that was selected
294    pub capture_kind: UpvarCapture,
295}
296
297pub fn place_to_string_for_capture<'tcx>(tcx: TyCtxt<'tcx>, place: &HirPlace<'tcx>) -> String {
298    let mut curr_string: String = match place.base {
299        HirPlaceBase::Upvar(upvar_id) => tcx.hir_name(upvar_id.var_path.hir_id).to_string(),
300        _ => bug!("Capture_information should only contain upvars"),
301    };
302
303    for (i, proj) in place.projections.iter().enumerate() {
304        match proj.kind {
305            HirProjectionKind::Deref => {
306                curr_string = format!("*{curr_string}");
307            }
308            HirProjectionKind::Field(idx, variant) => match place.ty_before_projection(i).kind() {
309                ty::Adt(def, ..) => {
310                    curr_string = format!(
311                        "{}.{}",
312                        curr_string,
313                        def.variant(variant).fields[idx].name.as_str()
314                    );
315                }
316                ty::Tuple(_) => {
317                    curr_string = format!("{}.{}", curr_string, idx.index());
318                }
319                _ => {
320                    bug!(
321                        "Field projection applied to a type other than Adt or Tuple: {:?}.",
322                        place.ty_before_projection(i).kind()
323                    )
324                }
325            },
326            proj => bug!("{:?} unexpected because it isn't captured", proj),
327        }
328    }
329
330    curr_string
331}
332
333#[derive(Eq, Clone, PartialEq, Debug, TyEncodable, TyDecodable, Copy, HashStable, Hash)]
334#[derive(TypeFoldable, TypeVisitable)]
335pub enum BorrowKind {
336    /// Data must be immutable and is aliasable.
337    Immutable,
338
339    /// Data must be immutable but not aliasable. This kind of borrow
340    /// cannot currently be expressed by the user and is used only in
341    /// implicit closure bindings. It is needed when the closure
342    /// is borrowing or mutating a mutable referent, e.g.:
343    ///
344    /// ```
345    /// let mut z = 3;
346    /// let x: &mut isize = &mut z;
347    /// let y = || *x += 5;
348    /// ```
349    ///
350    /// If we were to try to translate this closure into a more explicit
351    /// form, we'd encounter an error with the code as written:
352    ///
353    /// ```compile_fail,E0594
354    /// struct Env<'a> { x: &'a &'a mut isize }
355    /// let mut z = 3;
356    /// let x: &mut isize = &mut z;
357    /// let y = (&mut Env { x: &x }, fn_ptr);  // Closure is pair of env and fn
358    /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
359    /// ```
360    ///
361    /// This is then illegal because you cannot mutate a `&mut` found
362    /// in an aliasable location. To solve, you'd have to translate with
363    /// an `&mut` borrow:
364    ///
365    /// ```compile_fail,E0596
366    /// struct Env<'a> { x: &'a mut &'a mut isize }
367    /// let mut z = 3;
368    /// let x: &mut isize = &mut z;
369    /// let y = (&mut Env { x: &mut x }, fn_ptr); // changed from &x to &mut x
370    /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
371    /// ```
372    ///
373    /// Now the assignment to `**env.x` is legal, but creating a
374    /// mutable pointer to `x` is not because `x` is not mutable. We
375    /// could fix this by declaring `x` as `let mut x`. This is ok in
376    /// user code, if awkward, but extra weird for closures, since the
377    /// borrow is hidden.
378    ///
379    /// So we introduce a "unique imm" borrow -- the referent is
380    /// immutable, but not aliasable. This solves the problem. For
381    /// simplicity, we don't give users the way to express this
382    /// borrow, it's just used when translating closures.
383    ///
384    /// FIXME: Rename this to indicate the borrow is actually not immutable.
385    UniqueImmutable,
386
387    /// Data is mutable and not aliasable.
388    Mutable,
389}
390
391impl BorrowKind {
392    pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
393        match m {
394            hir::Mutability::Mut => BorrowKind::Mutable,
395            hir::Mutability::Not => BorrowKind::Immutable,
396        }
397    }
398
399    /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
400    /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
401    /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
402    /// question.
403    pub fn to_mutbl_lossy(self) -> hir::Mutability {
404        match self {
405            BorrowKind::Mutable => hir::Mutability::Mut,
406            BorrowKind::Immutable => hir::Mutability::Not,
407
408            // We have no type corresponding to a unique imm borrow, so
409            // use `&mut`. It gives all the capabilities of a `&uniq`
410            // and hence is a safe "over approximation".
411            BorrowKind::UniqueImmutable => hir::Mutability::Mut,
412        }
413    }
414}
415
416pub fn analyze_coroutine_closure_captures<'a, 'tcx: 'a, T>(
417    parent_captures: impl IntoIterator<Item = &'a CapturedPlace<'tcx>>,
418    child_captures: impl IntoIterator<Item = &'a CapturedPlace<'tcx>>,
419    mut for_each: impl FnMut((usize, &'a CapturedPlace<'tcx>), (usize, &'a CapturedPlace<'tcx>)) -> T,
420) -> impl Iterator<Item = T> {
421    std::iter::from_coroutine(
422        #[coroutine]
423        move || {
424            let mut child_captures = child_captures.into_iter().enumerate().peekable();
425
426            // One parent capture may correspond to several child captures if we end up
427            // refining the set of captures via edition-2021 precise captures. We want to
428            // match up any number of child captures with one parent capture, so we keep
429            // peeking off this `Peekable` until the child doesn't match anymore.
430            for (parent_field_idx, parent_capture) in parent_captures.into_iter().enumerate() {
431                // Make sure we use every field at least once, b/c why are we capturing something
432                // if it's not used in the inner coroutine.
433                let mut field_used_at_least_once = false;
434
435                // A parent matches a child if they share the same prefix of projections.
436                // The child may have more, if it is capturing sub-fields out of
437                // something that is captured by-move in the parent closure.
438                while child_captures.peek().is_some_and(|(_, child_capture)| {
439                    child_prefix_matches_parent_projections(parent_capture, child_capture)
440                }) {
441                    let (child_field_idx, child_capture) = child_captures.next().unwrap();
442                    // This analysis only makes sense if the parent capture is a
443                    // prefix of the child capture.
444                    assert!(
445                        child_capture.place.projections.len()
446                            >= parent_capture.place.projections.len(),
447                        "parent capture ({parent_capture:#?}) expected to be prefix of \
448                    child capture ({child_capture:#?})"
449                    );
450
451                    yield for_each(
452                        (parent_field_idx, parent_capture),
453                        (child_field_idx, child_capture),
454                    );
455
456                    field_used_at_least_once = true;
457                }
458
459                // Make sure the field was used at least once.
460                assert!(
461                    field_used_at_least_once,
462                    "we captured {parent_capture:#?} but it was not used in the child coroutine?"
463                );
464            }
465            assert_eq!(child_captures.next(), None, "leftover child captures?");
466        },
467    )
468}
469
470fn child_prefix_matches_parent_projections(
471    parent_capture: &ty::CapturedPlace<'_>,
472    child_capture: &ty::CapturedPlace<'_>,
473) -> bool {
474    let HirPlaceBase::Upvar(parent_base) = parent_capture.place.base else {
475        bug!("expected capture to be an upvar");
476    };
477    let HirPlaceBase::Upvar(child_base) = child_capture.place.base else {
478        bug!("expected capture to be an upvar");
479    };
480
481    parent_base.var_path.hir_id == child_base.var_path.hir_id
482        && std::iter::zip(&child_capture.place.projections, &parent_capture.place.projections)
483            .all(|(child, parent)| child.kind == parent.kind)
484}
485
486pub fn provide(providers: &mut Providers) {
487    *providers = Providers { closure_typeinfo, ..*providers }
488}