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