blob: 282292a2ac09ce52796390f042d2f08748d7da6a [file] [log] [blame]
Niko Matsakis86b6e6e2013-05-10 17:10:351// Copyright 2012 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
11use middle::cfg::*;
12use middle::graph;
13use middle::typeck;
14use middle::ty;
15use std::hashmap::HashMap;
16use syntax::ast;
17use syntax::ast_util;
18use syntax::opt_vec;
19
20struct CFGBuilder {
21 tcx: ty::ctxt,
22 method_map: typeck::method_map,
Michael Woerister8a329772013-07-27 08:25:5923 exit_map: HashMap<ast::NodeId, CFGIndex>,
Niko Matsakis86b6e6e2013-05-10 17:10:3524 graph: CFGGraph,
25 loop_scopes: ~[LoopScope],
26}
27
28struct LoopScope {
Michael Woerister8a329772013-07-27 08:25:5929 loop_id: ast::NodeId, // id of loop/while node
Niko Matsakis86b6e6e2013-05-10 17:10:3530 continue_index: CFGIndex, // where to go on a `loop`
31 break_index: CFGIndex, // where to go on a `break
32}
33
34pub fn construct(tcx: ty::ctxt,
35 method_map: typeck::method_map,
Michael Woerister4bd14242013-07-19 05:38:5536 blk: &ast::Block) -> CFG {
Niko Matsakis86b6e6e2013-05-10 17:10:3537 let mut cfg_builder = CFGBuilder {
38 exit_map: HashMap::new(),
39 graph: graph::Graph::new(),
40 tcx: tcx,
41 method_map: method_map,
42 loop_scopes: ~[]
43 };
44 let entry = cfg_builder.add_node(0, []);
45 let exit = cfg_builder.block(blk, entry);
46 let CFGBuilder {exit_map, graph, _} = cfg_builder;
47 CFG {exit_map: exit_map,
48 graph: graph,
49 entry: entry,
50 exit: exit}
51}
52
53impl CFGBuilder {
Michael Woerister4bd14242013-07-19 05:38:5554 fn block(&mut self, blk: &ast::Block, pred: CFGIndex) -> CFGIndex {
Niko Matsakis86b6e6e2013-05-10 17:10:3555 let mut stmts_exit = pred;
Daniel Micay100894552013-08-03 16:45:2356 for &stmt in blk.stmts.iter() {
Niko Matsakis86b6e6e2013-05-10 17:10:3557 stmts_exit = self.stmt(stmt, stmts_exit);
58 }
59
Michael Woerister0cc70742013-07-16 18:08:3560 let expr_exit = self.opt_expr(blk.expr, stmts_exit);
Niko Matsakis86b6e6e2013-05-10 17:10:3561
Michael Woerister0cc70742013-07-16 18:08:3562 self.add_node(blk.id, [expr_exit])
Niko Matsakis86b6e6e2013-05-10 17:10:3563 }
64
65 fn stmt(&mut self, stmt: @ast::stmt, pred: CFGIndex) -> CFGIndex {
66 match stmt.node {
67 ast::stmt_decl(decl, _) => {
68 self.decl(decl, pred)
69 }
70
71 ast::stmt_expr(expr, _) | ast::stmt_semi(expr, _) => {
72 self.expr(expr, pred)
73 }
74
75 ast::stmt_mac(*) => {
76 self.tcx.sess.span_bug(stmt.span, "unexpanded macro");
77 }
78 }
79 }
80
81 fn decl(&mut self, decl: @ast::decl, pred: CFGIndex) -> CFGIndex {
82 match decl.node {
83 ast::decl_local(local) => {
Michael Woerister4bd14242013-07-19 05:38:5584 let init_exit = self.opt_expr(local.init, pred);
85 self.pat(local.pat, init_exit)
Niko Matsakis86b6e6e2013-05-10 17:10:3586 }
87
88 ast::decl_item(_) => {
89 pred
90 }
91 }
92 }
93
94 fn pat(&mut self, pat: @ast::pat, pred: CFGIndex) -> CFGIndex {
95 match pat.node {
96 ast::pat_ident(_, _, None) |
97 ast::pat_enum(_, None) |
98 ast::pat_lit(*) |
99 ast::pat_range(*) |
100 ast::pat_wild => {
101 self.add_node(pat.id, [pred])
102 }
103
104 ast::pat_box(subpat) |
105 ast::pat_uniq(subpat) |
106 ast::pat_region(subpat) |
107 ast::pat_ident(_, _, Some(subpat)) => {
108 let subpat_exit = self.pat(subpat, pred);
109 self.add_node(pat.id, [subpat_exit])
110 }
111
112 ast::pat_enum(_, Some(ref subpats)) |
113 ast::pat_tup(ref subpats) => {
114 let pats_exit =
Erick Tryzelaar68f40d22013-08-10 03:09:47115 self.pats_all(subpats.iter().map(|p| *p), pred);
Niko Matsakis86b6e6e2013-05-10 17:10:35116 self.add_node(pat.id, [pats_exit])
117 }
118
119 ast::pat_struct(_, ref subpats, _) => {
120 let pats_exit =
Erick Tryzelaar68f40d22013-08-10 03:09:47121 self.pats_all(subpats.iter().map(|f| f.pat), pred);
Niko Matsakis86b6e6e2013-05-10 17:10:35122 self.add_node(pat.id, [pats_exit])
123 }
124
125 ast::pat_vec(ref pre, ref vec, ref post) => {
126 let pre_exit =
Erick Tryzelaar68f40d22013-08-10 03:09:47127 self.pats_all(pre.iter().map(|p| *p), pred);
Niko Matsakis86b6e6e2013-05-10 17:10:35128 let vec_exit =
Erick Tryzelaar68f40d22013-08-10 03:09:47129 self.pats_all(vec.iter().map(|p| *p), pre_exit);
Niko Matsakis86b6e6e2013-05-10 17:10:35130 let post_exit =
Erick Tryzelaar68f40d22013-08-10 03:09:47131 self.pats_all(post.iter().map(|p| *p), vec_exit);
Niko Matsakis86b6e6e2013-05-10 17:10:35132 self.add_node(pat.id, [post_exit])
133 }
134 }
135 }
136
137 fn pats_all<I: Iterator<@ast::pat>>(&mut self,
138 pats: I,
139 pred: CFGIndex) -> CFGIndex {
140 //! Handles case where all of the patterns must match.
141 let mut pats = pats;
142 pats.fold(pred, |pred, pat| self.pat(pat, pred))
143 }
144
145 fn pats_any(&mut self,
146 pats: &[@ast::pat],
147 pred: CFGIndex) -> CFGIndex {
148 //! Handles case where just one of the patterns must match.
149
150 if pats.len() == 1 {
151 self.pat(pats[0], pred)
152 } else {
153 let collect = self.add_dummy_node([]);
Daniel Micay100894552013-08-03 16:45:23154 for &pat in pats.iter() {
Niko Matsakis86b6e6e2013-05-10 17:10:35155 let pat_exit = self.pat(pat, pred);
156 self.add_contained_edge(pat_exit, collect);
157 }
158 collect
159 }
160 }
161
162 fn expr(&mut self, expr: @ast::expr, pred: CFGIndex) -> CFGIndex {
163 match expr.node {
164 ast::expr_block(ref blk) => {
165 let blk_exit = self.block(blk, pred);
166 self.add_node(expr.id, [blk_exit])
167 }
168
169 ast::expr_if(cond, ref then, None) => {
170 //
171 // [pred]
172 // |
173 // v 1
174 // [cond]
175 // |
176 // / \
177 // / \
178 // v 2 *
179 // [then] |
180 // | |
181 // v 3 v 4
182 // [..expr..]
183 //
184 let cond_exit = self.expr(cond, pred); // 1
185 let then_exit = self.block(then, cond_exit); // 2
186 self.add_node(expr.id, [cond_exit, then_exit]) // 3,4
187 }
188
189 ast::expr_if(cond, ref then, Some(otherwise)) => {
190 //
191 // [pred]
192 // |
193 // v 1
194 // [cond]
195 // |
196 // / \
197 // / \
198 // v 2 v 3
199 // [then][otherwise]
200 // | |
201 // v 4 v 5
202 // [..expr..]
203 //
204 let cond_exit = self.expr(cond, pred); // 1
205 let then_exit = self.block(then, cond_exit); // 2
206 let else_exit = self.expr(otherwise, cond_exit); // 3
207 self.add_node(expr.id, [then_exit, else_exit]) // 4, 5
208 }
209
210 ast::expr_while(cond, ref body) => {
211 //
212 // [pred]
213 // |
214 // v 1
215 // [loopback] <--+ 5
216 // | |
217 // v 2 |
218 // +-----[cond] |
219 // | | |
220 // | v 4 |
221 // | [body] -----+
222 // v 3
223 // [expr]
224 //
225 // Note that `break` and `loop` statements
226 // may cause additional edges.
227
Michael Sullivan7dbc5ae2013-07-30 23:47:22228 // Is the condition considered part of the loop?
Niko Matsakis86b6e6e2013-05-10 17:10:35229 let loopback = self.add_dummy_node([pred]); // 1
230 let cond_exit = self.expr(cond, loopback); // 2
231 let expr_exit = self.add_node(expr.id, [cond_exit]); // 3
232 self.loop_scopes.push(LoopScope {
233 loop_id: expr.id,
234 continue_index: loopback,
235 break_index: expr_exit
236 });
237 let body_exit = self.block(body, cond_exit); // 4
238 self.add_contained_edge(body_exit, loopback); // 5
239 expr_exit
240 }
241
Graydon Hoarec29e9fb2013-07-30 00:25:00242 ast::expr_for_loop(*) => fail!("non-desugared expr_for_loop"),
243
Niko Matsakis86b6e6e2013-05-10 17:10:35244 ast::expr_loop(ref body, _) => {
245 //
246 // [pred]
247 // |
248 // v 1
249 // [loopback] <---+
250 // | 4 |
251 // v 3 |
252 // [body] ------+
253 //
254 // [expr] 2
255 //
256 // Note that `break` and `loop` statements
257 // may cause additional edges.
258
259 let loopback = self.add_dummy_node([pred]); // 1
260 let expr_exit = self.add_node(expr.id, []); // 2
261 self.loop_scopes.push(LoopScope {
262 loop_id: expr.id,
263 continue_index: loopback,
264 break_index: expr_exit,
265 });
266 let body_exit = self.block(body, loopback); // 3
267 self.add_contained_edge(body_exit, loopback); // 4
268 self.loop_scopes.pop();
269 expr_exit
270 }
271
272 ast::expr_match(discr, ref arms) => {
273 //
274 // [pred]
275 // |
276 // v 1
277 // [discr]
278 // |
279 // v 2
280 // [guard1]
281 // / \
282 // | \
283 // v 3 |
284 // [pat1] |
285 // |
286 // v 4 |
287 // [body1] v
288 // | [guard2]
289 // | / \
290 // | [body2] \
291 // | | ...
292 // | | |
293 // v 5 v v
294 // [....expr....]
295 //
296 let discr_exit = self.expr(discr, pred); // 1
297
298 let expr_exit = self.add_node(expr.id, []);
299 let mut guard_exit = discr_exit;
Daniel Micay100894552013-08-03 16:45:23300 for arm in arms.iter() {
Niko Matsakis86b6e6e2013-05-10 17:10:35301 guard_exit = self.opt_expr(arm.guard, guard_exit); // 2
302 let pats_exit = self.pats_any(arm.pats, guard_exit); // 3
303 let body_exit = self.block(&arm.body, pats_exit); // 4
304 self.add_contained_edge(body_exit, expr_exit); // 5
305 }
306 expr_exit
307 }
308
309 ast::expr_binary(_, op, l, r) if ast_util::lazy_binop(op) => {
310 //
311 // [pred]
312 // |
313 // v 1
314 // [l]
315 // |
316 // / \
317 // / \
318 // v 2 *
319 // [r] |
320 // | |
321 // v 3 v 4
322 // [..exit..]
323 //
324 let l_exit = self.expr(l, pred); // 1
325 let r_exit = self.expr(r, l_exit); // 2
326 self.add_node(expr.id, [l_exit, r_exit]) // 3,4
327 }
328
329 ast::expr_ret(v) => {
330 let v_exit = self.opt_expr(v, pred);
331 let loop_scope = self.loop_scopes[0];
332 self.add_exiting_edge(expr, v_exit,
333 loop_scope, loop_scope.break_index);
334 self.add_node(expr.id, [])
335 }
336
337 ast::expr_break(label) => {
338 let loop_scope = self.find_scope(expr, label);
339 self.add_exiting_edge(expr, pred,
340 loop_scope, loop_scope.break_index);
341 self.add_node(expr.id, [])
342 }
343
344 ast::expr_again(label) => {
345 let loop_scope = self.find_scope(expr, label);
346 self.add_exiting_edge(expr, pred,
347 loop_scope, loop_scope.continue_index);
348 self.add_node(expr.id, [])
349 }
350
351 ast::expr_vec(ref elems, _) => {
352 self.straightline(expr, pred, *elems)
353 }
354
355 ast::expr_call(func, ref args, _) => {
356 self.call(expr, pred, func, *args)
357 }
358
359 ast::expr_method_call(_, rcvr, _, _, ref args, _) => {
360 self.call(expr, pred, rcvr, *args)
361 }
362
363 ast::expr_index(_, l, r) |
364 ast::expr_binary(_, _, l, r) if self.is_method_call(expr) => {
365 self.call(expr, pred, l, [r])
366 }
367
368 ast::expr_unary(_, _, e) if self.is_method_call(expr) => {
369 self.call(expr, pred, e, [])
370 }
371
372 ast::expr_tup(ref exprs) => {
373 self.straightline(expr, pred, *exprs)
374 }
375
376 ast::expr_struct(_, ref fields, base) => {
377 let base_exit = self.opt_expr(base, pred);
378 let field_exprs: ~[@ast::expr] =
Erick Tryzelaar68f40d22013-08-10 03:09:47379 fields.iter().map(|f| f.expr).collect();
Niko Matsakis86b6e6e2013-05-10 17:10:35380 self.straightline(expr, base_exit, field_exprs)
381 }
382
383 ast::expr_repeat(elem, count, _) => {
384 self.straightline(expr, pred, [elem, count])
385 }
386
387 ast::expr_assign(l, r) |
388 ast::expr_assign_op(_, _, l, r) => {
389 self.straightline(expr, pred, [r, l])
390 }
391
392 ast::expr_log(l, r) |
393 ast::expr_index(_, l, r) |
394 ast::expr_binary(_, _, l, r) => { // NB: && and || handled earlier
395 self.straightline(expr, pred, [l, r])
396 }
397
398 ast::expr_addr_of(_, e) |
Niko Matsakis86b6e6e2013-05-10 17:10:35399 ast::expr_do_body(e) |
400 ast::expr_cast(e, _) |
401 ast::expr_unary(_, _, e) |
402 ast::expr_paren(e) |
403 ast::expr_vstore(e, _) |
404 ast::expr_field(e, _, _) => {
405 self.straightline(expr, pred, [e])
406 }
407
408 ast::expr_mac(*) |
409 ast::expr_inline_asm(*) |
410 ast::expr_self |
411 ast::expr_fn_block(*) |
412 ast::expr_lit(*) |
413 ast::expr_path(*) => {
414 self.straightline(expr, pred, [])
415 }
416 }
417 }
418
419 fn call(&mut self,
420 call_expr: @ast::expr,
421 pred: CFGIndex,
422 func_or_rcvr: @ast::expr,
423 args: &[@ast::expr]) -> CFGIndex {
424 let func_or_rcvr_exit = self.expr(func_or_rcvr, pred);
425 self.straightline(call_expr, func_or_rcvr_exit, args)
426 }
427
428 fn exprs(&mut self,
429 exprs: &[@ast::expr],
430 pred: CFGIndex) -> CFGIndex {
431 //! Constructs graph for `exprs` evaluated in order
432
433 exprs.iter().fold(pred, |p, &e| self.expr(e, p))
434 }
435
436 fn opt_expr(&mut self,
437 opt_expr: Option<@ast::expr>,
438 pred: CFGIndex) -> CFGIndex {
439 //! Constructs graph for `opt_expr` evaluated, if Some
440
441 opt_expr.iter().fold(pred, |p, &e| self.expr(e, p))
442 }
443
444 fn straightline(&mut self,
445 expr: @ast::expr,
446 pred: CFGIndex,
447 subexprs: &[@ast::expr]) -> CFGIndex {
448 //! Handles case of an expression that evaluates `subexprs` in order
449
450 let subexprs_exit = self.exprs(subexprs, pred);
451 self.add_node(expr.id, [subexprs_exit])
452 }
453
454 fn add_dummy_node(&mut self, preds: &[CFGIndex]) -> CFGIndex {
455 self.add_node(0, preds)
456 }
457
Michael Woerister8a329772013-07-27 08:25:59458 fn add_node(&mut self, id: ast::NodeId, preds: &[CFGIndex]) -> CFGIndex {
Niko Matsakis86b6e6e2013-05-10 17:10:35459 assert!(!self.exit_map.contains_key(&id));
460 let node = self.graph.add_node(CFGNodeData {id: id});
461 self.exit_map.insert(id, node);
Daniel Micay100894552013-08-03 16:45:23462 for &pred in preds.iter() {
Niko Matsakis86b6e6e2013-05-10 17:10:35463 self.add_contained_edge(pred, node);
464 }
465 node
466 }
467
468 fn add_contained_edge(&mut self,
469 source: CFGIndex,
470 target: CFGIndex) {
471 let data = CFGEdgeData {exiting_scopes: opt_vec::Empty};
472 self.graph.add_edge(source, target, data);
473 }
474
475 fn add_exiting_edge(&mut self,
476 from_expr: @ast::expr,
477 from_index: CFGIndex,
478 to_loop: LoopScope,
479 to_index: CFGIndex) {
480 let mut data = CFGEdgeData {exiting_scopes: opt_vec::Empty};
481 let mut scope_id = from_expr.id;
482 while scope_id != to_loop.loop_id {
483 data.exiting_scopes.push(scope_id);
484 scope_id = self.tcx.region_maps.encl_scope(scope_id);
485 }
486 self.graph.add_edge(from_index, to_index, data);
487 }
488
489 fn find_scope(&self,
490 expr: @ast::expr,
491 label: Option<ast::ident>) -> LoopScope {
492 match label {
493 None => {
494 return *self.loop_scopes.last();
495 }
496
497 Some(_) => {
498 match self.tcx.def_map.find(&expr.id) {
499 Some(&ast::def_label(loop_id)) => {
Daniel Micay100894552013-08-03 16:45:23500 for l in self.loop_scopes.iter() {
Niko Matsakis86b6e6e2013-05-10 17:10:35501 if l.loop_id == loop_id {
502 return *l;
503 }
504 }
505 self.tcx.sess.span_bug(
506 expr.span,
507 fmt!("No loop scope for id %?", loop_id));
508 }
509
510 r => {
511 self.tcx.sess.span_bug(
512 expr.span,
513 fmt!("Bad entry `%?` in def_map for label", r));
514 }
515 }
516 }
517 }
518 }
519
520 fn is_method_call(&self, expr: &ast::expr) -> bool {
521 self.method_map.contains_key(&expr.id)
522 }
Patrick Walton99d44d22013-07-10 02:32:09523}