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