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