1 use crate::hir::place::{
2 Place as HirPlace, PlaceBase as HirPlaceBase, ProjectionKind as HirProjectionKind,
8 use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
10 use rustc_hir::def_id::{DefId, LocalDefId};
11 use rustc_span::{Span, Symbol};
13 use super::{Ty, TyCtxt};
15 use self::BorrowKind::*;
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);
33 pub struct UpvarPath {
34 pub hir_id: hir::HirId,
37 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
38 /// the original var ID (that is, the root variable that is referenced
39 /// by the upvar) and the ID of the closure expression.
40 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
42 pub var_path: UpvarPath,
43 pub closure_expr_id: LocalDefId,
47 pub fn new(var_hir_id: hir::HirId, closure_def_id: LocalDefId) -> UpvarId {
48 UpvarId { var_path: UpvarPath { hir_id: var_hir_id }, closure_expr_id: closure_def_id }
52 /// Information describing the capture of an upvar. This is computed
53 /// during `typeck`, specifically by `regionck`.
54 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
55 pub enum UpvarCapture {
56 /// Upvar is captured by value. This is always true when the
57 /// closure is labeled `move`, but can also be true in other cases
58 /// depending on inference.
61 /// Upvar is captured by reference.
65 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
66 pub type UpvarCaptureMap = FxHashMap<UpvarId, UpvarCapture>;
68 /// Given the closure DefId this map provides a map of root variables to minimum
69 /// set of `CapturedPlace`s that need to be tracked to support all captures of that closure.
70 pub type MinCaptureInformationMap<'tcx> = FxHashMap<DefId, RootVariableMinCaptureList<'tcx>>;
72 /// Part of `MinCaptureInformationMap`; Maps a root variable to the list of `CapturedPlace`.
73 /// Used to track the minimum set of `Place`s that need to be captured to support all
74 /// Places captured by the closure starting at a given root variable.
76 /// This provides a convenient and quick way of checking if a variable being used within
77 /// a closure is a capture of a local variable.
78 pub type RootVariableMinCaptureList<'tcx> = FxIndexMap<hir::HirId, MinCaptureList<'tcx>>;
80 /// Part of `MinCaptureInformationMap`; List of `CapturePlace`s.
81 pub type MinCaptureList<'tcx> = Vec<CapturedPlace<'tcx>>;
83 /// Represents the various closure traits in the language. This
84 /// will determine the type of the environment (`self`, in the
85 /// desugaring) argument that the closure expects.
87 /// You can get the environment type of a closure using
88 /// `tcx.closure_env_ty()`.
89 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
91 pub enum ClosureKind {
92 // Warning: Ordering is significant here! The ordering is chosen
93 // because the trait Fn is a subtrait of FnMut and so in turn, and
94 // hence we order it so that Fn < FnMut < FnOnce.
100 impl<'tcx> ClosureKind {
101 // This is the initial value used when doing upvar inference.
102 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
104 /// Returns `true` if a type that impls this closure kind
105 /// must also implement `other`.
106 pub fn extends(self, other: ty::ClosureKind) -> bool {
109 (ClosureKind::Fn, ClosureKind::Fn)
110 | (ClosureKind::Fn, ClosureKind::FnMut)
111 | (ClosureKind::Fn, ClosureKind::FnOnce)
112 | (ClosureKind::FnMut, ClosureKind::FnMut)
113 | (ClosureKind::FnMut, ClosureKind::FnOnce)
114 | (ClosureKind::FnOnce, ClosureKind::FnOnce)
118 /// Returns the representative scalar type for this closure kind.
119 /// See `Ty::to_opt_closure_kind` for more details.
120 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
122 ty::ClosureKind::Fn => tcx.types.i8,
123 ty::ClosureKind::FnMut => tcx.types.i16,
124 ty::ClosureKind::FnOnce => tcx.types.i32,
129 /// A composite describing a `Place` that is captured by a closure.
130 #[derive(PartialEq, Clone, Debug, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
131 pub struct CapturedPlace<'tcx> {
132 /// The `Place` that is captured.
133 pub place: HirPlace<'tcx>,
135 /// `CaptureKind` and expression(s) that resulted in such capture of `place`.
136 pub info: CaptureInfo,
138 /// Represents if `place` can be mutated or not.
139 pub mutability: hir::Mutability,
141 /// Region of the resulting reference if the upvar is captured by ref.
142 pub region: Option<ty::Region<'tcx>>,
145 impl<'tcx> CapturedPlace<'tcx> {
146 pub fn to_string(&self, tcx: TyCtxt<'tcx>) -> String {
147 place_to_string_for_capture(tcx, &self.place)
150 /// Returns a symbol of the captured upvar, which looks like `name__field1__field2`.
151 fn to_symbol(&self, tcx: TyCtxt<'tcx>) -> Symbol {
152 let hir_id = match self.place.base {
153 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
154 base => bug!("Expected an upvar, found {:?}", base),
156 let mut symbol = tcx.hir().name(hir_id).as_str().to_string();
158 let mut ty = self.place.base_ty;
159 for proj in self.place.projections.iter() {
161 HirProjectionKind::Field(idx, variant) => match ty.kind() {
162 ty::Tuple(_) => write!(&mut symbol, "__{}", idx).unwrap(),
163 ty::Adt(def, ..) => {
167 def.variants[variant].fields[idx as usize].name.as_str(),
172 bug!("Unexpected type {:?} for `Field` projection", ty)
176 // Ignore derefs for now, as they are likely caused by
177 // autoderefs that don't appear in the original code.
178 HirProjectionKind::Deref => {}
179 proj => bug!("Unexpected projection {:?} in captured place", proj),
184 Symbol::intern(&symbol)
187 /// Returns the hir-id of the root variable for the captured place.
188 /// e.g., if `a.b.c` was captured, would return the hir-id for `a`.
189 pub fn get_root_variable(&self) -> hir::HirId {
190 match self.place.base {
191 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
192 base => bug!("Expected upvar, found={:?}", base),
196 /// Returns the `LocalDefId` of the closure that captured this Place
197 pub fn get_closure_local_def_id(&self) -> LocalDefId {
198 match self.place.base {
199 HirPlaceBase::Upvar(upvar_id) => upvar_id.closure_expr_id,
200 base => bug!("expected upvar, found={:?}", base),
204 /// Return span pointing to use that resulted in selecting the captured path
205 pub fn get_path_span(&self, tcx: TyCtxt<'tcx>) -> Span {
206 if let Some(path_expr_id) = self.info.path_expr_id {
207 tcx.hir().span(path_expr_id)
208 } else if let Some(capture_kind_expr_id) = self.info.capture_kind_expr_id {
209 tcx.hir().span(capture_kind_expr_id)
211 // Fallback on upvars mentioned if neither path or capture expr id is captured
213 // Safe to unwrap since we know this place is captured by the closure, therefore the closure must have upvars.
214 tcx.upvars_mentioned(self.get_closure_local_def_id()).unwrap()
215 [&self.get_root_variable()]
220 /// Return span pointing to use that resulted in selecting the current capture kind
221 pub fn get_capture_kind_span(&self, tcx: TyCtxt<'tcx>) -> Span {
222 if let Some(capture_kind_expr_id) = self.info.capture_kind_expr_id {
223 tcx.hir().span(capture_kind_expr_id)
224 } else if let Some(path_expr_id) = self.info.path_expr_id {
225 tcx.hir().span(path_expr_id)
227 // Fallback on upvars mentioned if neither path or capture expr id is captured
229 // Safe to unwrap since we know this place is captured by the closure, therefore the closure must have upvars.
230 tcx.upvars_mentioned(self.get_closure_local_def_id()).unwrap()
231 [&self.get_root_variable()]
237 fn symbols_for_closure_captures<'tcx>(
239 def_id: (LocalDefId, DefId),
241 let typeck_results = tcx.typeck(def_id.0);
242 let captures = typeck_results.closure_min_captures_flattened(def_id.1);
243 captures.into_iter().map(|captured_place| captured_place.to_symbol(tcx)).collect()
246 /// Return true if the `proj_possible_ancestor` represents an ancestor path
247 /// to `proj_capture` or `proj_possible_ancestor` is same as `proj_capture`,
248 /// assuming they both start off of the same root variable.
250 /// **Note:** It's the caller's responsibility to ensure that both lists of projections
251 /// start off of the same root variable.
253 /// Eg: 1. `foo.x` which is represented using `projections=[Field(x)]` is an ancestor of
254 /// `foo.x.y` which is represented using `projections=[Field(x), Field(y)]`.
255 /// Note both `foo.x` and `foo.x.y` start off of the same root variable `foo`.
256 /// 2. Since we only look at the projections here function will return `bar.x` as an a valid
257 /// ancestor of `foo.x.y`. It's the caller's responsibility to ensure that both projections
258 /// list are being applied to the same root variable.
259 pub fn is_ancestor_or_same_capture(
260 proj_possible_ancestor: &[HirProjectionKind],
261 proj_capture: &[HirProjectionKind],
263 // We want to make sure `is_ancestor_or_same_capture("x.0.0", "x.0")` to return false.
264 // Therefore we can't just check if all projections are same in the zipped iterator below.
265 if proj_possible_ancestor.len() > proj_capture.len() {
269 proj_possible_ancestor.iter().zip(proj_capture).all(|(a, b)| a == b)
272 /// Part of `MinCaptureInformationMap`; describes the capture kind (&, &mut, move)
273 /// for a particular capture as well as identifying the part of the source code
274 /// that triggered this capture to occur.
275 #[derive(PartialEq, Clone, Debug, Copy, TyEncodable, TyDecodable, TypeFoldable, HashStable)]
276 pub struct CaptureInfo {
277 /// Expr Id pointing to use that resulted in selecting the current capture kind
281 /// let mut t = (0,1);
284 /// println!("{t}"); // L1
288 /// `capture_kind_expr_id` will point to the use on L2 and `path_expr_id` will point to the
291 /// If the user doesn't enable feature `capture_disjoint_fields` (RFC 2229) then, it is
292 /// possible that we don't see the use of a particular place resulting in capture_kind_expr_id being
293 /// None. In such case we fallback on uvpars_mentioned for span.
304 /// In this example, if `capture_disjoint_fields` is **not** set, then x will be captured,
305 /// but we won't see it being used during capture analysis, since it's essentially a discard.
306 pub capture_kind_expr_id: Option<hir::HirId>,
307 /// Expr Id pointing to use that resulted the corresponding place being captured
309 /// See `capture_kind_expr_id` for example.
311 pub path_expr_id: Option<hir::HirId>,
313 /// Capture mode that was selected
314 pub capture_kind: UpvarCapture,
317 pub fn place_to_string_for_capture<'tcx>(tcx: TyCtxt<'tcx>, place: &HirPlace<'tcx>) -> String {
318 let mut curr_string: String = match place.base {
319 HirPlaceBase::Upvar(upvar_id) => tcx.hir().name(upvar_id.var_path.hir_id).to_string(),
320 _ => bug!("Capture_information should only contain upvars"),
323 for (i, proj) in place.projections.iter().enumerate() {
325 HirProjectionKind::Deref => {
326 curr_string = format!("*{}", curr_string);
328 HirProjectionKind::Field(idx, variant) => match place.ty_before_projection(i).kind() {
329 ty::Adt(def, ..) => {
330 curr_string = format!(
333 def.variants[variant].fields[idx as usize].name.as_str()
337 curr_string = format!("{}.{}", curr_string, idx);
341 "Field projection applied to a type other than Adt or Tuple: {:?}.",
342 place.ty_before_projection(i).kind()
346 proj => bug!("{:?} unexpected because it isn't captured", proj),
353 #[derive(Clone, PartialEq, Debug, TyEncodable, TyDecodable, TypeFoldable, Copy, HashStable)]
354 pub enum BorrowKind {
355 /// Data must be immutable and is aliasable.
358 /// Data must be immutable but not aliasable. This kind of borrow
359 /// cannot currently be expressed by the user and is used only in
360 /// implicit closure bindings. It is needed when the closure
361 /// is borrowing or mutating a mutable referent, e.g.:
364 /// let x: &mut isize = ...;
365 /// let y = || *x += 5;
368 /// If we were to try to translate this closure into a more explicit
369 /// form, we'd encounter an error with the code as written:
372 /// struct Env { x: & &mut isize }
373 /// let x: &mut isize = ...;
374 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
375 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
378 /// This is then illegal because you cannot mutate a `&mut` found
379 /// in an aliasable location. To solve, you'd have to translate with
380 /// an `&mut` borrow:
383 /// struct Env { x: &mut &mut isize }
384 /// let x: &mut isize = ...;
385 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
386 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
389 /// Now the assignment to `**env.x` is legal, but creating a
390 /// mutable pointer to `x` is not because `x` is not mutable. We
391 /// could fix this by declaring `x` as `let mut x`. This is ok in
392 /// user code, if awkward, but extra weird for closures, since the
393 /// borrow is hidden.
395 /// So we introduce a "unique imm" borrow -- the referent is
396 /// immutable, but not aliasable. This solves the problem. For
397 /// simplicity, we don't give users the way to express this
398 /// borrow, it's just used when translating closures.
401 /// Data is mutable and not aliasable.
406 pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
408 hir::Mutability::Mut => MutBorrow,
409 hir::Mutability::Not => ImmBorrow,
413 /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
414 /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
415 /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
417 pub fn to_mutbl_lossy(self) -> hir::Mutability {
419 MutBorrow => hir::Mutability::Mut,
420 ImmBorrow => hir::Mutability::Not,
422 // We have no type corresponding to a unique imm borrow, so
423 // use `&mut`. It gives all the capabilities of a `&uniq`
424 // and hence is a safe "over approximation".
425 UniqueImmBorrow => hir::Mutability::Mut,
430 pub fn provide(providers: &mut ty::query::Providers) {
431 *providers = ty::query::Providers { symbols_for_closure_captures, ..*providers }