]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/middle/region.rs
Fix drop handling for `if let` expressions
[rust.git] / compiler / rustc_middle / src / middle / region.rs
1 //! This file declares the `ScopeTree` type, which describes
2 //! the parent links in the region hierarchy.
3 //!
4 //! For more information about how MIR-based region-checking works,
5 //! see the [rustc dev guide].
6 //!
7 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/borrow_check.html
8
9 use crate::ich::{NodeIdHashingMode, StableHashingContext};
10 use crate::ty::TyCtxt;
11 use rustc_hir as hir;
12 use rustc_hir::Node;
13
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
16 use rustc_macros::HashStable;
17 use rustc_span::{Span, DUMMY_SP};
18
19 use std::fmt;
20
21 /// Represents a statically-describable scope that can be used to
22 /// bound the lifetime/region for values.
23 ///
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.
27 ///
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`.
33 ///
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.
37 ///
38 /// So: the following code can be broken down into the scopes beneath:
39 ///
40 /// ```text
41 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y)  }   ) ;
42 ///
43 ///                                                              +-+ (D12.)
44 ///                                                        +-+       (D11.)
45 ///                                              +---------+         (R10.)
46 ///                                              +-+                  (D9.)
47 ///                                   +----------+                    (M8.)
48 ///                                 +----------------------+          (R7.)
49 ///                                 +-+                               (D6.)
50 ///                      +----------+                                 (M5.)
51 ///                    +-----------------------------------+          (M4.)
52 ///         +--------------------------------------------------+      (M3.)
53 ///         +--+                                                      (M2.)
54 /// +-----------------------------------------------------------+     (M1.)
55 ///
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()).
68 /// ```
69 ///
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.
78 //
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)]
84 #[derive(HashStable)]
85 pub struct Scope {
86     pub id: hir::ItemLocalId,
87     pub data: ScopeData,
88 }
89
90 impl fmt::Debug for Scope {
91     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
92         match self.data {
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!(
99                 fmt,
100                 "Remainder {{ block: {:?}, first_statement_index: {}}}",
101                 self.id,
102                 fsi.as_u32(),
103             ),
104         }
105     }
106 }
107
108 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, TyEncodable, TyDecodable)]
109 #[derive(HashStable)]
110 pub enum ScopeData {
111     Node,
112
113     /// Scope of the call-site for a function or closure
114     /// (outlives the arguments as well as the body).
115     CallSite,
116
117     /// Scope of arguments passed to a function or closure
118     /// (they outlive its body).
119     Arguments,
120
121     /// Scope of destructors for temporaries of node-id.
122     Destruction,
123
124     /// Scope of the condition and then block of an if expression
125     /// Used for variables introduced in an if-let expression.
126     IfThen,
127
128     /// Scope following a `let id = expr;` binding in a block.
129     Remainder(FirstStatementIndex),
130 }
131
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`.
138     ///
139     /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
140     ///
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`.
147     ///
148     /// * The subscope with `first_statement_index == 1` is scope of `c`,
149     ///   and thus does not include EXPR_2, but covers the `...`.
150     pub struct FirstStatementIndex {
151         derive [HashStable]
152     }
153 }
154
155 // compilation error if size of `ScopeData` is not the same as a `u32`
156 static_assert_size!(ScopeData, 4);
157
158 impl Scope {
159     /// Returns an item-local ID associated with this scope.
160     ///
161     /// N.B., likely to be replaced as API is refined; e.g., pnkfelix
162     /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
163     pub fn item_local_id(&self) -> hir::ItemLocalId {
164         self.id
165     }
166
167     pub fn hir_id(&self, scope_tree: &ScopeTree) -> Option<hir::HirId> {
168         scope_tree
169             .root_body
170             .map(|hir_id| hir::HirId { owner: hir_id.owner, local_id: self.item_local_id() })
171     }
172
173     /// Returns the span of this `Scope`. Note that in general the
174     /// returned span may not correspond to the span of any `NodeId` in
175     /// the AST.
176     pub fn span(&self, tcx: TyCtxt<'_>, scope_tree: &ScopeTree) -> Span {
177         let hir_id = match self.hir_id(scope_tree) {
178             Some(hir_id) => hir_id,
179             None => return DUMMY_SP,
180         };
181         let span = tcx.hir().span(hir_id);
182         if let ScopeData::Remainder(first_statement_index) = self.data {
183             if let Node::Block(ref blk) = tcx.hir().get(hir_id) {
184                 // Want span for scope starting after the
185                 // indexed statement and ending at end of
186                 // `blk`; reuse span of `blk` and shift `lo`
187                 // forward to end of indexed statement.
188                 //
189                 // (This is the special case alluded to in the
190                 // doc-comment for this method)
191
192                 let stmt_span = blk.stmts[first_statement_index.index()].span;
193
194                 // To avoid issues with macro-generated spans, the span
195                 // of the statement must be nested in that of the block.
196                 if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() {
197                     return span.with_lo(stmt_span.lo());
198                 }
199             }
200         }
201         span
202     }
203 }
204
205 pub type ScopeDepth = u32;
206
207 /// The region scope tree encodes information about region relationships.
208 #[derive(Default, Debug)]
209 pub struct ScopeTree {
210     /// If not empty, this body is the root of this region hierarchy.
211     pub root_body: Option<hir::HirId>,
212
213     /// The parent of the root body owner, if the latter is an
214     /// an associated const or method, as impls/traits can also
215     /// have lifetime parameters free in this body.
216     pub root_parent: Option<hir::HirId>,
217
218     /// Maps from a scope ID to the enclosing scope id;
219     /// this is usually corresponding to the lexical nesting, though
220     /// in the case of closures the parent scope is the innermost
221     /// conditional expression or repeating block. (Note that the
222     /// enclosing scope ID for the block associated with a closure is
223     /// the closure itself.)
224     pub parent_map: FxHashMap<Scope, (Scope, ScopeDepth)>,
225
226     /// Maps from a variable or binding ID to the block in which that
227     /// variable is declared.
228     var_map: FxHashMap<hir::ItemLocalId, Scope>,
229
230     /// Maps from a `NodeId` to the associated destruction scope (if any).
231     destruction_scopes: FxHashMap<hir::ItemLocalId, Scope>,
232
233     /// `rvalue_scopes` includes entries for those expressions whose
234     /// cleanup scope is larger than the default. The map goes from the
235     /// expression ID to the cleanup scope id. For rvalues not present in
236     /// this table, the appropriate cleanup scope is the innermost
237     /// enclosing statement, conditional expression, or repeating
238     /// block (see `terminating_scopes`).
239     /// In constants, None is used to indicate that certain expressions
240     /// escape into 'static and should have no local cleanup scope.
241     rvalue_scopes: FxHashMap<hir::ItemLocalId, Option<Scope>>,
242
243     /// If there are any `yield` nested within a scope, this map
244     /// stores the `Span` of the last one and its index in the
245     /// postorder of the Visitor traversal on the HIR.
246     ///
247     /// HIR Visitor postorder indexes might seem like a peculiar
248     /// thing to care about. but it turns out that HIR bindings
249     /// and the temporary results of HIR expressions are never
250     /// storage-live at the end of HIR nodes with postorder indexes
251     /// lower than theirs, and therefore don't need to be suspended
252     /// at yield-points at these indexes.
253     ///
254     /// For an example, suppose we have some code such as:
255     /// ```rust,ignore (example)
256     ///     foo(f(), yield y, bar(g()))
257     /// ```
258     ///
259     /// With the HIR tree (calls numbered for expository purposes)
260     /// ```
261     ///     Call#0(foo, [Call#1(f), Yield(y), Call#2(bar, Call#3(g))])
262     /// ```
263     ///
264     /// Obviously, the result of `f()` was created before the yield
265     /// (and therefore needs to be kept valid over the yield) while
266     /// the result of `g()` occurs after the yield (and therefore
267     /// doesn't). If we want to infer that, we can look at the
268     /// postorder traversal:
269     /// ```plain,ignore
270     ///     `foo` `f` Call#1 `y` Yield `bar` `g` Call#3 Call#2 Call#0
271     /// ```
272     ///
273     /// In which we can easily see that `Call#1` occurs before the yield,
274     /// and `Call#3` after it.
275     ///
276     /// To see that this method works, consider:
277     ///
278     /// Let `D` be our binding/temporary and `U` be our other HIR node, with
279     /// `HIR-postorder(U) < HIR-postorder(D)`. Suppose, as in our example,
280     /// U is the yield and D is one of the calls.
281     /// Let's show that `D` is storage-dead at `U`.
282     ///
283     /// Remember that storage-live/storage-dead refers to the state of
284     /// the *storage*, and does not consider moves/drop flags.
285     ///
286     /// Then:
287     ///
288     ///   1. From the ordering guarantee of HIR visitors (see
289     ///   `rustc_hir::intravisit`), `D` does not dominate `U`.
290     ///
291     ///   2. Therefore, `D` is *potentially* storage-dead at `U` (because
292     ///   we might visit `U` without ever getting to `D`).
293     ///
294     ///   3. However, we guarantee that at each HIR point, each
295     ///   binding/temporary is always either always storage-live
296     ///   or always storage-dead. This is what is being guaranteed
297     ///   by `terminating_scopes` including all blocks where the
298     ///   count of executions is not guaranteed.
299     ///
300     ///   4. By `2.` and `3.`, `D` is *statically* storage-dead at `U`,
301     ///   QED.
302     ///
303     /// This property ought to not on (3) in an essential way -- it
304     /// is probably still correct even if we have "unrestricted" terminating
305     /// scopes. However, why use the complicated proof when a simple one
306     /// works?
307     ///
308     /// A subtle thing: `box` expressions, such as `box (&x, yield 2, &y)`. It
309     /// might seem that a `box` expression creates a `Box<T>` temporary
310     /// when it *starts* executing, at `HIR-preorder(BOX-EXPR)`. That might
311     /// be true in the MIR desugaring, but it is not important in the semantics.
312     ///
313     /// The reason is that semantically, until the `box` expression returns,
314     /// the values are still owned by their containing expressions. So
315     /// we'll see that `&x`.
316     pub yield_in_scope: FxHashMap<Scope, YieldData>,
317
318     /// The number of visit_expr and visit_pat calls done in the body.
319     /// Used to sanity check visit_expr/visit_pat call count when
320     /// calculating generator interiors.
321     pub body_expr_count: FxHashMap<hir::BodyId, usize>,
322 }
323
324 #[derive(Debug, Copy, Clone, TyEncodable, TyDecodable, HashStable)]
325 pub struct YieldData {
326     /// The `Span` of the yield.
327     pub span: Span,
328     /// The number of expressions and patterns appearing before the `yield` in the body, plus one.
329     pub expr_and_pat_count: usize,
330     pub source: hir::YieldSource,
331 }
332
333 impl ScopeTree {
334     pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) {
335         debug!("{:?}.parent = {:?}", child, parent);
336
337         if let Some(p) = parent {
338             let prev = self.parent_map.insert(child, p);
339             assert!(prev.is_none());
340         }
341
342         // Record the destruction scopes for later so we can query them.
343         if let ScopeData::Destruction = child.data {
344             self.destruction_scopes.insert(child.item_local_id(), child);
345         }
346     }
347
348     pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option<Scope> {
349         self.destruction_scopes.get(&n).cloned()
350     }
351
352     pub fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) {
353         debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
354         assert!(var != lifetime.item_local_id());
355         self.var_map.insert(var, lifetime);
356     }
357
358     pub fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option<Scope>) {
359         debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
360         if let Some(lifetime) = lifetime {
361             assert!(var != lifetime.item_local_id());
362         }
363         self.rvalue_scopes.insert(var, lifetime);
364     }
365
366     /// Returns the narrowest scope that encloses `id`, if any.
367     pub fn opt_encl_scope(&self, id: Scope) -> Option<Scope> {
368         self.parent_map.get(&id).cloned().map(|(p, _)| p)
369     }
370
371     /// Returns the lifetime of the local variable `var_id`
372     pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope {
373         self.var_map
374             .get(&var_id)
375             .cloned()
376             .unwrap_or_else(|| bug!("no enclosing scope for id {:?}", var_id))
377     }
378
379     /// Returns the scope when the temp created by `expr_id` will be cleaned up.
380     pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> {
381         // Check for a designated rvalue scope.
382         if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
383             debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
384             return s;
385         }
386
387         // Otherwise, locate the innermost terminating scope
388         // if there's one. Static items, for instance, won't
389         // have an enclosing scope, hence no scope will be
390         // returned.
391         let mut id = Scope { id: expr_id, data: ScopeData::Node };
392
393         while let Some(&(p, _)) = self.parent_map.get(&id) {
394             match p.data {
395                 ScopeData::Destruction => {
396                     debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id);
397                     return Some(id);
398                 }
399                 _ => id = p,
400             }
401         }
402
403         debug!("temporary_scope({:?}) = None", expr_id);
404         None
405     }
406
407     /// Returns `true` if `subscope` is equal to or is lexically nested inside `superscope`, and
408     /// `false` otherwise.
409     ///
410     /// Used by clippy.
411     pub fn is_subscope_of(&self, subscope: Scope, superscope: Scope) -> bool {
412         let mut s = subscope;
413         debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
414         while superscope != s {
415             match self.opt_encl_scope(s) {
416                 None => {
417                     debug!("is_subscope_of({:?}, {:?}, s={:?})=false", subscope, superscope, s);
418                     return false;
419                 }
420                 Some(scope) => s = scope,
421             }
422         }
423
424         debug!("is_subscope_of({:?}, {:?})=true", subscope, superscope);
425
426         true
427     }
428
429     /// Checks whether the given scope contains a `yield`. If so,
430     /// returns `Some(YieldData)`. If not, returns `None`.
431     pub fn yield_in_scope(&self, scope: Scope) -> Option<YieldData> {
432         self.yield_in_scope.get(&scope).cloned()
433     }
434
435     /// Gives the number of expressions visited in a body.
436     /// Used to sanity check visit_expr call count when
437     /// calculating generator interiors.
438     pub fn body_expr_count(&self, body_id: hir::BodyId) -> Option<usize> {
439         self.body_expr_count.get(&body_id).copied()
440     }
441 }
442
443 impl<'a> HashStable<StableHashingContext<'a>> for ScopeTree {
444     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
445         let ScopeTree {
446             root_body,
447             root_parent,
448             ref body_expr_count,
449             ref parent_map,
450             ref var_map,
451             ref destruction_scopes,
452             ref rvalue_scopes,
453             ref yield_in_scope,
454         } = *self;
455
456         hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
457             root_body.hash_stable(hcx, hasher);
458             root_parent.hash_stable(hcx, hasher);
459         });
460
461         body_expr_count.hash_stable(hcx, hasher);
462         parent_map.hash_stable(hcx, hasher);
463         var_map.hash_stable(hcx, hasher);
464         destruction_scopes.hash_stable(hcx, hasher);
465         rvalue_scopes.hash_stable(hcx, hasher);
466         yield_in_scope.hash_stable(hcx, hasher);
467     }
468 }