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