]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/block.rs
use matches!() macro for simple if let conditions
[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 crate::thir::*;
5 use rustc_hir as hir;
6 use rustc_middle::mir::*;
7 use rustc_session::lint::builtin::UNSAFE_OP_IN_UNSAFE_FN;
8 use rustc_session::lint::Level;
9 use rustc_span::Span;
10
11 impl<'a, 'tcx> Builder<'a, 'tcx> {
12     crate fn ast_block(
13         &mut self,
14         destination: Place<'tcx>,
15         block: BasicBlock,
16         ast_block: &'tcx hir::Block<'tcx>,
17         source_info: SourceInfo,
18     ) -> BlockAnd<()> {
19         let Block {
20             region_scope,
21             opt_destruction_scope,
22             span,
23             stmts,
24             expr,
25             targeted_by_break,
26             safety_mode,
27         } = self.hir.mirror(ast_block);
28         self.in_opt_scope(opt_destruction_scope.map(|de| (de, source_info)), move |this| {
29             this.in_scope((region_scope, source_info), LintLevel::Inherited, move |this| {
30                 if targeted_by_break {
31                     // This is a `break`-able block
32                     let exit_block = this.cfg.start_new_block();
33                     let block_exit =
34                         this.in_breakable_scope(None, exit_block, destination, |this| {
35                             this.ast_block_stmts(destination, block, span, stmts, expr, safety_mode)
36                         });
37                     this.cfg.goto(unpack!(block_exit), source_info, exit_block);
38                     exit_block.unit()
39                 } else {
40                     this.ast_block_stmts(destination, block, span, stmts, expr, safety_mode)
41                 }
42             })
43         })
44     }
45
46     fn ast_block_stmts(
47         &mut self,
48         destination: Place<'tcx>,
49         mut block: BasicBlock,
50         span: Span,
51         stmts: Vec<StmtRef<'tcx>>,
52         expr: Option<ExprRef<'tcx>>,
53         safety_mode: BlockSafety,
54     ) -> BlockAnd<()> {
55         let this = self;
56
57         // This convoluted structure is to avoid using recursion as we walk down a list
58         // of statements. Basically, the structure we get back is something like:
59         //
60         //    let x = <init> in {
61         //       expr1;
62         //       let y = <init> in {
63         //           expr2;
64         //           expr3;
65         //           ...
66         //       }
67         //    }
68         //
69         // The let bindings are valid till the end of block so all we have to do is to pop all
70         // the let-scopes at the end.
71         //
72         // First we build all the statements in the block.
73         let mut let_scope_stack = Vec::with_capacity(8);
74         let outer_source_scope = this.source_scope;
75         let outer_push_unsafe_count = this.push_unsafe_count;
76         let outer_unpushed_unsafe = this.unpushed_unsafe;
77         this.update_source_scope_for_safety_mode(span, safety_mode);
78
79         let source_info = this.source_info(span);
80         for stmt in stmts {
81             let Stmt { kind, opt_destruction_scope } = this.hir.mirror(stmt);
82             match kind {
83                 StmtKind::Expr { scope, expr } => {
84                     this.block_context.push(BlockFrame::Statement { ignores_expr_result: true });
85                     unpack!(
86                         block = this.in_opt_scope(
87                             opt_destruction_scope.map(|de| (de, source_info)),
88                             |this| {
89                                 let si = (scope, source_info);
90                                 this.in_scope(si, LintLevel::Inherited, |this| {
91                                     let expr = this.hir.mirror(expr);
92                                     this.stmt_expr(block, expr, Some(scope))
93                                 })
94                             }
95                         )
96                     );
97                 }
98                 StmtKind::Let { remainder_scope, init_scope, pattern, initializer, lint_level } => {
99                     let ignores_expr_result = matches!(*pattern.kind, PatKind::Wild);
100                     this.block_context.push(BlockFrame::Statement { ignores_expr_result });
101
102                     // Enter the remainder scope, i.e., the bindings' destruction scope.
103                     this.push_scope((remainder_scope, source_info));
104                     let_scope_stack.push(remainder_scope);
105
106                     // Declare the bindings, which may create a source scope.
107                     let remainder_span =
108                         remainder_scope.span(this.hir.tcx(), &this.hir.region_scope_tree);
109
110                     let visibility_scope =
111                         Some(this.new_source_scope(remainder_span, LintLevel::Inherited, None));
112
113                     // Evaluate the initializer, if present.
114                     if let Some(init) = initializer {
115                         let initializer_span = init.span();
116
117                         unpack!(
118                             block = this.in_opt_scope(
119                                 opt_destruction_scope.map(|de| (de, source_info)),
120                                 |this| {
121                                     let scope = (init_scope, source_info);
122                                     this.in_scope(scope, lint_level, |this| {
123                                         this.declare_bindings(
124                                             visibility_scope,
125                                             remainder_span,
126                                             &pattern,
127                                             ArmHasGuard(false),
128                                             Some((None, initializer_span)),
129                                         );
130                                         this.expr_into_pattern(block, pattern, init)
131                                     })
132                                 }
133                             )
134                         );
135                     } else {
136                         let scope = (init_scope, source_info);
137                         unpack!(this.in_scope(scope, lint_level, |this| {
138                             this.declare_bindings(
139                                 visibility_scope,
140                                 remainder_span,
141                                 &pattern,
142                                 ArmHasGuard(false),
143                                 None,
144                             );
145                             block.unit()
146                         }));
147
148                         debug!("ast_block_stmts: pattern={:?}", pattern);
149                         this.visit_primary_bindings(
150                             &pattern,
151                             UserTypeProjections::none(),
152                             &mut |this, _, _, _, node, span, _, _| {
153                                 this.storage_live_binding(block, node, span, OutsideGuard, true);
154                                 this.schedule_drop_for_binding(node, span, OutsideGuard);
155                             },
156                         )
157                     }
158
159                     // Enter the visibility scope, after evaluating the initializer.
160                     if let Some(source_scope) = visibility_scope {
161                         this.source_scope = source_scope;
162                     }
163                 }
164             }
165
166             let popped = this.block_context.pop();
167             assert!(popped.map_or(false, |bf| bf.is_statement()));
168         }
169
170         // Then, the block may have an optional trailing expression which is a “return” value
171         // of the block, which is stored into `destination`.
172         let tcx = this.hir.tcx();
173         let destination_ty = destination.ty(&this.local_decls, tcx).ty;
174         if let Some(expr) = expr {
175             let tail_result_is_ignored =
176                 destination_ty.is_unit() || this.block_context.currently_ignores_tail_results();
177             let span = match expr {
178                 ExprRef::Thir(expr) => expr.span,
179                 ExprRef::Mirror(ref expr) => expr.span,
180             };
181             this.block_context.push(BlockFrame::TailExpr { tail_result_is_ignored, span });
182
183             unpack!(block = this.into(destination, block, expr));
184             let popped = this.block_context.pop();
185
186             assert!(popped.map_or(false, |bf| bf.is_tail_expr()));
187         } else {
188             // If a block has no trailing expression, then it is given an implicit return type.
189             // This return type is usually `()`, unless the block is diverging, in which case the
190             // return type is `!`. For the unit type, we need to actually return the unit, but in
191             // the case of `!`, no return value is required, as the block will never return.
192             if destination_ty.is_unit() {
193                 // We only want to assign an implicit `()` as the return value of the block if the
194                 // block does not diverge. (Otherwise, we may try to assign a unit to a `!`-type.)
195                 this.cfg.push_assign_unit(block, source_info, destination, this.hir.tcx());
196             }
197         }
198         // Finally, we pop all the let scopes before exiting out from the scope of block
199         // itself.
200         for scope in let_scope_stack.into_iter().rev() {
201             unpack!(block = this.pop_scope((scope, source_info), block));
202         }
203         // Restore the original source scope.
204         this.source_scope = outer_source_scope;
205         this.push_unsafe_count = outer_push_unsafe_count;
206         this.unpushed_unsafe = outer_unpushed_unsafe;
207         block.unit()
208     }
209
210     /// If we are changing the safety mode, create a new source scope
211     fn update_source_scope_for_safety_mode(&mut self, span: Span, safety_mode: BlockSafety) {
212         debug!("update_source_scope_for({:?}, {:?})", span, safety_mode);
213         let new_unsafety = match safety_mode {
214             BlockSafety::Safe => None,
215             BlockSafety::ExplicitUnsafe(hir_id) => {
216                 assert_eq!(self.push_unsafe_count, 0);
217                 match self.unpushed_unsafe {
218                     Safety::Safe => {}
219                     // no longer treat `unsafe fn`s as `unsafe` contexts (see RFC #2585)
220                     Safety::FnUnsafe
221                         if self.hir.tcx().lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, hir_id).0
222                             != Level::Allow => {}
223                     _ => return,
224                 }
225                 self.unpushed_unsafe = Safety::ExplicitUnsafe(hir_id);
226                 Some(Safety::ExplicitUnsafe(hir_id))
227             }
228             BlockSafety::PushUnsafe => {
229                 self.push_unsafe_count += 1;
230                 Some(Safety::BuiltinUnsafe)
231             }
232             BlockSafety::PopUnsafe => {
233                 self.push_unsafe_count = self
234                     .push_unsafe_count
235                     .checked_sub(1)
236                     .unwrap_or_else(|| span_bug!(span, "unsafe count underflow"));
237                 if self.push_unsafe_count == 0 { Some(self.unpushed_unsafe) } else { None }
238             }
239         };
240
241         if let Some(unsafety) = new_unsafety {
242             self.source_scope = self.new_source_scope(span, LintLevel::Inherited, Some(unsafety));
243         }
244     }
245 }