]> git.lizzy.rs Git - rust.git/blob - src/librustc/cfg/construct.rs
Check for uninhabitedness instead of never
[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::DeclKind::Local(ref local) => {
130                 let init_exit = self.opt_expr(&local.init, pred);
131                 self.pat(&local.pat, init_exit)
132             }
133
134             hir::DeclKind::Item(_) => 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::ExprKind::Block(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::ExprKind::If(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::ExprKind::If(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::ExprKind::While(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::ExprKind::Loop(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::ExprKind::Match(ref discr, ref arms, _) => {
299                 self.match_(expr.hir_id.local_id, &discr, &arms, pred)
300             }
301
302             hir::ExprKind::Binary(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::ExprKind::Ret(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::ExprKind::Break(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::ExprKind::Continue(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::ExprKind::Array(ref elems) => {
347                 self.straightline(expr, pred, elems.iter().map(|e| &*e))
348             }
349
350             hir::ExprKind::Call(ref func, ref args) => {
351                 self.call(expr, pred, &func, args.iter().map(|e| &*e))
352             }
353
354             hir::ExprKind::MethodCall(.., ref args) => {
355                 self.call(expr, pred, &args[0], args[1..].iter().map(|e| &*e))
356             }
357
358             hir::ExprKind::Index(ref l, ref r) |
359             hir::ExprKind::Binary(_, 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::ExprKind::Unary(_, ref e) if self.tables.is_method_call(expr) => {
364                 self.call(expr, pred, &e, None::<hir::Expr>.iter())
365             }
366
367             hir::ExprKind::Tup(ref exprs) => {
368                 self.straightline(expr, pred, exprs.iter().map(|e| &*e))
369             }
370
371             hir::ExprKind::Struct(_, 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::ExprKind::Assign(ref l, ref r) |
377             hir::ExprKind::AssignOp(_, ref l, ref r) => {
378                 self.straightline(expr, pred, [r, l].iter().map(|&e| &**e))
379             }
380
381             hir::ExprKind::Index(ref l, ref r) |
382             hir::ExprKind::Binary(_, ref l, ref r) => { // N.B., && and || handled earlier
383                 self.straightline(expr, pred, [l, r].iter().map(|&e| &**e))
384             }
385
386             hir::ExprKind::Box(ref e) |
387             hir::ExprKind::AddrOf(_, ref e) |
388             hir::ExprKind::Cast(ref e, _) |
389             hir::ExprKind::Type(ref e, _) |
390             hir::ExprKind::Unary(_, ref e) |
391             hir::ExprKind::Field(ref e, _) |
392             hir::ExprKind::Yield(ref e) |
393             hir::ExprKind::Repeat(ref e, _) => {
394                 self.straightline(expr, pred, Some(&**e).into_iter())
395             }
396
397             hir::ExprKind::InlineAsm(_, 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::ExprKind::Closure(..) |
404             hir::ExprKind::Lit(..) |
405             hir::ExprKind::Path(_) => {
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         if self.tables.expr_ty(call_expr).conservative_is_uninhabited() {
419             self.add_unreachable_node()
420         } else {
421             ret
422         }
423     }
424
425     fn exprs<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
426                                              exprs: I,
427                                              pred: CFGIndex) -> CFGIndex {
428         //! Constructs graph for `exprs` evaluated in order
429         exprs.fold(pred, |p, e| self.expr(e, p))
430     }
431
432     fn opt_expr(&mut self,
433                 opt_expr: &Option<P<hir::Expr>>,
434                 pred: CFGIndex) -> CFGIndex {
435         //! Constructs graph for `opt_expr` evaluated, if Some
436         opt_expr.iter().fold(pred, |p, e| self.expr(&e, p))
437     }
438
439     fn straightline<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
440                     expr: &hir::Expr,
441                     pred: CFGIndex,
442                     subexprs: I) -> CFGIndex {
443         //! Handles case of an expression that evaluates `subexprs` in order
444
445         let subexprs_exit = self.exprs(subexprs, pred);
446         self.add_ast_node(expr.hir_id.local_id, &[subexprs_exit])
447     }
448
449     fn match_(&mut self, id: hir::ItemLocalId, discr: &hir::Expr,
450               arms: &[hir::Arm], pred: CFGIndex) -> CFGIndex {
451         // The CFG for match expression is quite complex, so no ASCII
452         // art for it (yet).
453         //
454         // The CFG generated below matches roughly what MIR contains.
455         // Each pattern and guard is visited in parallel, with
456         // arms containing multiple patterns generating multiple nodes
457         // for the same guard expression. The guard expressions chain
458         // into each other from top to bottom, with a specific
459         // exception to allow some additional valid programs
460         // (explained below). MIR differs slightly in that the
461         // pattern matching may continue after a guard but the visible
462         // behaviour should be the same.
463         //
464         // What is going on is explained in further comments.
465
466         // Visit the discriminant expression
467         let discr_exit = self.expr(discr, pred);
468
469         // Add a node for the exit of the match expression as a whole.
470         let expr_exit = self.add_ast_node(id, &[]);
471
472         // Keep track of the previous guard expressions
473         let mut prev_guards = Vec::new();
474
475         for arm in arms {
476             // Add an exit node for when we've visited all the
477             // patterns and the guard (if there is one) in the arm.
478             let arm_exit = self.add_dummy_node(&[]);
479
480             for pat in &arm.pats {
481                 // Visit the pattern, coming from the discriminant exit
482                 let mut pat_exit = self.pat(&pat, discr_exit);
483
484                 // If there is a guard expression, handle it here
485                 if let Some(ref guard) = arm.guard {
486                     // Add a dummy node for the previous guard
487                     // expression to target
488                     let guard_start = self.add_dummy_node(&[pat_exit]);
489                     // Visit the guard expression
490                     let guard_exit = match guard {
491                         hir::Guard::If(ref e) => self.expr(e, 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 {
559             id: from_expr.hir_id.local_id,
560             data: region::ScopeData::Node
561         };
562         let region_scope_tree = self.tcx.region_scope_tree(self.owner_def_id);
563         while scope != target_scope {
564             data.exiting_scopes.push(scope.item_local_id());
565             scope = region_scope_tree.encl_scope(scope);
566         }
567         self.graph.add_edge(from_index, to_index, data);
568     }
569
570     fn add_returning_edge(&mut self,
571                           _from_expr: &hir::Expr,
572                           from_index: CFGIndex) {
573         let data = CFGEdgeData {
574             exiting_scopes: self.loop_scopes.iter()
575                                             .rev()
576                                             .map(|&LoopScope { loop_id: id, .. }| id)
577                                             .collect()
578         };
579         self.graph.add_edge(from_index, self.fn_exit, data);
580     }
581
582     fn find_scope_edge(&self,
583                   expr: &hir::Expr,
584                   destination: hir::Destination,
585                   scope_cf_kind: ScopeCfKind) -> (region::Scope, CFGIndex) {
586
587         match destination.target_id {
588             Ok(loop_id) => {
589                 for b in &self.breakable_block_scopes {
590                     if b.block_expr_id == self.tcx.hir().node_to_hir_id(loop_id).local_id {
591                         let scope = region::Scope {
592                             id: self.tcx.hir().node_to_hir_id(loop_id).local_id,
593                             data: region::ScopeData::Node
594                         };
595                         return (scope, match scope_cf_kind {
596                             ScopeCfKind::Break => b.break_index,
597                             ScopeCfKind::Continue => bug!("can't continue to block"),
598                         });
599                     }
600                 }
601                 for l in &self.loop_scopes {
602                     if l.loop_id == self.tcx.hir().node_to_hir_id(loop_id).local_id {
603                         let scope = region::Scope {
604                             id: self.tcx.hir().node_to_hir_id(loop_id).local_id,
605                             data: region::ScopeData::Node
606                         };
607                         return (scope, match scope_cf_kind {
608                             ScopeCfKind::Break => l.break_index,
609                             ScopeCfKind::Continue => l.continue_index,
610                         });
611                     }
612                 }
613                 span_bug!(expr.span, "no scope for id {}", loop_id);
614             }
615             Err(err) => span_bug!(expr.span, "scope error: {}",  err),
616         }
617     }
618 }
619
620 #[derive(Copy, Clone, Eq, PartialEq)]
621 enum ScopeCfKind {
622     Break,
623     Continue,
624 }