]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cfg/construct.rs
Merge pull request #20510 from tshepang/patch-6
[rust.git] / src / librustc / middle / 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 middle::cfg::*;
12 use middle::def;
13 use middle::graph;
14 use middle::region::CodeExtent;
15 use middle::ty;
16 use syntax::ast;
17 use syntax::ast_util;
18 use syntax::ptr::P;
19 use util::nodemap::NodeMap;
20
21 struct CFGBuilder<'a, 'tcx: 'a> {
22     tcx: &'a ty::ctxt<'tcx>,
23     exit_map: NodeMap<CFGIndex>,
24     graph: CFGGraph,
25     fn_exit: CFGIndex,
26     loop_scopes: Vec<LoopScope>,
27 }
28
29 #[derive(Copy)]
30 struct LoopScope {
31     loop_id: ast::NodeId,     // id of loop/while node
32     continue_index: CFGIndex, // where to go on a `loop`
33     break_index: CFGIndex,    // where to go on a `break
34 }
35
36 pub fn construct(tcx: &ty::ctxt,
37                  blk: &ast::Block) -> CFG {
38     let mut graph = graph::Graph::new();
39     let entry = add_initial_dummy_node(&mut graph);
40
41     // `fn_exit` is target of return exprs, which lies somewhere
42     // outside input `blk`. (Distinguishing `fn_exit` and `block_exit`
43     // also resolves chicken-and-egg problem that arises if you try to
44     // have return exprs jump to `block_exit` during construction.)
45     let fn_exit = add_initial_dummy_node(&mut graph);
46     let block_exit;
47
48     let mut cfg_builder = CFGBuilder {
49         exit_map: NodeMap::new(),
50         graph: graph,
51         fn_exit: fn_exit,
52         tcx: tcx,
53         loop_scopes: Vec::new()
54     };
55     block_exit = cfg_builder.block(blk, entry);
56     cfg_builder.add_contained_edge(block_exit, fn_exit);
57     let CFGBuilder {exit_map, graph, ..} = cfg_builder;
58     CFG {exit_map: exit_map,
59          graph: graph,
60          entry: entry,
61          exit: fn_exit}
62 }
63
64 fn add_initial_dummy_node(g: &mut CFGGraph) -> CFGIndex {
65     g.add_node(CFGNodeData { id: ast::DUMMY_NODE_ID })
66 }
67
68 impl<'a, 'tcx> CFGBuilder<'a, 'tcx> {
69     fn block(&mut self, blk: &ast::Block, pred: CFGIndex) -> CFGIndex {
70         let mut stmts_exit = pred;
71         for stmt in blk.stmts.iter() {
72             stmts_exit = self.stmt(&**stmt, stmts_exit);
73         }
74
75         let expr_exit = self.opt_expr(&blk.expr, stmts_exit);
76
77         self.add_node(blk.id, &[expr_exit])
78     }
79
80     fn stmt(&mut self, stmt: &ast::Stmt, pred: CFGIndex) -> CFGIndex {
81         match stmt.node {
82             ast::StmtDecl(ref decl, id) => {
83                 let exit = self.decl(&**decl, pred);
84                 self.add_node(id, &[exit])
85             }
86
87             ast::StmtExpr(ref expr, id) | ast::StmtSemi(ref expr, id) => {
88                 let exit = self.expr(&**expr, pred);
89                 self.add_node(id, &[exit])
90             }
91
92             ast::StmtMac(..) => {
93                 self.tcx.sess.span_bug(stmt.span, "unexpanded macro");
94             }
95         }
96     }
97
98     fn decl(&mut self, decl: &ast::Decl, pred: CFGIndex) -> CFGIndex {
99         match decl.node {
100             ast::DeclLocal(ref local) => {
101                 let init_exit = self.opt_expr(&local.init, pred);
102                 self.pat(&*local.pat, init_exit)
103             }
104
105             ast::DeclItem(_) => {
106                 pred
107             }
108         }
109     }
110
111     fn pat(&mut self, pat: &ast::Pat, pred: CFGIndex) -> CFGIndex {
112         match pat.node {
113             ast::PatIdent(_, _, None) |
114             ast::PatEnum(_, None) |
115             ast::PatLit(..) |
116             ast::PatRange(..) |
117             ast::PatWild(_) => {
118                 self.add_node(pat.id, &[pred])
119             }
120
121             ast::PatBox(ref subpat) |
122             ast::PatRegion(ref subpat) |
123             ast::PatIdent(_, _, Some(ref subpat)) => {
124                 let subpat_exit = self.pat(&**subpat, pred);
125                 self.add_node(pat.id, &[subpat_exit])
126             }
127
128             ast::PatEnum(_, Some(ref subpats)) |
129             ast::PatTup(ref subpats) => {
130                 let pats_exit = self.pats_all(subpats.iter(), pred);
131                 self.add_node(pat.id, &[pats_exit])
132             }
133
134             ast::PatStruct(_, ref subpats, _) => {
135                 let pats_exit =
136                     self.pats_all(subpats.iter().map(|f| &f.node.pat), pred);
137                 self.add_node(pat.id, &[pats_exit])
138             }
139
140             ast::PatVec(ref pre, ref vec, ref post) => {
141                 let pre_exit = self.pats_all(pre.iter(), pred);
142                 let vec_exit = self.pats_all(vec.iter(), pre_exit);
143                 let post_exit = self.pats_all(post.iter(), vec_exit);
144                 self.add_node(pat.id, &[post_exit])
145             }
146
147             ast::PatMac(_) => {
148                 self.tcx.sess.span_bug(pat.span, "unexpanded macro");
149             }
150         }
151     }
152
153     fn pats_all<'b, I: Iterator<Item=&'b P<ast::Pat>>>(&mut self,
154                                           pats: I,
155                                           pred: CFGIndex) -> CFGIndex {
156         //! Handles case where all of the patterns must match.
157         pats.fold(pred, |pred, pat| self.pat(&**pat, pred))
158     }
159
160     fn pats_any(&mut self,
161                 pats: &[P<ast::Pat>],
162                 pred: CFGIndex) -> CFGIndex {
163         //! Handles case where just one of the patterns must match.
164
165         if pats.len() == 1 {
166             self.pat(&*pats[0], pred)
167         } else {
168             let collect = self.add_dummy_node(&[]);
169             for pat in pats.iter() {
170                 let pat_exit = self.pat(&**pat, pred);
171                 self.add_contained_edge(pat_exit, collect);
172             }
173             collect
174         }
175     }
176
177     fn expr(&mut self, expr: &ast::Expr, pred: CFGIndex) -> CFGIndex {
178         match expr.node {
179             ast::ExprBlock(ref blk) => {
180                 let blk_exit = self.block(&**blk, pred);
181                 self.add_node(expr.id, &[blk_exit])
182             }
183
184             ast::ExprIf(ref cond, ref then, None) => {
185                 //
186                 //     [pred]
187                 //       |
188                 //       v 1
189                 //     [cond]
190                 //       |
191                 //      / \
192                 //     /   \
193                 //    v 2   *
194                 //  [then]  |
195                 //    |     |
196                 //    v 3   v 4
197                 //   [..expr..]
198                 //
199                 let cond_exit = self.expr(&**cond, pred);                // 1
200                 let then_exit = self.block(&**then, cond_exit);          // 2
201                 self.add_node(expr.id, &[cond_exit, then_exit])          // 3,4
202             }
203
204             ast::ExprIf(ref cond, ref then, Some(ref otherwise)) => {
205                 //
206                 //     [pred]
207                 //       |
208                 //       v 1
209                 //     [cond]
210                 //       |
211                 //      / \
212                 //     /   \
213                 //    v 2   v 3
214                 //  [then][otherwise]
215                 //    |     |
216                 //    v 4   v 5
217                 //   [..expr..]
218                 //
219                 let cond_exit = self.expr(&**cond, pred);                // 1
220                 let then_exit = self.block(&**then, cond_exit);          // 2
221                 let else_exit = self.expr(&**otherwise, cond_exit);      // 3
222                 self.add_node(expr.id, &[then_exit, else_exit])          // 4, 5
223             }
224
225             ast::ExprIfLet(..) => {
226                 self.tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
227             }
228
229             ast::ExprWhile(ref cond, ref body, _) => {
230                 //
231                 //         [pred]
232                 //           |
233                 //           v 1
234                 //       [loopback] <--+ 5
235                 //           |         |
236                 //           v 2       |
237                 //   +-----[cond]      |
238                 //   |       |         |
239                 //   |       v 4       |
240                 //   |     [body] -----+
241                 //   v 3
242                 // [expr]
243                 //
244                 // Note that `break` and `continue` statements
245                 // may cause additional edges.
246
247                 // Is the condition considered part of the loop?
248                 let loopback = self.add_dummy_node(&[pred]);              // 1
249                 let cond_exit = self.expr(&**cond, loopback);             // 2
250                 let expr_exit = self.add_node(expr.id, &[cond_exit]);     // 3
251                 self.loop_scopes.push(LoopScope {
252                     loop_id: expr.id,
253                     continue_index: loopback,
254                     break_index: expr_exit
255                 });
256                 let body_exit = self.block(&**body, cond_exit);          // 4
257                 self.add_contained_edge(body_exit, loopback);            // 5
258                 self.loop_scopes.pop();
259                 expr_exit
260             }
261
262             ast::ExprWhileLet(..) => {
263                 self.tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
264             }
265
266             ast::ExprForLoop(ref pat, ref head, ref body, _) => {
267                 //
268                 //          [pred]
269                 //            |
270                 //            v 1
271                 //          [head]
272                 //            |
273                 //            v 2
274                 //        [loopback] <--+ 7
275                 //            |         |
276                 //            v 3       |
277                 //   +------[cond]      |
278                 //   |        |         |
279                 //   |        v 5       |
280                 //   |       [pat]      |
281                 //   |        |         |
282                 //   |        v 6       |
283                 //   v 4    [body] -----+
284                 // [expr]
285                 //
286                 // Note that `break` and `continue` statements
287                 // may cause additional edges.
288
289                 let head = self.expr(&**head, pred);             // 1
290                 let loopback = self.add_dummy_node(&[head]);     // 2
291                 let cond = self.add_dummy_node(&[loopback]);     // 3
292                 let expr_exit = self.add_node(expr.id, &[cond]); // 4
293                 self.loop_scopes.push(LoopScope {
294                     loop_id: expr.id,
295                     continue_index: loopback,
296                     break_index: expr_exit,
297                 });
298                 let pat = self.pat(&**pat, cond);               // 5
299                 let body = self.block(&**body, pat);            // 6
300                 self.add_contained_edge(body, loopback);        // 7
301                 self.loop_scopes.pop();
302                 expr_exit
303             }
304
305             ast::ExprLoop(ref body, _) => {
306                 //
307                 //     [pred]
308                 //       |
309                 //       v 1
310                 //   [loopback] <---+
311                 //       |      4   |
312                 //       v 3        |
313                 //     [body] ------+
314                 //
315                 //     [expr] 2
316                 //
317                 // Note that `break` and `loop` statements
318                 // may cause additional edges.
319
320                 let loopback = self.add_dummy_node(&[pred]);              // 1
321                 let expr_exit = self.add_node(expr.id, &[]);              // 2
322                 self.loop_scopes.push(LoopScope {
323                     loop_id: expr.id,
324                     continue_index: loopback,
325                     break_index: expr_exit,
326                 });
327                 let body_exit = self.block(&**body, loopback);           // 3
328                 self.add_contained_edge(body_exit, loopback);            // 4
329                 self.loop_scopes.pop();
330                 expr_exit
331             }
332
333             ast::ExprMatch(ref discr, ref arms, _) => {
334                 //
335                 //     [pred]
336                 //       |
337                 //       v 1
338                 //    [discr]
339                 //       |
340                 //       v 2
341                 //    [cond1]
342                 //      /  \
343                 //     |    \
344                 //     v 3   \
345                 //  [pat1]    \
346                 //     |       |
347                 //     v 4     |
348                 //  [guard1]   |
349                 //     |       |
350                 //     |       |
351                 //     v 5     v
352                 //  [body1]  [cond2]
353                 //     |      /  \
354                 //     |    ...  ...
355                 //     |     |    |
356                 //     v 6   v    v
357                 //  [.....expr.....]
358                 //
359                 let discr_exit = self.expr(&**discr, pred);              // 1
360
361                 let expr_exit = self.add_node(expr.id, &[]);
362                 let mut cond_exit = discr_exit;
363                 for arm in arms.iter() {
364                     cond_exit = self.add_dummy_node(&[cond_exit]);        // 2
365                     let pats_exit = self.pats_any(arm.pats[],
366                                                   cond_exit);            // 3
367                     let guard_exit = self.opt_expr(&arm.guard,
368                                                    pats_exit);           // 4
369                     let body_exit = self.expr(&*arm.body, guard_exit);   // 5
370                     self.add_contained_edge(body_exit, expr_exit);       // 6
371                 }
372                 expr_exit
373             }
374
375             ast::ExprBinary(op, ref l, ref r) if ast_util::lazy_binop(op) => {
376                 //
377                 //     [pred]
378                 //       |
379                 //       v 1
380                 //      [l]
381                 //       |
382                 //      / \
383                 //     /   \
384                 //    v 2  *
385                 //   [r]   |
386                 //    |    |
387                 //    v 3  v 4
388                 //   [..exit..]
389                 //
390                 let l_exit = self.expr(&**l, pred);                      // 1
391                 let r_exit = self.expr(&**r, l_exit);                    // 2
392                 self.add_node(expr.id, &[l_exit, r_exit])                 // 3,4
393             }
394
395             ast::ExprRet(ref v) => {
396                 let v_exit = self.opt_expr(v, pred);
397                 let b = self.add_node(expr.id, &[v_exit]);
398                 self.add_returning_edge(expr, b);
399                 self.add_node(ast::DUMMY_NODE_ID, &[])
400             }
401
402             ast::ExprBreak(label) => {
403                 let loop_scope = self.find_scope(expr, label);
404                 let b = self.add_node(expr.id, &[pred]);
405                 self.add_exiting_edge(expr, b,
406                                       loop_scope, loop_scope.break_index);
407                 self.add_node(ast::DUMMY_NODE_ID, &[])
408             }
409
410             ast::ExprAgain(label) => {
411                 let loop_scope = self.find_scope(expr, label);
412                 let a = self.add_node(expr.id, &[pred]);
413                 self.add_exiting_edge(expr, a,
414                                       loop_scope, loop_scope.continue_index);
415                 self.add_node(ast::DUMMY_NODE_ID, &[])
416             }
417
418             ast::ExprVec(ref elems) => {
419                 self.straightline(expr, pred, elems.iter().map(|e| &**e))
420             }
421
422             ast::ExprCall(ref func, ref args) => {
423                 self.call(expr, pred, &**func, args.iter().map(|e| &**e))
424             }
425
426             ast::ExprMethodCall(_, _, ref args) => {
427                 self.call(expr, pred, &*args[0], args.slice_from(1).iter().map(|e| &**e))
428             }
429
430             ast::ExprIndex(ref l, ref r) |
431             ast::ExprBinary(_, ref l, ref r) if self.is_method_call(expr) => {
432                 self.call(expr, pred, &**l, Some(&**r).into_iter())
433             }
434
435             ast::ExprRange(ref start, ref end) => {
436                 let fields = start.as_ref().map(|e| &**e).into_iter()
437                     .chain(end.as_ref().map(|e| &**e).into_iter());
438                 self.straightline(expr, pred, fields)
439             }
440
441             ast::ExprUnary(_, ref e) if self.is_method_call(expr) => {
442                 self.call(expr, pred, &**e, None::<ast::Expr>.iter())
443             }
444
445             ast::ExprTup(ref exprs) => {
446                 self.straightline(expr, pred, exprs.iter().map(|e| &**e))
447             }
448
449             ast::ExprStruct(_, ref fields, ref base) => {
450                 let field_cfg = self.straightline(expr, pred, fields.iter().map(|f| &*f.expr));
451                 self.opt_expr(base, field_cfg)
452             }
453
454             ast::ExprRepeat(ref elem, ref count) => {
455                 self.straightline(expr, pred, [elem, count].iter().map(|&e| &**e))
456             }
457
458             ast::ExprAssign(ref l, ref r) |
459             ast::ExprAssignOp(_, ref l, ref r) => {
460                 self.straightline(expr, pred, [r, l].iter().map(|&e| &**e))
461             }
462
463             ast::ExprBox(Some(ref l), ref r) |
464             ast::ExprIndex(ref l, ref r) |
465             ast::ExprBinary(_, ref l, ref r) => { // NB: && and || handled earlier
466                 self.straightline(expr, pred, [l, r].iter().map(|&e| &**e))
467             }
468
469             ast::ExprBox(None, ref e) |
470             ast::ExprAddrOf(_, ref e) |
471             ast::ExprCast(ref e, _) |
472             ast::ExprUnary(_, ref e) |
473             ast::ExprParen(ref e) |
474             ast::ExprField(ref e, _) |
475             ast::ExprTupField(ref e, _) => {
476                 self.straightline(expr, pred, Some(&**e).into_iter())
477             }
478
479             ast::ExprInlineAsm(ref inline_asm) => {
480                 let inputs = inline_asm.inputs.iter();
481                 let outputs = inline_asm.outputs.iter();
482                 let post_inputs = self.exprs(inputs.map(|a| {
483                     debug!("cfg::construct InlineAsm id:{} input:{}", expr.id, a);
484                     let &(_, ref expr) = a;
485                     &**expr
486                 }), pred);
487                 let post_outputs = self.exprs(outputs.map(|a| {
488                     debug!("cfg::construct InlineAsm id:{} output:{}", expr.id, a);
489                     let &(_, ref expr, _) = a;
490                     &**expr
491                 }), post_inputs);
492                 self.add_node(expr.id, &[post_outputs])
493             }
494
495             ast::ExprMac(..) |
496             ast::ExprClosure(..) |
497             ast::ExprLit(..) |
498             ast::ExprPath(..) => {
499                 self.straightline(expr, pred, None::<ast::Expr>.iter())
500             }
501         }
502     }
503
504     fn call<'b, I: Iterator<Item=&'b ast::Expr>>(&mut self,
505             call_expr: &ast::Expr,
506             pred: CFGIndex,
507             func_or_rcvr: &ast::Expr,
508             args: I) -> CFGIndex {
509         let method_call = ty::MethodCall::expr(call_expr.id);
510         let return_ty = ty::ty_fn_ret(match self.tcx.method_map.borrow().get(&method_call) {
511             Some(method) => method.ty,
512             None => ty::expr_ty_adjusted(self.tcx, func_or_rcvr)
513         });
514
515         let func_or_rcvr_exit = self.expr(func_or_rcvr, pred);
516         let ret = self.straightline(call_expr, func_or_rcvr_exit, args);
517         if return_ty == ty::FnDiverging {
518             self.add_node(ast::DUMMY_NODE_ID, &[])
519         } else {
520             ret
521         }
522     }
523
524     fn exprs<'b, I: Iterator<Item=&'b ast::Expr>>(&mut self,
525                                              exprs: I,
526                                              pred: CFGIndex) -> CFGIndex {
527         //! Constructs graph for `exprs` evaluated in order
528         exprs.fold(pred, |p, e| self.expr(e, p))
529     }
530
531     fn opt_expr(&mut self,
532                 opt_expr: &Option<P<ast::Expr>>,
533                 pred: CFGIndex) -> CFGIndex {
534         //! Constructs graph for `opt_expr` evaluated, if Some
535         opt_expr.iter().fold(pred, |p, e| self.expr(&**e, p))
536     }
537
538     fn straightline<'b, I: Iterator<Item=&'b ast::Expr>>(&mut self,
539                     expr: &ast::Expr,
540                     pred: CFGIndex,
541                     subexprs: I) -> CFGIndex {
542         //! Handles case of an expression that evaluates `subexprs` in order
543
544         let subexprs_exit = self.exprs(subexprs, pred);
545         self.add_node(expr.id, &[subexprs_exit])
546     }
547
548     fn add_dummy_node(&mut self, preds: &[CFGIndex]) -> CFGIndex {
549         self.add_node(ast::DUMMY_NODE_ID, preds)
550     }
551
552     fn add_node(&mut self, id: ast::NodeId, preds: &[CFGIndex]) -> CFGIndex {
553         assert!(!self.exit_map.contains_key(&id));
554         let node = self.graph.add_node(CFGNodeData {id: id});
555         if id != ast::DUMMY_NODE_ID {
556             assert!(!self.exit_map.contains_key(&id));
557             self.exit_map.insert(id, node);
558         }
559         for &pred in preds.iter() {
560             self.add_contained_edge(pred, node);
561         }
562         node
563     }
564
565     fn add_contained_edge(&mut self,
566                           source: CFGIndex,
567                           target: CFGIndex) {
568         let data = CFGEdgeData {exiting_scopes: vec!() };
569         self.graph.add_edge(source, target, data);
570     }
571
572     fn add_exiting_edge(&mut self,
573                         from_expr: &ast::Expr,
574                         from_index: CFGIndex,
575                         to_loop: LoopScope,
576                         to_index: CFGIndex) {
577         let mut data = CFGEdgeData {exiting_scopes: vec!() };
578         let mut scope = CodeExtent::from_node_id(from_expr.id);
579         let target_scope = CodeExtent::from_node_id(to_loop.loop_id);
580         while scope != target_scope {
581
582             data.exiting_scopes.push(scope.node_id());
583             scope = self.tcx.region_maps.encl_scope(scope);
584         }
585         self.graph.add_edge(from_index, to_index, data);
586     }
587
588     fn add_returning_edge(&mut self,
589                           _from_expr: &ast::Expr,
590                           from_index: CFGIndex) {
591         let mut data = CFGEdgeData {
592             exiting_scopes: vec!(),
593         };
594         for &LoopScope { loop_id: id, .. } in self.loop_scopes.iter().rev() {
595             data.exiting_scopes.push(id);
596         }
597         self.graph.add_edge(from_index, self.fn_exit, data);
598     }
599
600     fn find_scope(&self,
601                   expr: &ast::Expr,
602                   label: Option<ast::Ident>) -> LoopScope {
603         match label {
604             None => {
605                 return *self.loop_scopes.last().unwrap();
606             }
607
608             Some(_) => {
609                 match self.tcx.def_map.borrow().get(&expr.id) {
610                     Some(&def::DefLabel(loop_id)) => {
611                         for l in self.loop_scopes.iter() {
612                             if l.loop_id == loop_id {
613                                 return *l;
614                             }
615                         }
616                         self.tcx.sess.span_bug(
617                             expr.span,
618                             format!("no loop scope for id {}",
619                                     loop_id)[]);
620                     }
621
622                     r => {
623                         self.tcx.sess.span_bug(
624                             expr.span,
625                             format!("bad entry `{}` in def_map for label",
626                                     r)[]);
627                     }
628                 }
629             }
630         }
631     }
632
633     fn is_method_call(&self, expr: &ast::Expr) -> bool {
634         let method_call = ty::MethodCall::expr(expr.id);
635         self.tcx.method_map.borrow().contains_key(&method_call)
636     }
637 }