]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/graphviz.rs
rustc: split off BodyOwnerKind from MirSource.
[rust.git] / src / librustc_mir / util / graphviz.rs
1 // Copyright 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 dot;
12 use rustc::hir::def_id::DefId;
13 use rustc::mir::*;
14 use rustc::ty::TyCtxt;
15 use std::fmt::Debug;
16 use std::io::{self, Write};
17
18 use rustc_data_structures::indexed_vec::Idx;
19
20 use super::pretty::dump_mir_def_ids;
21
22 /// Write a graphviz DOT graph of a list of MIRs.
23 pub fn write_mir_graphviz<'tcx, W>(tcx: TyCtxt<'_, '_, 'tcx>,
24                                    single: Option<DefId>,
25                                    w: &mut W)
26                                    -> io::Result<()>
27     where W: Write
28 {
29     for def_id in dump_mir_def_ids(tcx, single) {
30         let mir = &tcx.optimized_mir(def_id);
31         write_mir_fn_graphviz(tcx, def_id, mir, w)?;
32     }
33     Ok(())
34 }
35
36 /// Write a graphviz DOT graph of the MIR.
37 pub fn write_mir_fn_graphviz<'tcx, W>(tcx: TyCtxt<'_, '_, 'tcx>,
38                                       def_id: DefId,
39                                       mir: &Mir,
40                                       w: &mut W) -> io::Result<()>
41     where W: Write
42 {
43     writeln!(w, "digraph Mir_{} {{", tcx.hir.as_local_node_id(def_id).unwrap())?;
44
45     // Global graph properties
46     writeln!(w, r#"    graph [fontname="monospace"];"#)?;
47     writeln!(w, r#"    node [fontname="monospace"];"#)?;
48     writeln!(w, r#"    edge [fontname="monospace"];"#)?;
49
50     // Graph label
51     write_graph_label(tcx, def_id, mir, w)?;
52
53     // Nodes
54     for (block, _) in mir.basic_blocks().iter_enumerated() {
55         write_node(block, mir, w)?;
56     }
57
58     // Edges
59     for (source, _) in mir.basic_blocks().iter_enumerated() {
60         write_edges(source, mir, w)?;
61     }
62     writeln!(w, "}}")
63 }
64
65 /// Write a graphviz HTML-styled label for the given basic block, with
66 /// all necessary escaping already performed. (This is suitable for
67 /// emitting directly, as is done in this module, or for use with the
68 /// LabelText::HtmlStr from libgraphviz.)
69 ///
70 /// `init` and `fini` are callbacks for emitting additional rows of
71 /// data (using HTML enclosed with `<tr>` in the emitted text).
72 pub fn write_node_label<W: Write, INIT, FINI>(block: BasicBlock,
73                                               mir: &Mir,
74                                               w: &mut W,
75                                               num_cols: u32,
76                                               init: INIT,
77                                               fini: FINI) -> io::Result<()>
78     where INIT: Fn(&mut W) -> io::Result<()>,
79           FINI: Fn(&mut W) -> io::Result<()>
80 {
81     let data = &mir[block];
82
83     write!(w, r#"<table border="0" cellborder="1" cellspacing="0">"#)?;
84
85     // Basic block number at the top.
86     write!(w, r#"<tr><td {attrs} colspan="{colspan}">{blk}</td></tr>"#,
87            attrs=r#"bgcolor="gray" align="center""#,
88            colspan=num_cols,
89            blk=block.index())?;
90
91     init(w)?;
92
93     // List of statements in the middle.
94     if !data.statements.is_empty() {
95         write!(w, r#"<tr><td align="left" balign="left">"#)?;
96         for statement in &data.statements {
97             write!(w, "{}<br/>", escape(statement))?;
98         }
99         write!(w, "</td></tr>")?;
100     }
101
102     // Terminator head at the bottom, not including the list of successor blocks. Those will be
103     // displayed as labels on the edges between blocks.
104     let mut terminator_head = String::new();
105     data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
106     write!(w, r#"<tr><td align="left">{}</td></tr>"#, dot::escape_html(&terminator_head))?;
107
108     fini(w)?;
109
110     // Close the table
111     writeln!(w, "</table>")
112 }
113
114 /// Write a graphviz DOT node for the given basic block.
115 fn write_node<W: Write>(block: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
116     // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables.
117     write!(w, r#"    {} [shape="none", label=<"#, node(block))?;
118     write_node_label(block, mir, w, 1, |_| Ok(()), |_| Ok(()))?;
119     // Close the node label and the node itself.
120     writeln!(w, ">];")
121 }
122
123 /// Write graphviz DOT edges with labels between the given basic block and all of its successors.
124 fn write_edges<W: Write>(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
125     let terminator = mir[source].terminator();
126     let labels = terminator.kind.fmt_successor_labels();
127
128     for (&target, label) in terminator.successors().iter().zip(labels) {
129         writeln!(w, r#"    {} -> {} [label="{}"];"#, node(source), node(target), label)?;
130     }
131
132     Ok(())
133 }
134
135 /// Write the graphviz DOT label for the overall graph. This is essentially a block of text that
136 /// will appear below the graph, showing the type of the `fn` this MIR represents and the types of
137 /// all the variables and temporaries.
138 fn write_graph_label<'a, 'gcx, 'tcx, W: Write>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
139                                                def_id: DefId,
140                                                mir: &Mir,
141                                                w: &mut W)
142                                                -> io::Result<()> {
143     write!(w, "    label=<fn {}(", dot::escape_html(&tcx.item_path_str(def_id)))?;
144
145     // fn argument types.
146     for (i, arg) in mir.args_iter().enumerate() {
147         if i > 0 {
148             write!(w, ", ")?;
149         }
150         write!(w, "{:?}: {}", Lvalue::Local(arg), escape(&mir.local_decls[arg].ty))?;
151     }
152
153     write!(w, ") -&gt; {}", escape(mir.return_ty))?;
154     write!(w, r#"<br align="left"/>"#)?;
155
156     for local in mir.vars_and_temps_iter() {
157         let decl = &mir.local_decls[local];
158
159         write!(w, "let ")?;
160         if decl.mutability == Mutability::Mut {
161             write!(w, "mut ")?;
162         }
163
164         if let Some(name) = decl.name {
165             write!(w, r#"{:?}: {}; // {}<br align="left"/>"#,
166                    Lvalue::Local(local), escape(&decl.ty), name)?;
167         } else {
168             write!(w, r#"let mut {:?}: {};<br align="left"/>"#,
169                    Lvalue::Local(local), escape(&decl.ty))?;
170         }
171     }
172
173     writeln!(w, ">;")
174 }
175
176 fn node(block: BasicBlock) -> String {
177     format!("bb{}", block.index())
178 }
179
180 fn escape<T: Debug>(t: &T) -> String {
181     dot::escape_html(&format!("{:?}", t))
182 }