]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/block.rs
2ef71617b7cb615fd771ed42284d31f37b4f193e
[rust.git] / src / librustc_mir / build / block.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
12 use build::ForGuard::OutsideGuard;
13 use build::matches::ArmHasGuard;
14 use hair::*;
15 use rustc::mir::*;
16 use rustc::hir;
17 use syntax_pos::Span;
18
19 use std::slice;
20
21 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
22     pub fn ast_block(&mut self,
23                      destination: &Place<'tcx>,
24                      block: BasicBlock,
25                      ast_block: &'tcx hir::Block,
26                      source_info: SourceInfo)
27                      -> BlockAnd<()> {
28         let Block {
29             region_scope,
30             opt_destruction_scope,
31             span,
32             stmts,
33             expr,
34             targeted_by_break,
35             safety_mode
36         } =
37             self.hir.mirror(ast_block);
38         self.in_opt_scope(opt_destruction_scope.map(|de|(de, source_info)), block, move |this| {
39             this.in_scope((region_scope, source_info), LintLevel::Inherited, block, move |this| {
40                 if targeted_by_break {
41                     // This is a `break`-able block
42                     let exit_block = this.cfg.start_new_block();
43                     let block_exit = this.in_breakable_scope(
44                         None, exit_block, destination.clone(), |this| {
45                             this.ast_block_stmts(destination, block, span, stmts, expr,
46                                                  safety_mode)
47                         });
48                     this.cfg.terminate(unpack!(block_exit), source_info,
49                                        TerminatorKind::Goto { target: exit_block });
50                     exit_block.unit()
51                 } else {
52                     this.ast_block_stmts(destination, block, span, stmts, expr,
53                                          safety_mode)
54                 }
55             })
56         })
57     }
58
59     fn ast_block_stmts(&mut self,
60                        destination: &Place<'tcx>,
61                        mut block: BasicBlock,
62                        span: Span,
63                        stmts: Vec<StmtRef<'tcx>>,
64                        expr: Option<ExprRef<'tcx>>,
65                        safety_mode: BlockSafety)
66                        -> BlockAnd<()> {
67         let this = self;
68
69         // This convoluted structure is to avoid using recursion as we walk down a list
70         // of statements. Basically, the structure we get back is something like:
71         //
72         //    let x = <init> in {
73         //       expr1;
74         //       let y = <init> in {
75         //           expr2;
76         //           expr3;
77         //           ...
78         //       }
79         //    }
80         //
81         // The let bindings are valid till the end of block so all we have to do is to pop all
82         // the let-scopes at the end.
83         //
84         // First we build all the statements in the block.
85         let mut let_scope_stack = Vec::with_capacity(8);
86         let outer_source_scope = this.source_scope;
87         let outer_push_unsafe_count = this.push_unsafe_count;
88         let outer_unpushed_unsafe = this.unpushed_unsafe;
89         this.update_source_scope_for_safety_mode(span, safety_mode);
90
91         let source_info = this.source_info(span);
92         for stmt in stmts {
93             let Stmt { kind, opt_destruction_scope, span: stmt_span } = this.hir.mirror(stmt);
94             match kind {
95                 StmtKind::Expr { scope, expr } => {
96                     this.block_context.push(BlockFrame::Statement { ignores_expr_result: true });
97                     unpack!(block = this.in_opt_scope(
98                         opt_destruction_scope.map(|de|(de, source_info)), block, |this| {
99                             let si = (scope, source_info);
100                             this.in_scope(si, LintLevel::Inherited, block, |this| {
101                                 let expr = this.hir.mirror(expr);
102                                 this.stmt_expr(block, expr, Some(stmt_span))
103                             })
104                         }));
105                 }
106                 StmtKind::Let {
107                     remainder_scope,
108                     init_scope,
109                     pattern,
110                     initializer,
111                     lint_level
112                 } => {
113                     let ignores_expr_result = if let PatternKind::Wild = *pattern.kind {
114                         true
115                     } else {
116                         false
117                     };
118                     this.block_context.push(BlockFrame::Statement { ignores_expr_result });
119
120                     // Enter the remainder scope, i.e. the bindings' destruction scope.
121                     this.push_scope((remainder_scope, source_info));
122                     let_scope_stack.push(remainder_scope);
123
124                     // Declare the bindings, which may create a source scope.
125                     let remainder_span = remainder_scope.span(this.hir.tcx(),
126                                                               &this.hir.region_scope_tree);
127
128                     let scope;
129
130                     // Evaluate the initializer, if present.
131                     if let Some(init) = initializer {
132                         let initializer_span = init.span();
133
134                         scope = this.declare_bindings(
135                             None,
136                             remainder_span,
137                             lint_level,
138                             slice::from_ref(&pattern),
139                             ArmHasGuard(false),
140                             Some((None, initializer_span)),
141                         );
142                         unpack!(block = this.in_opt_scope(
143                             opt_destruction_scope.map(|de|(de, source_info)), block, |this| {
144                                 let scope = (init_scope, source_info);
145                                 this.in_scope(scope, lint_level, block, |this| {
146                                     this.expr_into_pattern(block, pattern, init)
147                                 })
148                             }));
149                     } else {
150                         scope = this.declare_bindings(
151                             None, remainder_span, lint_level, slice::from_ref(&pattern),
152                             ArmHasGuard(false), None);
153
154                         this.visit_bindings(
155                             &pattern,
156                             &PatternTypeProjections::none(),
157                             &mut |this, _, _, _, node, span, _, _| {
158                                 this.storage_live_binding(block, node, span, OutsideGuard);
159                                 this.schedule_drop_for_binding(node, span, OutsideGuard);
160                             })
161                     }
162
163                     // Enter the source scope, after evaluating the initializer.
164                     if let Some(source_scope) = scope {
165                         this.source_scope = source_scope;
166                     }
167                 }
168             }
169
170             let popped = this.block_context.pop();
171             assert!(popped.map_or(false, |bf|bf.is_statement()));
172         }
173
174         // Then, the block may have an optional trailing expression which is a “return” value
175         // of the block, which is stored into `destination`.
176         let tcx = this.hir.tcx();
177         let destination_ty = destination.ty(&this.local_decls, tcx).to_ty(tcx);
178         if let Some(expr) = expr {
179             let tail_result_is_ignored = destination_ty.is_unit() ||
180                 this.block_context.currently_ignores_tail_results();
181             this.block_context.push(BlockFrame::TailExpr { tail_result_is_ignored });
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);
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,
212                                                span: Span,
213                                                safety_mode: BlockSafety)
214     {
215         debug!("update_source_scope_for({:?}, {:?})", span, safety_mode);
216         let new_unsafety = match safety_mode {
217             BlockSafety::Safe => None,
218             BlockSafety::ExplicitUnsafe(node_id) => {
219                 assert_eq!(self.push_unsafe_count, 0);
220                 match self.unpushed_unsafe {
221                     Safety::Safe => {}
222                     _ => return
223                 }
224                 self.unpushed_unsafe = Safety::ExplicitUnsafe(node_id);
225                 Some(Safety::ExplicitUnsafe(node_id))
226             }
227             BlockSafety::PushUnsafe => {
228                 self.push_unsafe_count += 1;
229                 Some(Safety::BuiltinUnsafe)
230             }
231             BlockSafety::PopUnsafe => {
232                 self.push_unsafe_count =
233                     self.push_unsafe_count.checked_sub(1).unwrap_or_else(|| {
234                         span_bug!(span, "unsafe count underflow")
235                     });
236                 if self.push_unsafe_count == 0 {
237                     Some(self.unpushed_unsafe)
238                 } else {
239                     None
240                 }
241             }
242         };
243
244         if let Some(unsafety) = new_unsafety {
245             self.source_scope = self.new_source_scope(
246                 span, LintLevel::Inherited, Some(unsafety));
247         }
248     }
249 }