]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/block.rs
Rollup merge of #101011 - BlackHoleFox:apple-random-improvements, r=thomcc
[rust.git] / compiler / rustc_mir_build / src / build / block.rs
1 use crate::build::matches::ArmHasGuard;
2 use crate::build::ForGuard::OutsideGuard;
3 use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
4 use rustc_middle::middle::region::Scope;
5 use rustc_middle::thir::*;
6 use rustc_middle::{mir::*, ty};
7 use rustc_span::Span;
8
9 impl<'a, 'tcx> Builder<'a, 'tcx> {
10     pub(crate) fn ast_block(
11         &mut self,
12         destination: Place<'tcx>,
13         block: BasicBlock,
14         ast_block: BlockId,
15         source_info: SourceInfo,
16     ) -> BlockAnd<()> {
17         let Block {
18             region_scope,
19             opt_destruction_scope,
20             span,
21             ref stmts,
22             expr,
23             targeted_by_break,
24             safety_mode,
25         } = self.thir[ast_block];
26         let expr = expr.map(|expr| &self.thir[expr]);
27         self.in_opt_scope(opt_destruction_scope.map(|de| (de, source_info)), move |this| {
28             this.in_scope((region_scope, source_info), LintLevel::Inherited, move |this| {
29                 if targeted_by_break {
30                     this.in_breakable_scope(None, destination, span, |this| {
31                         Some(this.ast_block_stmts(
32                             destination,
33                             block,
34                             span,
35                             &stmts,
36                             expr,
37                             safety_mode,
38                             region_scope,
39                         ))
40                     })
41                 } else {
42                     this.ast_block_stmts(
43                         destination,
44                         block,
45                         span,
46                         &stmts,
47                         expr,
48                         safety_mode,
49                         region_scope,
50                     )
51                 }
52             })
53         })
54     }
55
56     fn ast_block_stmts(
57         &mut self,
58         destination: Place<'tcx>,
59         mut block: BasicBlock,
60         span: Span,
61         stmts: &[StmtId],
62         expr: Option<&Expr<'tcx>>,
63         safety_mode: BlockSafety,
64         region_scope: Scope,
65     ) -> BlockAnd<()> {
66         let this = self;
67
68         // This convoluted structure is to avoid using recursion as we walk down a list
69         // of statements. Basically, the structure we get back is something like:
70         //
71         //    let x = <init> in {
72         //       expr1;
73         //       let y = <init> in {
74         //           expr2;
75         //           expr3;
76         //           ...
77         //       }
78         //    }
79         //
80         // The let bindings are valid till the end of block so all we have to do is to pop all
81         // the let-scopes at the end.
82         //
83         // First we build all the statements in the block.
84         let mut let_scope_stack = Vec::with_capacity(8);
85         let outer_source_scope = this.source_scope;
86         let outer_in_scope_unsafe = this.in_scope_unsafe;
87         // This scope information is kept for breaking out of the parent remainder scope in case
88         // one let-else pattern matching fails.
89         // By doing so, we can be sure that even temporaries that receive extended lifetime
90         // assignments are dropped, too.
91         let mut last_remainder_scope = region_scope;
92         this.update_source_scope_for_safety_mode(span, safety_mode);
93
94         let source_info = this.source_info(span);
95         for stmt in stmts {
96             let Stmt { ref kind, opt_destruction_scope } = this.thir[*stmt];
97             match kind {
98                 StmtKind::Expr { scope, expr } => {
99                     this.block_context.push(BlockFrame::Statement { ignores_expr_result: true });
100                     unpack!(
101                         block = this.in_opt_scope(
102                             opt_destruction_scope.map(|de| (de, source_info)),
103                             |this| {
104                                 let si = (*scope, source_info);
105                                 this.in_scope(si, LintLevel::Inherited, |this| {
106                                     this.stmt_expr(block, &this.thir[*expr], Some(*scope))
107                                 })
108                             }
109                         )
110                     );
111                 }
112                 StmtKind::Let {
113                     remainder_scope,
114                     init_scope,
115                     ref pattern,
116                     initializer,
117                     lint_level,
118                     else_block,
119                 } => {
120                     let ignores_expr_result = matches!(*pattern.kind, PatKind::Wild);
121                     this.block_context.push(BlockFrame::Statement { ignores_expr_result });
122
123                     // Enter the remainder scope, i.e., the bindings' destruction scope.
124                     this.push_scope((*remainder_scope, source_info));
125                     let_scope_stack.push(remainder_scope);
126
127                     // Declare the bindings, which may create a source scope.
128                     let remainder_span = remainder_scope.span(this.tcx, this.region_scope_tree);
129
130                     let visibility_scope =
131                         Some(this.new_source_scope(remainder_span, LintLevel::Inherited, None));
132
133                     // Evaluate the initializer, if present.
134                     if let Some(init) = initializer {
135                         let init = &this.thir[*init];
136                         let initializer_span = init.span;
137
138                         unpack!(
139                             block = this.in_opt_scope(
140                                 opt_destruction_scope.map(|de| (de, source_info)),
141                                 |this| {
142                                     let scope = (*init_scope, source_info);
143                                     this.in_scope(scope, *lint_level, |this| {
144                                         if let Some(else_block) = else_block {
145                                             this.ast_let_else(
146                                                 block,
147                                                 init,
148                                                 initializer_span,
149                                                 *else_block,
150                                                 visibility_scope,
151                                                 last_remainder_scope,
152                                                 remainder_span,
153                                                 pattern,
154                                             )
155                                         } else {
156                                             this.declare_bindings(
157                                                 visibility_scope,
158                                                 remainder_span,
159                                                 pattern,
160                                                 ArmHasGuard(false),
161                                                 Some((None, initializer_span)),
162                                             );
163                                             this.expr_into_pattern(block, pattern.clone(), init) // irrefutable pattern
164                                         }
165                                     })
166                                 },
167                             )
168                         )
169                     } else {
170                         let scope = (*init_scope, source_info);
171                         unpack!(this.in_scope(scope, *lint_level, |this| {
172                             this.declare_bindings(
173                                 visibility_scope,
174                                 remainder_span,
175                                 pattern,
176                                 ArmHasGuard(false),
177                                 None,
178                             );
179                             block.unit()
180                         }));
181
182                         debug!("ast_block_stmts: pattern={:?}", pattern);
183                         this.visit_primary_bindings(
184                             pattern,
185                             UserTypeProjections::none(),
186                             &mut |this, _, _, _, node, span, _, _| {
187                                 this.storage_live_binding(block, node, span, OutsideGuard, true);
188                                 this.schedule_drop_for_binding(node, span, OutsideGuard);
189                             },
190                         )
191                     }
192
193                     // Enter the visibility scope, after evaluating the initializer.
194                     if let Some(source_scope) = visibility_scope {
195                         this.source_scope = source_scope;
196                     }
197                     last_remainder_scope = *remainder_scope;
198                 }
199             }
200
201             let popped = this.block_context.pop();
202             assert!(popped.map_or(false, |bf| bf.is_statement()));
203         }
204
205         // Then, the block may have an optional trailing expression which is a “return” value
206         // of the block, which is stored into `destination`.
207         let tcx = this.tcx;
208         let destination_ty = destination.ty(&this.local_decls, tcx).ty;
209         if let Some(expr) = expr {
210             let tail_result_is_ignored =
211                 destination_ty.is_unit() || this.block_context.currently_ignores_tail_results();
212             this.block_context
213                 .push(BlockFrame::TailExpr { tail_result_is_ignored, span: expr.span });
214
215             unpack!(block = this.expr_into_dest(destination, block, expr));
216             let popped = this.block_context.pop();
217
218             assert!(popped.map_or(false, |bf| bf.is_tail_expr()));
219         } else {
220             // If a block has no trailing expression, then it is given an implicit return type.
221             // This return type is usually `()`, unless the block is diverging, in which case the
222             // return type is `!`. For the unit type, we need to actually return the unit, but in
223             // the case of `!`, no return value is required, as the block will never return.
224             // Opaque types of empty bodies also need this unit assignment, in order to infer that their
225             // type is actually unit. Otherwise there will be no defining use found in the MIR.
226             if destination_ty.is_unit() || matches!(destination_ty.kind(), ty::Opaque(..)) {
227                 // We only want to assign an implicit `()` as the return value of the block if the
228                 // block does not diverge. (Otherwise, we may try to assign a unit to a `!`-type.)
229                 this.cfg.push_assign_unit(block, source_info, destination, this.tcx);
230             }
231         }
232         // Finally, we pop all the let scopes before exiting out from the scope of block
233         // itself.
234         for scope in let_scope_stack.into_iter().rev() {
235             unpack!(block = this.pop_scope((*scope, source_info), block));
236         }
237         // Restore the original source scope.
238         this.source_scope = outer_source_scope;
239         this.in_scope_unsafe = outer_in_scope_unsafe;
240         block.unit()
241     }
242
243     /// If we are entering an unsafe block, create a new source scope
244     fn update_source_scope_for_safety_mode(&mut self, span: Span, safety_mode: BlockSafety) {
245         debug!("update_source_scope_for({:?}, {:?})", span, safety_mode);
246         let new_unsafety = match safety_mode {
247             BlockSafety::Safe => return,
248             BlockSafety::BuiltinUnsafe => Safety::BuiltinUnsafe,
249             BlockSafety::ExplicitUnsafe(hir_id) => {
250                 self.in_scope_unsafe = Safety::ExplicitUnsafe(hir_id);
251                 Safety::ExplicitUnsafe(hir_id)
252             }
253         };
254
255         self.source_scope = self.new_source_scope(span, LintLevel::Inherited, Some(new_unsafety));
256     }
257 }