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