]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/block.rs
Rollup merge of #82091 - henryboisdequin:use-place-ref-more, r=RalfJung
[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.in_breakable_scope(None, destination, span, |this| {
32                         Some(this.ast_block_stmts(
33                             destination,
34                             block,
35                             span,
36                             stmts,
37                             expr,
38                             safety_mode,
39                         ))
40                     })
41                 } else {
42                     this.ast_block_stmts(destination, block, span, stmts, expr, safety_mode)
43                 }
44             })
45         })
46     }
47
48     fn ast_block_stmts(
49         &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 } = 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!(
88                         block = this.in_opt_scope(
89                             opt_destruction_scope.map(|de| (de, source_info)),
90                             |this| {
91                                 let si = (scope, source_info);
92                                 this.in_scope(si, LintLevel::Inherited, |this| {
93                                     let expr = this.hir.mirror(expr);
94                                     this.stmt_expr(block, expr, Some(scope))
95                                 })
96                             }
97                         )
98                     );
99                 }
100                 StmtKind::Let { remainder_scope, init_scope, pattern, initializer, lint_level } => {
101                     let ignores_expr_result = matches!(*pattern.kind, PatKind::Wild);
102                     this.block_context.push(BlockFrame::Statement { ignores_expr_result });
103
104                     // Enter the remainder scope, i.e., the bindings' destruction scope.
105                     this.push_scope((remainder_scope, source_info));
106                     let_scope_stack.push(remainder_scope);
107
108                     // Declare the bindings, which may create a source scope.
109                     let remainder_span =
110                         remainder_scope.span(this.hir.tcx(), &this.hir.region_scope_tree);
111
112                     let visibility_scope =
113                         Some(this.new_source_scope(remainder_span, LintLevel::Inherited, None));
114
115                     // Evaluate the initializer, if present.
116                     if let Some(init) = initializer {
117                         let initializer_span = init.span();
118
119                         unpack!(
120                             block = this.in_opt_scope(
121                                 opt_destruction_scope.map(|de| (de, source_info)),
122                                 |this| {
123                                     let scope = (init_scope, source_info);
124                                     this.in_scope(scope, lint_level, |this| {
125                                         this.declare_bindings(
126                                             visibility_scope,
127                                             remainder_span,
128                                             &pattern,
129                                             ArmHasGuard(false),
130                                             Some((None, initializer_span)),
131                                         );
132                                         this.expr_into_pattern(block, pattern, init)
133                                     })
134                                 }
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_primary_bindings(
152                             &pattern,
153                             UserTypeProjections::none(),
154                             &mut |this, _, _, _, node, span, _, _| {
155                                 this.storage_live_binding(block, node, span, OutsideGuard, true);
156                                 this.schedule_drop_for_binding(node, span, OutsideGuard);
157                             },
158                         )
159                     }
160
161                     // Enter the visibility scope, after evaluating the initializer.
162                     if let Some(source_scope) = visibility_scope {
163                         this.source_scope = source_scope;
164                     }
165                 }
166             }
167
168             let popped = this.block_context.pop();
169             assert!(popped.map_or(false, |bf| bf.is_statement()));
170         }
171
172         // Then, the block may have an optional trailing expression which is a “return” value
173         // of the block, which is stored into `destination`.
174         let tcx = this.hir.tcx();
175         let destination_ty = destination.ty(&this.local_decls, tcx).ty;
176         if let Some(expr) = expr {
177             let tail_result_is_ignored =
178                 destination_ty.is_unit() || this.block_context.currently_ignores_tail_results();
179             let span = match expr {
180                 ExprRef::Thir(expr) => expr.span,
181                 ExprRef::Mirror(ref expr) => expr.span,
182             };
183             this.block_context.push(BlockFrame::TailExpr { tail_result_is_ignored, span });
184
185             unpack!(block = this.into(destination, block, expr));
186             let popped = this.block_context.pop();
187
188             assert!(popped.map_or(false, |bf| bf.is_tail_expr()));
189         } else {
190             // If a block has no trailing expression, then it is given an implicit return type.
191             // This return type is usually `()`, unless the block is diverging, in which case the
192             // return type is `!`. For the unit type, we need to actually return the unit, but in
193             // the case of `!`, no return value is required, as the block will never return.
194             if destination_ty.is_unit() {
195                 // We only want to assign an implicit `()` as the return value of the block if the
196                 // block does not diverge. (Otherwise, we may try to assign a unit to a `!`-type.)
197                 this.cfg.push_assign_unit(block, source_info, destination, this.hir.tcx());
198             }
199         }
200         // Finally, we pop all the let scopes before exiting out from the scope of block
201         // itself.
202         for scope in let_scope_stack.into_iter().rev() {
203             unpack!(block = this.pop_scope((scope, source_info), block));
204         }
205         // Restore the original source scope.
206         this.source_scope = outer_source_scope;
207         this.push_unsafe_count = outer_push_unsafe_count;
208         this.unpushed_unsafe = outer_unpushed_unsafe;
209         block.unit()
210     }
211
212     /// If we are changing the safety mode, create a new source scope
213     fn update_source_scope_for_safety_mode(&mut self, span: Span, safety_mode: BlockSafety) {
214         debug!("update_source_scope_for({:?}, {:?})", span, safety_mode);
215         let new_unsafety = match safety_mode {
216             BlockSafety::Safe => None,
217             BlockSafety::ExplicitUnsafe(hir_id) => {
218                 assert_eq!(self.push_unsafe_count, 0);
219                 match self.unpushed_unsafe {
220                     Safety::Safe => {}
221                     // no longer treat `unsafe fn`s as `unsafe` contexts (see RFC #2585)
222                     Safety::FnUnsafe
223                         if self.hir.tcx().lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, hir_id).0
224                             != Level::Allow => {}
225                     _ => return,
226                 }
227                 self.unpushed_unsafe = Safety::ExplicitUnsafe(hir_id);
228                 Some(Safety::ExplicitUnsafe(hir_id))
229             }
230             BlockSafety::PushUnsafe => {
231                 self.push_unsafe_count += 1;
232                 Some(Safety::BuiltinUnsafe)
233             }
234             BlockSafety::PopUnsafe => {
235                 self.push_unsafe_count = self
236                     .push_unsafe_count
237                     .checked_sub(1)
238                     .unwrap_or_else(|| span_bug!(span, "unsafe count underflow"));
239                 if self.push_unsafe_count == 0 { Some(self.unpushed_unsafe) } else { None }
240             }
241         };
242
243         if let Some(unsafety) = new_unsafety {
244             self.source_scope = self.new_source_scope(span, LintLevel::Inherited, Some(unsafety));
245         }
246     }
247 }