]> git.lizzy.rs Git - rust.git/blob - src/librustc/cfg/construct.rs
Run `rustfmt --file-lines ...` for changes from previous commits.
[rust.git] / src / librustc / cfg / construct.rs
1 use crate::cfg::*;
2 use crate::middle::region;
3 use rustc_data_structures::graph::implementation as graph;
4 use syntax::ptr::P;
5 use crate::ty::{self, TyCtxt};
6
7 use crate::hir::{self, PatKind};
8 use crate::hir::def_id::DefId;
9
10 struct CFGBuilder<'a, 'tcx: 'a> {
11     tcx: TyCtxt<'tcx, 'tcx>,
12     owner_def_id: DefId,
13     tables: &'a ty::TypeckTables<'tcx>,
14     graph: CFGGraph,
15     fn_exit: CFGIndex,
16     loop_scopes: Vec<LoopScope>,
17     breakable_block_scopes: Vec<BlockScope>,
18 }
19
20 #[derive(Copy, Clone)]
21 struct BlockScope {
22     block_expr_id: hir::ItemLocalId, // id of breakable block expr node
23     break_index: CFGIndex, // where to go on `break`
24 }
25
26 #[derive(Copy, Clone)]
27 struct LoopScope {
28     loop_id: hir::ItemLocalId,     // id of loop/while node
29     continue_index: CFGIndex, // where to go on a `loop`
30     break_index: CFGIndex,    // where to go on a `break`
31 }
32
33 pub fn construct<'tcx>(tcx: TyCtxt<'tcx, 'tcx>, body: &hir::Body) -> CFG {
34     let mut graph = graph::Graph::new();
35     let entry = graph.add_node(CFGNodeData::Entry);
36
37     // `fn_exit` is target of return exprs, which lies somewhere
38     // outside input `body`. (Distinguishing `fn_exit` and `body_exit`
39     // also resolves chicken-and-egg problem that arises if you try to
40     // have return exprs jump to `body_exit` during construction.)
41     let fn_exit = graph.add_node(CFGNodeData::Exit);
42     let body_exit;
43
44     // Find the tables for this body.
45     let owner_def_id = tcx.hir().local_def_id(tcx.hir().body_owner(body.id()));
46     let tables = tcx.typeck_tables_of(owner_def_id);
47
48     let mut cfg_builder = CFGBuilder {
49         tcx,
50         owner_def_id,
51         tables,
52         graph,
53         fn_exit,
54         loop_scopes: Vec::new(),
55         breakable_block_scopes: Vec::new(),
56     };
57     body_exit = cfg_builder.expr(&body.value, entry);
58     cfg_builder.add_contained_edge(body_exit, fn_exit);
59     let CFGBuilder { graph, .. } = cfg_builder;
60     CFG {
61         owner_def_id,
62         graph,
63         entry,
64         exit: fn_exit,
65     }
66 }
67
68 impl<'a, 'tcx> CFGBuilder<'a, 'tcx> {
69     fn block(&mut self, blk: &hir::Block, pred: CFGIndex) -> CFGIndex {
70         if blk.targeted_by_break {
71             let expr_exit = self.add_ast_node(blk.hir_id.local_id, &[]);
72
73             self.breakable_block_scopes.push(BlockScope {
74                 block_expr_id: blk.hir_id.local_id,
75                 break_index: expr_exit,
76             });
77
78             let mut stmts_exit = pred;
79             for stmt in &blk.stmts {
80                 stmts_exit = self.stmt(stmt, stmts_exit);
81             }
82             let blk_expr_exit = self.opt_expr(&blk.expr, stmts_exit);
83             self.add_contained_edge(blk_expr_exit, expr_exit);
84
85             self.breakable_block_scopes.pop();
86
87             expr_exit
88         } else {
89             let mut stmts_exit = pred;
90             for stmt in &blk.stmts {
91                 stmts_exit = self.stmt(stmt, stmts_exit);
92             }
93
94             let expr_exit = self.opt_expr(&blk.expr, stmts_exit);
95
96             self.add_ast_node(blk.hir_id.local_id, &[expr_exit])
97         }
98     }
99
100     fn stmt(&mut self, stmt: &hir::Stmt, pred: CFGIndex) -> CFGIndex {
101         let exit = match stmt.node {
102             hir::StmtKind::Local(ref local) => {
103                 let init_exit = self.opt_expr(&local.init, pred);
104                 self.pat(&local.pat, init_exit)
105             }
106             hir::StmtKind::Item(_) => {
107                 pred
108             }
109             hir::StmtKind::Expr(ref expr) |
110             hir::StmtKind::Semi(ref expr) => {
111                 self.expr(&expr, pred)
112             }
113         };
114         self.add_ast_node(stmt.hir_id.local_id, &[exit])
115     }
116
117     fn pat(&mut self, pat: &hir::Pat, pred: CFGIndex) -> CFGIndex {
118         match pat.node {
119             PatKind::Binding(.., None) |
120             PatKind::Path(_) |
121             PatKind::Lit(..) |
122             PatKind::Range(..) |
123             PatKind::Wild => self.add_ast_node(pat.hir_id.local_id, &[pred]),
124
125             PatKind::Box(ref subpat) |
126             PatKind::Ref(ref subpat, _) |
127             PatKind::Binding(.., Some(ref subpat)) => {
128                 let subpat_exit = self.pat(&subpat, pred);
129                 self.add_ast_node(pat.hir_id.local_id, &[subpat_exit])
130             }
131
132             PatKind::TupleStruct(_, ref subpats, _) |
133             PatKind::Tuple(ref subpats, _) => {
134                 let pats_exit = self.pats_all(subpats.iter(), pred);
135                 self.add_ast_node(pat.hir_id.local_id, &[pats_exit])
136             }
137
138             PatKind::Struct(_, ref subpats, _) => {
139                 let pats_exit = self.pats_all(subpats.iter().map(|f| &f.node.pat), pred);
140                 self.add_ast_node(pat.hir_id.local_id, &[pats_exit])
141             }
142
143             PatKind::Slice(ref pre, ref vec, ref post) => {
144                 let pre_exit = self.pats_all(pre.iter(), pred);
145                 let vec_exit = self.pats_all(vec.iter(), pre_exit);
146                 let post_exit = self.pats_all(post.iter(), vec_exit);
147                 self.add_ast_node(pat.hir_id.local_id, &[post_exit])
148             }
149         }
150     }
151
152     fn pats_all<'b, I: Iterator<Item=&'b P<hir::Pat>>>(
153         &mut self,
154         pats: I,
155         pred: CFGIndex
156     ) -> CFGIndex {
157         //! Handles case where all of the patterns must match.
158         pats.fold(pred, |pred, pat| self.pat(&pat, pred))
159     }
160
161     fn expr(&mut self, expr: &hir::Expr, pred: CFGIndex) -> CFGIndex {
162         match expr.node {
163             hir::ExprKind::Block(ref blk, _) => {
164                 let blk_exit = self.block(&blk, pred);
165                 self.add_ast_node(expr.hir_id.local_id, &[blk_exit])
166             }
167
168             hir::ExprKind::While(ref cond, ref body, _) => {
169                 //
170                 //         [pred]
171                 //           |
172                 //           v 1
173                 //       [loopback] <--+ 5
174                 //           |         |
175                 //           v 2       |
176                 //   +-----[cond]      |
177                 //   |       |         |
178                 //   |       v 4       |
179                 //   |     [body] -----+
180                 //   v 3
181                 // [expr]
182                 //
183                 // Note that `break` and `continue` statements
184                 // may cause additional edges.
185
186                 let loopback = self.add_dummy_node(&[pred]);              // 1
187
188                 // Create expr_exit without pred (cond_exit)
189                 let expr_exit = self.add_ast_node(expr.hir_id.local_id, &[]);         // 3
190
191                 // The LoopScope needs to be on the loop_scopes stack while evaluating the
192                 // condition and the body of the loop (both can break out of the loop)
193                 self.loop_scopes.push(LoopScope {
194                     loop_id: expr.hir_id.local_id,
195                     continue_index: loopback,
196                     break_index: expr_exit
197                 });
198
199                 let cond_exit = self.expr(&cond, loopback);             // 2
200
201                 // Add pred (cond_exit) to expr_exit
202                 self.add_contained_edge(cond_exit, expr_exit);
203
204                 let body_exit = self.block(&body, cond_exit);          // 4
205                 self.add_contained_edge(body_exit, loopback);            // 5
206                 self.loop_scopes.pop();
207                 expr_exit
208             }
209
210             hir::ExprKind::Loop(ref body, _, _) => {
211                 //
212                 //     [pred]
213                 //       |
214                 //       v 1
215                 //   [loopback] <---+
216                 //       |      4   |
217                 //       v 3        |
218                 //     [body] ------+
219                 //
220                 //     [expr] 2
221                 //
222                 // Note that `break` and `loop` statements
223                 // may cause additional edges.
224
225                 let loopback = self.add_dummy_node(&[pred]);              // 1
226                 let expr_exit = self.add_ast_node(expr.hir_id.local_id, &[]);          // 2
227                 self.loop_scopes.push(LoopScope {
228                     loop_id: expr.hir_id.local_id,
229                     continue_index: loopback,
230                     break_index: expr_exit,
231                 });
232                 let body_exit = self.block(&body, loopback);           // 3
233                 self.add_contained_edge(body_exit, loopback);            // 4
234                 self.loop_scopes.pop();
235                 expr_exit
236             }
237
238             hir::ExprKind::Match(ref discr, ref arms, _) => {
239                 self.match_(expr.hir_id.local_id, &discr, &arms, pred)
240             }
241
242             hir::ExprKind::Binary(op, ref l, ref r) if op.node.is_lazy() => {
243                 //
244                 //     [pred]
245                 //       |
246                 //       v 1
247                 //      [l]
248                 //       |
249                 //      / \
250                 //     /   \
251                 //    v 2  *
252                 //   [r]   |
253                 //    |    |
254                 //    v 3  v 4
255                 //   [..exit..]
256                 //
257                 let l_exit = self.expr(&l, pred);                      // 1
258                 let r_exit = self.expr(&r, l_exit);                    // 2
259                 self.add_ast_node(expr.hir_id.local_id, &[l_exit, r_exit])            // 3,4
260             }
261
262             hir::ExprKind::Ret(ref v) => {
263                 let v_exit = self.opt_expr(v, pred);
264                 let b = self.add_ast_node(expr.hir_id.local_id, &[v_exit]);
265                 self.add_returning_edge(expr, b);
266                 self.add_unreachable_node()
267             }
268
269             hir::ExprKind::Break(destination, ref opt_expr) => {
270                 let v = self.opt_expr(opt_expr, pred);
271                 let (target_scope, break_dest) =
272                     self.find_scope_edge(expr, destination, ScopeCfKind::Break);
273                 let b = self.add_ast_node(expr.hir_id.local_id, &[v]);
274                 self.add_exiting_edge(expr, b, target_scope, break_dest);
275                 self.add_unreachable_node()
276             }
277
278             hir::ExprKind::Continue(destination) => {
279                 let (target_scope, cont_dest) =
280                     self.find_scope_edge(expr, destination, ScopeCfKind::Continue);
281                 let a = self.add_ast_node(expr.hir_id.local_id, &[pred]);
282                 self.add_exiting_edge(expr, a, target_scope, cont_dest);
283                 self.add_unreachable_node()
284             }
285
286             hir::ExprKind::Array(ref elems) => {
287                 self.straightline(expr, pred, elems.iter().map(|e| &*e))
288             }
289
290             hir::ExprKind::Call(ref func, ref args) => {
291                 self.call(expr, pred, &func, args.iter().map(|e| &*e))
292             }
293
294             hir::ExprKind::MethodCall(.., ref args) => {
295                 self.call(expr, pred, &args[0], args[1..].iter().map(|e| &*e))
296             }
297
298             hir::ExprKind::Index(ref l, ref r) |
299             hir::ExprKind::Binary(_, ref l, ref r) if self.tables.is_method_call(expr) => {
300                 self.call(expr, pred, &l, Some(&**r).into_iter())
301             }
302
303             hir::ExprKind::Unary(_, ref e) if self.tables.is_method_call(expr) => {
304                 self.call(expr, pred, &e, None::<hir::Expr>.iter())
305             }
306
307             hir::ExprKind::Tup(ref exprs) => {
308                 self.straightline(expr, pred, exprs.iter().map(|e| &*e))
309             }
310
311             hir::ExprKind::Struct(_, ref fields, ref base) => {
312                 let field_cfg = self.straightline(expr, pred, fields.iter().map(|f| &*f.expr));
313                 self.opt_expr(base, field_cfg)
314             }
315
316             hir::ExprKind::Assign(ref l, ref r) |
317             hir::ExprKind::AssignOp(_, ref l, ref r) => {
318                 self.straightline(expr, pred, [r, l].iter().map(|&e| &**e))
319             }
320
321             hir::ExprKind::Index(ref l, ref r) |
322             hir::ExprKind::Binary(_, ref l, ref r) => { // N.B., && and || handled earlier
323                 self.straightline(expr, pred, [l, r].iter().map(|&e| &**e))
324             }
325
326             hir::ExprKind::Box(ref e) |
327             hir::ExprKind::AddrOf(_, ref e) |
328             hir::ExprKind::Cast(ref e, _) |
329             hir::ExprKind::Type(ref e, _) |
330             hir::ExprKind::DropTemps(ref e) |
331             hir::ExprKind::Unary(_, ref e) |
332             hir::ExprKind::Field(ref e, _) |
333             hir::ExprKind::Yield(ref e) |
334             hir::ExprKind::Repeat(ref e, _) => {
335                 self.straightline(expr, pred, Some(&**e).into_iter())
336             }
337
338             hir::ExprKind::InlineAsm(_, ref outputs, ref inputs) => {
339                 let post_outputs = self.exprs(outputs.iter().map(|e| &*e), pred);
340                 let post_inputs = self.exprs(inputs.iter().map(|e| &*e), post_outputs);
341                 self.add_ast_node(expr.hir_id.local_id, &[post_inputs])
342             }
343
344             hir::ExprKind::Closure(..) |
345             hir::ExprKind::Lit(..) |
346             hir::ExprKind::Path(_) |
347             hir::ExprKind::Err => {
348                 self.straightline(expr, pred, None::<hir::Expr>.iter())
349             }
350         }
351     }
352
353     fn call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
354             call_expr: &hir::Expr,
355             pred: CFGIndex,
356             func_or_rcvr: &hir::Expr,
357             args: I) -> CFGIndex {
358         let func_or_rcvr_exit = self.expr(func_or_rcvr, pred);
359         let ret = self.straightline(call_expr, func_or_rcvr_exit, args);
360         let m = self.tcx.hir().get_module_parent_by_hir_id(call_expr.hir_id);
361         if self.tcx.is_ty_uninhabited_from(m, self.tables.expr_ty(call_expr)) {
362             self.add_unreachable_node()
363         } else {
364             ret
365         }
366     }
367
368     fn exprs<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
369                                              exprs: I,
370                                              pred: CFGIndex) -> CFGIndex {
371         //! Constructs graph for `exprs` evaluated in order
372         exprs.fold(pred, |p, e| self.expr(e, p))
373     }
374
375     fn opt_expr(&mut self,
376                 opt_expr: &Option<P<hir::Expr>>,
377                 pred: CFGIndex) -> CFGIndex {
378         //! Constructs graph for `opt_expr` evaluated, if Some
379         opt_expr.iter().fold(pred, |p, e| self.expr(&e, p))
380     }
381
382     fn straightline<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
383                     expr: &hir::Expr,
384                     pred: CFGIndex,
385                     subexprs: I) -> CFGIndex {
386         //! Handles case of an expression that evaluates `subexprs` in order
387
388         let subexprs_exit = self.exprs(subexprs, pred);
389         self.add_ast_node(expr.hir_id.local_id, &[subexprs_exit])
390     }
391
392     fn match_(&mut self, id: hir::ItemLocalId, discr: &hir::Expr,
393               arms: &[hir::Arm], pred: CFGIndex) -> CFGIndex {
394         // The CFG for match expression is quite complex, so no ASCII
395         // art for it (yet).
396         //
397         // The CFG generated below matches roughly what MIR contains.
398         // Each pattern and guard is visited in parallel, with
399         // arms containing multiple patterns generating multiple nodes
400         // for the same guard expression. The guard expressions chain
401         // into each other from top to bottom, with a specific
402         // exception to allow some additional valid programs
403         // (explained below). MIR differs slightly in that the
404         // pattern matching may continue after a guard but the visible
405         // behaviour should be the same.
406         //
407         // What is going on is explained in further comments.
408
409         // Visit the discriminant expression
410         let discr_exit = self.expr(discr, pred);
411
412         // Add a node for the exit of the match expression as a whole.
413         let expr_exit = self.add_ast_node(id, &[]);
414
415         // Keep track of the previous guard expressions
416         let mut prev_guards = Vec::new();
417
418         for arm in arms {
419             // Add an exit node for when we've visited all the
420             // patterns and the guard (if there is one) in the arm.
421             let bindings_exit = self.add_dummy_node(&[]);
422
423             for pat in &arm.pats {
424                 // Visit the pattern, coming from the discriminant exit
425                 let mut pat_exit = self.pat(&pat, discr_exit);
426
427                 // If there is a guard expression, handle it here
428                 if let Some(ref guard) = arm.guard {
429                     // Add a dummy node for the previous guard
430                     // expression to target
431                     let guard_start = self.add_dummy_node(&[pat_exit]);
432                     // Visit the guard expression
433                     let guard_exit = match guard {
434                         hir::Guard::If(ref e) => self.expr(e, guard_start),
435                     };
436                     // #47295: We used to have very special case code
437                     // here for when a pair of arms are both formed
438                     // solely from constants, and if so, not add these
439                     // edges.  But this was not actually sound without
440                     // other constraints that we stopped enforcing at
441                     // some point.
442                     while let Some(prev) = prev_guards.pop() {
443                         self.add_contained_edge(prev, guard_start);
444                     }
445
446                     // Push the guard onto the list of previous guards
447                     prev_guards.push(guard_exit);
448
449                     // Update the exit node for the pattern
450                     pat_exit = guard_exit;
451                 }
452
453                 // Add an edge from the exit of this pattern to the
454                 // exit of the arm
455                 self.add_contained_edge(pat_exit, bindings_exit);
456             }
457
458             // Visit the body of this arm
459             let body_exit = self.expr(&arm.body, bindings_exit);
460
461             let arm_exit = self.add_ast_node(arm.hir_id.local_id, &[body_exit]);
462
463             // Link the body to the exit of the expression
464             self.add_contained_edge(arm_exit, expr_exit);
465         }
466
467         expr_exit
468     }
469
470     fn add_dummy_node(&mut self, preds: &[CFGIndex]) -> CFGIndex {
471         self.add_node(CFGNodeData::Dummy, preds)
472     }
473
474     fn add_ast_node(&mut self, id: hir::ItemLocalId, preds: &[CFGIndex]) -> CFGIndex {
475         self.add_node(CFGNodeData::AST(id), preds)
476     }
477
478     fn add_unreachable_node(&mut self) -> CFGIndex {
479         self.add_node(CFGNodeData::Unreachable, &[])
480     }
481
482     fn add_node(&mut self, data: CFGNodeData, preds: &[CFGIndex]) -> CFGIndex {
483         let node = self.graph.add_node(data);
484         for &pred in preds {
485             self.add_contained_edge(pred, node);
486         }
487         node
488     }
489
490     fn add_contained_edge(&mut self,
491                           source: CFGIndex,
492                           target: CFGIndex) {
493         let data = CFGEdgeData {exiting_scopes: vec![] };
494         self.graph.add_edge(source, target, data);
495     }
496
497     fn add_exiting_edge(&mut self,
498                         from_expr: &hir::Expr,
499                         from_index: CFGIndex,
500                         target_scope: region::Scope,
501                         to_index: CFGIndex) {
502         let mut data = CFGEdgeData { exiting_scopes: vec![] };
503         let mut scope = region::Scope {
504             id: from_expr.hir_id.local_id,
505             data: region::ScopeData::Node
506         };
507         let region_scope_tree = self.tcx.region_scope_tree(self.owner_def_id);
508         while scope != target_scope {
509             data.exiting_scopes.push(scope.item_local_id());
510             scope = region_scope_tree.encl_scope(scope);
511         }
512         self.graph.add_edge(from_index, to_index, data);
513     }
514
515     fn add_returning_edge(&mut self,
516                           _from_expr: &hir::Expr,
517                           from_index: CFGIndex) {
518         let data = CFGEdgeData {
519             exiting_scopes: self.loop_scopes.iter()
520                                             .rev()
521                                             .map(|&LoopScope { loop_id: id, .. }| id)
522                                             .collect()
523         };
524         self.graph.add_edge(from_index, self.fn_exit, data);
525     }
526
527     fn find_scope_edge(&self,
528                   expr: &hir::Expr,
529                   destination: hir::Destination,
530                   scope_cf_kind: ScopeCfKind) -> (region::Scope, CFGIndex) {
531
532         match destination.target_id {
533             Ok(loop_id) => {
534                 for b in &self.breakable_block_scopes {
535                     if b.block_expr_id == loop_id.local_id {
536                         let scope = region::Scope {
537                             id: loop_id.local_id,
538                             data: region::ScopeData::Node
539                         };
540                         return (scope, match scope_cf_kind {
541                             ScopeCfKind::Break => b.break_index,
542                             ScopeCfKind::Continue => bug!("can't continue to block"),
543                         });
544                     }
545                 }
546                 for l in &self.loop_scopes {
547                     if l.loop_id == loop_id.local_id {
548                         let scope = region::Scope {
549                             id: loop_id.local_id,
550                             data: region::ScopeData::Node
551                         };
552                         return (scope, match scope_cf_kind {
553                             ScopeCfKind::Break => l.break_index,
554                             ScopeCfKind::Continue => l.continue_index,
555                         });
556                     }
557                 }
558                 span_bug!(expr.span, "no scope for id {}", loop_id);
559             }
560             Err(err) => span_bug!(expr.span, "scope error: {}",  err),
561         }
562     }
563 }
564
565 #[derive(Copy, Clone, Eq, PartialEq)]
566 enum ScopeCfKind {
567     Break,
568     Continue,
569 }