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