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