use rustc_graphviz as dot;
use rustc_hir::def_id::DefId;
use rustc_index::vec::Idx;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;
use std::fmt::Debug;
use std::io::{self, Write};
use super::pretty::dump_mir_def_ids;
pub fn write_mir_graphviz<W>(tcx: TyCtxt<'_>, single: Option<DefId>, w: &mut W) -> io::Result<()>
where
W: Write,
{
let def_ids = dump_mir_def_ids(tcx, single);
let use_subgraphs = def_ids.len() > 1;
if use_subgraphs {
writeln!(w, "digraph __crate__ {{")?;
}
for def_id in def_ids {
let body = &tcx.optimized_mir(def_id);
write_mir_fn_graphviz(tcx, def_id, body, use_subgraphs, w)?;
}
if use_subgraphs {
writeln!(w, "}}")?;
}
Ok(())
}
pub fn graphviz_safe_def_name(def_id: DefId) -> String {
format!("{}_{}", def_id.krate.index(), def_id.index.index(),)
}
pub fn write_mir_fn_graphviz<'tcx, W>(
tcx: TyCtxt<'tcx>,
def_id: DefId,
body: &Body<'_>,
subgraph: bool,
w: &mut W,
) -> io::Result<()>
where
W: Write,
{
let kind = if subgraph { "subgraph" } else { "digraph" };
let cluster = if subgraph { "cluster_" } else { "" };
let def_name = graphviz_safe_def_name(def_id);
writeln!(w, "{} {}Mir_{} {{", kind, cluster, def_name)?;
writeln!(w, r#" graph [fontname="monospace"];"#)?;
writeln!(w, r#" node [fontname="monospace"];"#)?;
writeln!(w, r#" edge [fontname="monospace"];"#)?;
write_graph_label(tcx, def_id, body, w)?;
for (block, _) in body.basic_blocks().iter_enumerated() {
write_node(def_id, block, body, w)?;
}
for (source, _) in body.basic_blocks().iter_enumerated() {
write_edges(def_id, source, body, w)?;
}
writeln!(w, "}}")
}
pub fn write_node_label<W: Write, INIT, FINI>(
block: BasicBlock,
body: &Body<'_>,
w: &mut W,
num_cols: u32,
init: INIT,
fini: FINI,
) -> io::Result<()>
where
INIT: Fn(&mut W) -> io::Result<()>,
FINI: Fn(&mut W) -> io::Result<()>,
{
let data = &body[block];
write!(w, r#"<table border="0" cellborder="1" cellspacing="0">"#)?;
write!(
w,
r#"<tr><td {attrs} colspan="{colspan}">{blk}</td></tr>"#,
attrs = r#"bgcolor="gray" align="center""#,
colspan = num_cols,
blk = block.index()
)?;
init(w)?;
if !data.statements.is_empty() {
write!(w, r#"<tr><td align="left" balign="left">"#)?;
for statement in &data.statements {
write!(w, "{}<br/>", escape(statement))?;
}
write!(w, "</td></tr>")?;
}
let mut terminator_head = String::new();
data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
write!(w, r#"<tr><td align="left">{}</td></tr>"#, dot::escape_html(&terminator_head))?;
fini(w)?;
write!(w, "</table>")
}
fn write_node<W: Write>(
def_id: DefId,
block: BasicBlock,
body: &Body<'_>,
w: &mut W,
) -> io::Result<()> {
write!(w, r#" {} [shape="none", label=<"#, node(def_id, block))?;
write_node_label(block, body, w, 1, |_| Ok(()), |_| Ok(()))?;
writeln!(w, ">];")
}
fn write_edges<W: Write>(
def_id: DefId,
source: BasicBlock,
body: &Body<'_>,
w: &mut W,
) -> io::Result<()> {
let terminator = body[source].terminator();
let labels = terminator.kind.fmt_successor_labels();
for (&target, label) in terminator.successors().zip(labels) {
let src = node(def_id, source);
let trg = node(def_id, target);
writeln!(w, r#" {} -> {} [label="{}"];"#, src, trg, label)?;
}
Ok(())
}
fn write_graph_label<'tcx, W: Write>(
tcx: TyCtxt<'tcx>,
def_id: DefId,
body: &Body<'_>,
w: &mut W,
) -> io::Result<()> {
write!(w, " label=<fn {}(", dot::escape_html(&tcx.def_path_str(def_id)))?;
for (i, arg) in body.args_iter().enumerate() {
if i > 0 {
write!(w, ", ")?;
}
write!(w, "{:?}: {}", Place::from(arg), escape(&body.local_decls[arg].ty))?;
}
write!(w, ") -> {}", escape(&body.return_ty()))?;
write!(w, r#"<br align="left"/>"#)?;
for local in body.vars_and_temps_iter() {
let decl = &body.local_decls[local];
write!(w, "let ")?;
if decl.mutability == Mutability::Mut {
write!(w, "mut ")?;
}
write!(w, r#"{:?}: {};<br align="left"/>"#, Place::from(local), escape(&decl.ty))?;
}
for var_debug_info in &body.var_debug_info {
write!(
w,
r#"debug {} => {};<br align="left"/>"#,
var_debug_info.name,
escape(&var_debug_info.place)
)?;
}
writeln!(w, ">;")
}
fn node(def_id: DefId, block: BasicBlock) -> String {
format!("bb{}__{}", block.index(), graphviz_safe_def_name(def_id))
}
fn escape<T: Debug>(t: &T) -> String {
dot::escape_html(&format!("{:?}", t))
}