]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/block.rs
Auto merge of #61587 - alexcrichton:distcheck-no-assertions, r=pietroalbini
[rust.git] / src / librustc_mir / build / block.rs
1 use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
2 use crate::build::ForGuard::OutsideGuard;
3 use crate::build::matches::ArmHasGuard;
4 use crate::hair::*;
5 use rustc::mir::*;
6 use rustc::hir;
7 use syntax_pos::Span;
8
9 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
10     pub fn ast_block(&mut self,
11                      destination: &Place<'tcx>,
12                      block: BasicBlock,
13                      ast_block: &'tcx hir::Block,
14                      source_info: SourceInfo)
15                      -> BlockAnd<()> {
16         let Block {
17             region_scope,
18             opt_destruction_scope,
19             span,
20             stmts,
21             expr,
22             targeted_by_break,
23             safety_mode
24         } =
25             self.hir.mirror(ast_block);
26         self.in_opt_scope(opt_destruction_scope.map(|de|(de, source_info)), move |this| {
27             this.in_scope((region_scope, source_info), LintLevel::Inherited, move |this| {
28                 if targeted_by_break {
29                     // This is a `break`-able block
30                     let exit_block = this.cfg.start_new_block();
31                     let block_exit = this.in_breakable_scope(
32                         None, exit_block, destination.clone(), |this| {
33                             this.ast_block_stmts(destination, block, span, stmts, expr,
34                                                  safety_mode)
35                         });
36                     this.cfg.terminate(unpack!(block_exit), source_info,
37                                        TerminatorKind::Goto { target: exit_block });
38                     exit_block.unit()
39                 } else {
40                     this.ast_block_stmts(destination, block, span, stmts, expr,
41                                          safety_mode)
42                 }
43             })
44         })
45     }
46
47     fn ast_block_stmts(&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, span: stmt_span } = 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!(block = this.in_opt_scope(
86                         opt_destruction_scope.map(|de|(de, source_info)), |this| {
87                             let si = (scope, source_info);
88                             this.in_scope(si, LintLevel::Inherited, |this| {
89                                 let expr = this.hir.mirror(expr);
90                                 this.stmt_expr(block, expr, Some(stmt_span))
91                             })
92                         }));
93                 }
94                 StmtKind::Let {
95                     remainder_scope,
96                     init_scope,
97                     pattern,
98                     initializer,
99                     lint_level
100                 } => {
101                     let ignores_expr_result = if let PatternKind::Wild = *pattern.kind {
102                         true
103                     } else {
104                         false
105                     };
106                     this.block_context.push(BlockFrame::Statement { ignores_expr_result });
107
108                     // Enter the remainder scope, i.e., the bindings' destruction scope.
109                     this.push_scope((remainder_scope, source_info));
110                     let_scope_stack.push(remainder_scope);
111
112                     // Declare the bindings, which may create a source scope.
113                     let remainder_span = remainder_scope.span(this.hir.tcx(),
114                                                               &this.hir.region_scope_tree);
115
116                     let visibility_scope =
117                         Some(this.new_source_scope(remainder_span, LintLevel::Inherited, None));
118
119                     // Evaluate the initializer, if present.
120                     if let Some(init) = initializer {
121                         let initializer_span = init.span();
122
123                         unpack!(block = this.in_opt_scope(
124                             opt_destruction_scope.map(|de|(de, source_info)), |this| {
125                                 let scope = (init_scope, source_info);
126                                 this.in_scope(scope, lint_level, |this| {
127                                     this.declare_bindings(
128                                         visibility_scope,
129                                         remainder_span,
130                                         &pattern,
131                                         ArmHasGuard(false),
132                                         Some((None, initializer_span)),
133                                     );
134                                     this.expr_into_pattern(block, pattern, init)
135                                 })
136                             }));
137                     } else {
138                         let scope = (init_scope, source_info);
139                         unpack!(this.in_scope(scope, lint_level, |this| {
140                             this.declare_bindings(
141                                 visibility_scope,
142                                 remainder_span,
143                                 &pattern,
144                                 ArmHasGuard(false),
145                                 None,
146                             );
147                             block.unit()
148                         }));
149
150                         debug!("ast_block_stmts: pattern={:?}", pattern);
151                         this.visit_bindings(
152                             &pattern,
153                             UserTypeProjections::none(),
154                             &mut |this, _, _, _, node, span, _, _| {
155                                 this.storage_live_binding(block, node, span, OutsideGuard);
156                                 this.schedule_drop_for_binding(node, span, OutsideGuard);
157                             })
158                     }
159
160                     // Enter the visibility scope, after evaluating the initializer.
161                     if let Some(source_scope) = visibility_scope {
162                         this.source_scope = source_scope;
163                     }
164                 }
165             }
166
167             let popped = this.block_context.pop();
168             assert!(popped.map_or(false, |bf|bf.is_statement()));
169         }
170
171         // Then, the block may have an optional trailing expression which is a “return” value
172         // of the block, which is stored into `destination`.
173         let tcx = this.hir.tcx();
174         let destination_ty = destination.ty(&this.local_decls, tcx).ty;
175         if let Some(expr) = expr {
176             let tail_result_is_ignored = destination_ty.is_unit() ||
177                 this.block_context.currently_ignores_tail_results();
178             this.block_context.push(BlockFrame::TailExpr { tail_result_is_ignored });
179
180             unpack!(block = this.into(destination, block, expr));
181             let popped = this.block_context.pop();
182
183             assert!(popped.map_or(false, |bf|bf.is_tail_expr()));
184         } else {
185             // If a block has no trailing expression, then it is given an implicit return type.
186             // This return type is usually `()`, unless the block is diverging, in which case the
187             // return type is `!`. For the unit type, we need to actually return the unit, but in
188             // the case of `!`, no return value is required, as the block will never return.
189             if destination_ty.is_unit() {
190                 // We only want to assign an implicit `()` as the return value of the block if the
191                 // block does not diverge. (Otherwise, we may try to assign a unit to a `!`-type.)
192                 this.cfg.push_assign_unit(block, source_info, destination);
193             }
194         }
195         // Finally, we pop all the let scopes before exiting out from the scope of block
196         // itself.
197         for scope in let_scope_stack.into_iter().rev() {
198             unpack!(block = this.pop_scope((scope, source_info), block));
199         }
200         // Restore the original source scope.
201         this.source_scope = outer_source_scope;
202         this.push_unsafe_count = outer_push_unsafe_count;
203         this.unpushed_unsafe = outer_unpushed_unsafe;
204         block.unit()
205     }
206
207     /// If we are changing the safety mode, create a new source scope
208     fn update_source_scope_for_safety_mode(&mut self,
209                                                span: Span,
210                                                safety_mode: BlockSafety)
211     {
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                     _ => return
220                 }
221                 self.unpushed_unsafe = Safety::ExplicitUnsafe(hir_id);
222                 Some(Safety::ExplicitUnsafe(hir_id))
223             }
224             BlockSafety::PushUnsafe => {
225                 self.push_unsafe_count += 1;
226                 Some(Safety::BuiltinUnsafe)
227             }
228             BlockSafety::PopUnsafe => {
229                 self.push_unsafe_count =
230                     self.push_unsafe_count.checked_sub(1).unwrap_or_else(|| {
231                         span_bug!(span, "unsafe count underflow")
232                     });
233                 if self.push_unsafe_count == 0 {
234                     Some(self.unpushed_unsafe)
235                 } else {
236                     None
237                 }
238             }
239         };
240
241         if let Some(unsafety) = new_unsafety {
242             self.source_scope = self.new_source_scope(
243                 span, LintLevel::Inherited, Some(unsafety));
244         }
245     }
246 }