1 //! This file declares the `ScopeTree` type, which describes
2 //! the parent links in the region hierarchy.
4 //! For more information about how MIR-based region-checking works,
5 //! see the [rustc dev guide].
7 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/borrow_check.html
10 use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
11 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
14 use rustc_macros::HashStable;
15 use rustc_query_system::ich::StableHashingContext;
16 use rustc_span::{Span, DUMMY_SP};
21 /// Represents a statically-describable scope that can be used to
22 /// bound the lifetime/region for values.
24 /// `Node(node_id)`: Any AST node that has any scope at all has the
25 /// `Node(node_id)` scope. Other variants represent special cases not
26 /// immediately derivable from the abstract syntax tree structure.
28 /// `DestructionScope(node_id)` represents the scope of destructors
29 /// implicitly-attached to `node_id` that run immediately after the
30 /// expression for `node_id` itself. Not every AST node carries a
31 /// `DestructionScope`, but those that are `terminating_scopes` do;
32 /// see discussion with `ScopeTree`.
34 /// `Remainder { block, statement_index }` represents
35 /// the scope of user code running immediately after the initializer
36 /// expression for the indexed statement, until the end of the block.
38 /// So: the following code can be broken down into the scopes beneath:
41 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
45 /// +---------+ (R10.)
47 /// +----------+ (M8.)
48 /// +----------------------+ (R7.)
50 /// +----------+ (M5.)
51 /// +-----------------------------------+ (M4.)
52 /// +--------------------------------------------------+ (M3.)
54 /// +-----------------------------------------------------------+ (M1.)
56 /// (M1.): Node scope of the whole `let a = ...;` statement.
57 /// (M2.): Node scope of the `f()` expression.
58 /// (M3.): Node scope of the `f().g(..)` expression.
59 /// (M4.): Node scope of the block labeled `'b:`.
60 /// (M5.): Node scope of the `let x = d();` statement
61 /// (D6.): DestructionScope for temporaries created during M5.
62 /// (R7.): Remainder scope for block `'b:`, stmt 0 (let x = ...).
63 /// (M8.): Node scope of the `let y = d();` statement.
64 /// (D9.): DestructionScope for temporaries created during M8.
65 /// (R10.): Remainder scope for block `'b:`, stmt 1 (let y = ...).
66 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
67 /// (D12.): DestructionScope for temporaries created during M1 (e.g., f()).
70 /// Note that while the above picture shows the destruction scopes
71 /// as following their corresponding node scopes, in the internal
72 /// data structures of the compiler the destruction scopes are
73 /// represented as enclosing parents. This is sound because we use the
74 /// enclosing parent relationship just to ensure that referenced
75 /// values live long enough; phrased another way, the starting point
76 /// of each range is not really the important thing in the above
77 /// picture, but rather the ending point.
79 // FIXME(pnkfelix): this currently derives `PartialOrd` and `Ord` to
80 // placate the same deriving in `ty::FreeRegion`, but we may want to
81 // actually attach a more meaningful ordering to scopes than the one
82 // generated via deriving here.
83 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy, TyEncodable, TyDecodable)]
86 pub id: hir::ItemLocalId,
90 impl fmt::Debug for Scope {
91 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
93 ScopeData::Node => write!(fmt, "Node({:?})", self.id),
94 ScopeData::CallSite => write!(fmt, "CallSite({:?})", self.id),
95 ScopeData::Arguments => write!(fmt, "Arguments({:?})", self.id),
96 ScopeData::Destruction => write!(fmt, "Destruction({:?})", self.id),
97 ScopeData::IfThen => write!(fmt, "IfThen({:?})", self.id),
98 ScopeData::Remainder(fsi) => write!(
100 "Remainder {{ block: {:?}, first_statement_index: {}}}",
108 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, TyEncodable, TyDecodable)]
109 #[derive(HashStable)]
113 /// Scope of the call-site for a function or closure
114 /// (outlives the arguments as well as the body).
117 /// Scope of arguments passed to a function or closure
118 /// (they outlive its body).
121 /// Scope of destructors for temporaries of node-id.
124 /// Scope of the condition and then block of an if expression
125 /// Used for variables introduced in an if-let expression.
128 /// Scope following a `let id = expr;` binding in a block.
129 Remainder(FirstStatementIndex),
132 rustc_index::newtype_index! {
133 /// Represents a subscope of `block` for a binding that is introduced
134 /// by `block.stmts[first_statement_index]`. Such subscopes represent
135 /// a suffix of the block. Note that each subscope does not include
136 /// the initializer expression, if any, for the statement indexed by
137 /// `first_statement_index`.
139 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
141 /// * The subscope with `first_statement_index == 0` is scope of both
142 /// `a` and `b`; it does not include EXPR_1, but does include
143 /// everything after that first `let`. (If you want a scope that
144 /// includes EXPR_1 as well, then do not use `Scope::Remainder`,
145 /// but instead another `Scope` that encompasses the whole block,
146 /// e.g., `Scope::Node`.
148 /// * The subscope with `first_statement_index == 1` is scope of `c`,
149 /// and thus does not include EXPR_2, but covers the `...`.
150 #[derive(HashStable)]
151 pub struct FirstStatementIndex {}
154 // compilation error if size of `ScopeData` is not the same as a `u32`
155 static_assert_size!(ScopeData, 4);
158 /// Returns an item-local ID associated with this scope.
160 /// N.B., likely to be replaced as API is refined; e.g., pnkfelix
161 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
162 pub fn item_local_id(&self) -> hir::ItemLocalId {
166 pub fn hir_id(&self, scope_tree: &ScopeTree) -> Option<hir::HirId> {
169 .map(|hir_id| hir::HirId { owner: hir_id.owner, local_id: self.item_local_id() })
172 /// Returns the span of this `Scope`. Note that in general the
173 /// returned span may not correspond to the span of any `NodeId` in
175 pub fn span(&self, tcx: TyCtxt<'_>, scope_tree: &ScopeTree) -> Span {
176 let Some(hir_id) = self.hir_id(scope_tree) else {
179 let span = tcx.hir().span(hir_id);
180 if let ScopeData::Remainder(first_statement_index) = self.data {
181 if let Node::Block(ref blk) = tcx.hir().get(hir_id) {
182 // Want span for scope starting after the
183 // indexed statement and ending at end of
184 // `blk`; reuse span of `blk` and shift `lo`
185 // forward to end of indexed statement.
187 // (This is the special case alluded to in the
188 // doc-comment for this method)
190 let stmt_span = blk.stmts[first_statement_index.index()].span;
192 // To avoid issues with macro-generated spans, the span
193 // of the statement must be nested in that of the block.
194 if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() {
195 return span.with_lo(stmt_span.lo());
203 pub type ScopeDepth = u32;
205 /// The region scope tree encodes information about region relationships.
206 #[derive(TyEncodable, TyDecodable, Default, Debug)]
207 pub struct ScopeTree {
208 /// If not empty, this body is the root of this region hierarchy.
209 pub root_body: Option<hir::HirId>,
211 /// Maps from a scope ID to the enclosing scope id;
212 /// this is usually corresponding to the lexical nesting, though
213 /// in the case of closures the parent scope is the innermost
214 /// conditional expression or repeating block. (Note that the
215 /// enclosing scope ID for the block associated with a closure is
216 /// the closure itself.)
217 pub parent_map: FxIndexMap<Scope, (Scope, ScopeDepth)>,
219 /// Maps from a variable or binding ID to the block in which that
220 /// variable is declared.
221 var_map: FxIndexMap<hir::ItemLocalId, Scope>,
223 /// Maps from a `NodeId` to the associated destruction scope (if any).
224 destruction_scopes: FxIndexMap<hir::ItemLocalId, Scope>,
226 /// Identifies expressions which, if captured into a temporary, ought to
227 /// have a temporary whose lifetime extends to the end of the enclosing *block*,
228 /// and not the enclosing *statement*. Expressions that are not present in this
229 /// table are not rvalue candidates. The set of rvalue candidates is computed
230 /// during type check based on a traversal of the AST.
231 pub rvalue_candidates: FxHashMap<hir::HirId, RvalueCandidateType>,
233 /// If there are any `yield` nested within a scope, this map
234 /// stores the `Span` of the last one and its index in the
235 /// postorder of the Visitor traversal on the HIR.
237 /// HIR Visitor postorder indexes might seem like a peculiar
238 /// thing to care about. but it turns out that HIR bindings
239 /// and the temporary results of HIR expressions are never
240 /// storage-live at the end of HIR nodes with postorder indexes
241 /// lower than theirs, and therefore don't need to be suspended
242 /// at yield-points at these indexes.
244 /// For an example, suppose we have some code such as:
245 /// ```rust,ignore (example)
246 /// foo(f(), yield y, bar(g()))
249 /// With the HIR tree (calls numbered for expository purposes)
252 /// Call#0(foo, [Call#1(f), Yield(y), Call#2(bar, Call#3(g))])
255 /// Obviously, the result of `f()` was created before the yield
256 /// (and therefore needs to be kept valid over the yield) while
257 /// the result of `g()` occurs after the yield (and therefore
258 /// doesn't). If we want to infer that, we can look at the
259 /// postorder traversal:
261 /// `foo` `f` Call#1 `y` Yield `bar` `g` Call#3 Call#2 Call#0
264 /// In which we can easily see that `Call#1` occurs before the yield,
265 /// and `Call#3` after it.
267 /// To see that this method works, consider:
269 /// Let `D` be our binding/temporary and `U` be our other HIR node, with
270 /// `HIR-postorder(U) < HIR-postorder(D)`. Suppose, as in our example,
271 /// U is the yield and D is one of the calls.
272 /// Let's show that `D` is storage-dead at `U`.
274 /// Remember that storage-live/storage-dead refers to the state of
275 /// the *storage*, and does not consider moves/drop flags.
279 /// 1. From the ordering guarantee of HIR visitors (see
280 /// `rustc_hir::intravisit`), `D` does not dominate `U`.
282 /// 2. Therefore, `D` is *potentially* storage-dead at `U` (because
283 /// we might visit `U` without ever getting to `D`).
285 /// 3. However, we guarantee that at each HIR point, each
286 /// binding/temporary is always either always storage-live
287 /// or always storage-dead. This is what is being guaranteed
288 /// by `terminating_scopes` including all blocks where the
289 /// count of executions is not guaranteed.
291 /// 4. By `2.` and `3.`, `D` is *statically* storage-dead at `U`,
294 /// This property ought to not on (3) in an essential way -- it
295 /// is probably still correct even if we have "unrestricted" terminating
296 /// scopes. However, why use the complicated proof when a simple one
299 /// A subtle thing: `box` expressions, such as `box (&x, yield 2, &y)`. It
300 /// might seem that a `box` expression creates a `Box<T>` temporary
301 /// when it *starts* executing, at `HIR-preorder(BOX-EXPR)`. That might
302 /// be true in the MIR desugaring, but it is not important in the semantics.
304 /// The reason is that semantically, until the `box` expression returns,
305 /// the values are still owned by their containing expressions. So
306 /// we'll see that `&x`.
307 pub yield_in_scope: FxHashMap<Scope, Vec<YieldData>>,
309 /// The number of visit_expr and visit_pat calls done in the body.
310 /// Used to sanity check visit_expr/visit_pat call count when
311 /// calculating generator interiors.
312 pub body_expr_count: FxHashMap<hir::BodyId, usize>,
315 /// Identifies the reason that a given expression is an rvalue candidate
316 /// (see the `rvalue_candidates` field for more information what rvalue
317 /// candidates in general). In constants, the `lifetime` field is None
318 /// to indicate that certain expressions escape into 'static and
319 /// should have no local cleanup scope.
320 #[derive(Debug, Copy, Clone, TyEncodable, TyDecodable, HashStable)]
321 pub enum RvalueCandidateType {
322 Borrow { target: hir::ItemLocalId, lifetime: Option<Scope> },
323 Pattern { target: hir::ItemLocalId, lifetime: Option<Scope> },
326 #[derive(Debug, Copy, Clone, TyEncodable, TyDecodable, HashStable)]
327 pub struct YieldData {
328 /// The `Span` of the yield.
330 /// The number of expressions and patterns appearing before the `yield` in the body, plus one.
331 pub expr_and_pat_count: usize,
332 pub source: hir::YieldSource,
336 pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) {
337 debug!("{:?}.parent = {:?}", child, parent);
339 if let Some(p) = parent {
340 let prev = self.parent_map.insert(child, p);
341 assert!(prev.is_none());
344 // Record the destruction scopes for later so we can query them.
345 if let ScopeData::Destruction = child.data {
346 self.destruction_scopes.insert(child.item_local_id(), child);
350 pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option<Scope> {
351 self.destruction_scopes.get(&n).cloned()
354 pub fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) {
355 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
356 assert!(var != lifetime.item_local_id());
357 self.var_map.insert(var, lifetime);
360 pub fn record_rvalue_candidate(
363 candidate_type: RvalueCandidateType,
365 debug!("record_rvalue_candidate(var={var:?}, type={candidate_type:?})");
366 match &candidate_type {
367 RvalueCandidateType::Borrow { lifetime: Some(lifetime), .. }
368 | RvalueCandidateType::Pattern { lifetime: Some(lifetime), .. } => {
369 assert!(var.local_id != lifetime.item_local_id())
373 self.rvalue_candidates.insert(var, candidate_type);
376 /// Returns the narrowest scope that encloses `id`, if any.
377 pub fn opt_encl_scope(&self, id: Scope) -> Option<Scope> {
378 self.parent_map.get(&id).cloned().map(|(p, _)| p)
381 /// Returns the lifetime of the local variable `var_id`, if any.
382 pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Option<Scope> {
383 self.var_map.get(&var_id).cloned()
386 /// Returns `true` if `subscope` is equal to or is lexically nested inside `superscope`, and
387 /// `false` otherwise.
390 pub fn is_subscope_of(&self, subscope: Scope, superscope: Scope) -> bool {
391 let mut s = subscope;
392 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
393 while superscope != s {
394 match self.opt_encl_scope(s) {
396 debug!("is_subscope_of({:?}, {:?}, s={:?})=false", subscope, superscope, s);
399 Some(scope) => s = scope,
403 debug!("is_subscope_of({:?}, {:?})=true", subscope, superscope);
408 /// Checks whether the given scope contains a `yield`. If so,
409 /// returns `Some(YieldData)`. If not, returns `None`.
410 pub fn yield_in_scope(&self, scope: Scope) -> Option<&[YieldData]> {
411 self.yield_in_scope.get(&scope).map(Deref::deref)
414 /// Gives the number of expressions visited in a body.
415 /// Used to sanity check visit_expr call count when
416 /// calculating generator interiors.
417 pub fn body_expr_count(&self, body_id: hir::BodyId) -> Option<usize> {
418 self.body_expr_count.get(&body_id).copied()
422 impl<'a> HashStable<StableHashingContext<'a>> for ScopeTree {
423 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
429 ref destruction_scopes,
430 ref rvalue_candidates,
434 root_body.hash_stable(hcx, hasher);
435 body_expr_count.hash_stable(hcx, hasher);
436 parent_map.hash_stable(hcx, hasher);
437 var_map.hash_stable(hcx, hasher);
438 destruction_scopes.hash_stable(hcx, hasher);
439 rvalue_candidates.hash_stable(hcx, hasher);
440 yield_in_scope.hash_stable(hcx, hasher);